Pytorch 语法
pytorch 初始化向量/张量
torch.normal(均值, 标准差, 形状)
torch.zero(row, col) 全0向量
torch.ones(row, col) 全1向量
torch.rand(row, col) 随机均匀分布[0, 1)
torch.matmul(a, b) 矩阵乘法
等价于:\(y = X w + b\)
y.reshape((-1, 1)) -> 变成列向量
-1表示自动计算行数1表示1列
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
关键字参数
x.sum(...)/torch.sum(x, ...) 求和
torch.sum(x, dim=1),dim代表要消除掉的维度,keep_dim代表是否保持形状
广播机制
pytorch的广播机制是右对齐
(32, 256) + (256, )
->(32, 256) + (32, 256) 行
(32, 256) + (32)
->(32, 256) + (xx, 32) 不行
(32, 256) + (32, 1)
->(32, 256) + (32, 1) 行
高级索引
# 1. 整数数组索引
res = y[[0,1], [0,2]]
# [y[0][0], y[1][2]]
# 2. 布尔索引
x = torch.tensor([[1, 2], [3, 4], [5, 6]])
mask = x > 3
res = x[mask]
# mask: tensor([[F, F], [T, T], [T, T]])
# res: tensor([4, 5, 6]) 筛选为1维向量
# 3. 混合逻辑
x = torch.arange(12).reshape(3, 4)
res = x[:2, [1,3]]
矩阵乘法 @
reshape
zeros_like(X)
生成形状一样的全零张量