0
0
0
5.转置
2026-10-14
文章摘要
|
第4课:转置(Transpose)
1. 定义
转置就是把矩阵的行和列互换
- 原矩阵位置
(i,j)→ 转置后放到(j,i) - 符号:A^T
只针对二维矩阵,高维张量的转置会更灵活,后面再说。
示例
A=\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{bmatrix}_{2\times3}
2行3列
转置 A^T:3行2列
A^T=\begin{bmatrix}
1 & 4 \\
2 & 5 \\
3 & 6
\end{bmatrix}_{3\times2}
重点:原shape (2,3) → 转置后shape (3,2)
2. 两个重要性质(AI里常用)
- (A^T)^T = A 转置两次变回自己
- (A @ B)^T = B^T @ A^T
矩阵乘积转置,顺序要颠倒!这个后面反向传播会用到。
3. Numpy代码实操
import numpy as np
A = np.array([[1,2,3],
[4,5,6]])
print("原矩阵A:")
print(A)
print("A shape:", A.shape)
A_T = A.T
print("\n转置 A.T:")
print(A_T)
print("A_T shape:", A_T.shape)
# 转置两次
A_TT = A_T.T
print("\n转置两次:")
print(A_TT)
运行观察:行变列,列变行。
4. 高维张量转置(PyTorch常用)
二维矩阵用 .T,三维及以上张量要用 transpose(维度1,维度2),交换指定两个维度
举个例子:张量 shape=(C, H, W) 通道、高、宽
import numpy as np
# 张量 shape=(3,28,28)
img = np.random.rand(3,28,28)
# 交换0维和2维
img2 = img.transpose(0,2)
print(img.shape)
print(img2.shape)
原shape (3,28,28) → transpose(0,2) → (28,28,3)
这个操作在图像预处理超级常见:把
CHW格式转为HWC
5. 小练习题
A shape=(4,6)
- A转置后的shape是多少?
- 如果 B shape=(6,2),A@B 的shape?(A@B)^T 的shape?
做完告诉我答案,我们下一课:向量点积。
答案先不看,自己算:
- (6,4)
- A@B shape=(4,2);(A@B)^T shape=(2,4)
