矩阵是”变换机器”
标量乘法 3 x 5 = 15 只是把一个数放大 3 倍。要对一个二维点进行缩放、旋转、镜像,一个数字不够用,需要矩阵。
矩阵乘以向量 = 对该点执行一次变换:
import numpy as np
A = np.array([[2, 0],
[0, 2]]) # 缩放矩阵
x = np.array([2, 3]) # 原始点 (2, 3)
print(A @ x) # [4, 6] -> 放大 2 倍
常见变换矩阵
缩放(Scaling):
[sx 0 ] 把 x 缩放 sx 倍
[0 sy] 把 y 缩放 sy 倍
旋转 angle(Rotation):
[cos a -sin a]
[sin a cos a]
逆时针旋转 90 度:
import math
theta = math.pi / 2
R = np.array([[math.cos(theta), -math.sin(theta)],
[math.sin(theta), math.cos(theta)]])
x = np.array([1, 0])
print(R @ x) # [0, 1] — (1,0) 逆时针旋转到 (0,1)
镜像(y 轴翻转):
[-1 0]
[ 0 1]
为什么矩阵乘法是那个规则
[1 2] [5] = [1x5 + 2x6] = [17]
[3 4] x [6] [3x5 + 4x6] [39]
不是人为规定,而是”两次变换合并”的自然结果:矩阵的每一行定义输出的一个维度,该维度由输入向量的线性组合得出。
矩阵乘法 = 变换的复合
两个矩阵连乘等于先做 B 变换再做 A 变换:
A = np.array([[2, 0], [0, 2]]) # 放大 2 倍
B = np.array([[0, -1], [1, 0]]) # 旋转 90 度
C = A @ B # 先旋转再缩放
x = np.array([1, 0])
print(C @ x) # [0, 2]
神经网络中的矩阵
全连接层(Linear 层)的本质就是矩阵乘法加偏置:
output = W x input + b
一个隐藏层有 128 个神经元、输入维度为 64:
import torch
import torch.nn as nn
linear = nn.Linear(64, 128)
# 内部持有 weight: Tensor (128, 64) 和 bias: Tensor (128,)
x = torch.randn(32, 64) # batch_size=32, input_dim=64
y = linear(x) # y.shape = (32, 128)
每一层做的都是:把输入向量从一个向量空间线性映射到另一个向量空间。激活函数(ReLU、Sigmoid 等)引入非线性,才让网络能拟合复杂函数。
PyTorch 矩阵运算
import torch
A = torch.tensor([[1., 2.], [3., 4.]])
B = torch.tensor([[5., 6.], [7., 8.]])
# 矩阵乘法
print(A @ B) # torch.matmul
print(torch.mm(A, B)) # 二维矩阵专用
# 转置
print(A.T)
# 行列式
print(torch.det(A)) # -2.0
# 逆矩阵
print(torch.inverse(A))
高维 Tensor = 批量矩阵运算
深度学习中输入通常是 3D 以上的 Tensor(batch x dim):
# batch matmul:对每个样本独立做矩阵乘法
A = torch.randn(32, 4, 4) # 32 个 4x4 矩阵
B = torch.randn(32, 4, 1) # 32 个列向量
C = torch.bmm(A, B) # (32, 4, 1)
torch.bmm 对 batch 中每个矩阵独立相乘,是卷积、Attention 等操作的底层基础。
