- 线性代数基本操作
# 求逆,A为张量
A.T
# 张量相乘
A*B
# 相加
A+B
# 求和
A.sum()
# 沿行求和,行为0,列为1
A.sum(axis=0)
# 沿行和列,等同于A.sum()
A.sum(axis=[0,1])
# 求均值,同“求和”
A.mean(axis=0)
# 非降维求和
A.sum(axis=0,keepdims=True)
# 沿轴累积求和
A.cumsum(axis=0)
- 点积
# 两个向量对应元素相乘再求和,等同于 torch.sum(x * y)
# 可以用来做加权平均
x = torch.arange(4,dtype=torch.float32)
y = torch.ones(4,dtype=torch.float32)
x.dot(y)
- 向量积
A = torch.arange(12).reshape(3,4)
x = torch.tensor([2,3,4,5])
torch.mv(A,x)   # tensor([ 6, 22, 38])
- 矩阵乘法
A = torch.randn(5,4)
B = torch.randn(4,3)
torch.mm(A,B)
- 范数
# L2范数: 假设维向量中的元素是x1,x2,x3...,其范数是向量元素平方和的平方根,同矩阵的Frobenius范数
u = torch.tensor([3.0, -4.0])
torch.norm(u)  # tensor(5.)
# L1范数:它表示为向量元素的绝对值之和
torch.abs(u).sum()