矩阵基础计算
A = torch.arange(12).reshape(4,3)
print(A)
# 转置
print(A.T)
# 对称矩阵
B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
print(B)
print(B == B.T) #
# 克隆
A = torch.arange(12, dtype=torch.float32).reshape(3, 4)
B = A.clone()
print(A)
print(B)
与矩阵相关
# 矩阵加法
print(A + B)
# 对位乘法
print(A * B)
# 矩阵乘法
A = torch.arange(12, dtype=torch.float32).reshape(3, 4)
B = torch.ones(4, 3)
print(A)
print(B)
ab_mm = torch.mm(B, A)
print(ab_mm)
print(A.shape, B.shape, ab_mm.shape)
求和
> 全值求和
X = torch.arange(4, dtype=torch.float32)
print(X)
print(X.sum())
> 维度求和
# 0维度求和
A = torch.arange(12).reshape(3, 2, 2)
print(A)
a_sum_axis0 = A.sum(axis=0)
print(a_sum_axis0.shape)
print(a_sum_axis0)
# 1维度求和
a_sum_axis1 = A.sum(axis=1)
print(A)
print(a_sum_axis1.shape)
print(a_sum_axis1)
> 组合维度求和
# 组合维度
a_sum_axis01 = A.sum(axis=[0, 1])
print(A)
print(a_sum_axis01.shape)
print(a_sum_axis01)
> 维度保持求和
# 求和保持维度
A = torch.arange(12, dtype=torch.float32).reshape(3, 4)
sum_A = A.sum(axis=1 , keepdims=True)
print(A)
print(sum_A.shape)
print(sum_A)
> 累加求和
A = torch.arange(12, dtype=torch.float32).reshape(3, 4)
# 累加求和
print(A.cumsum(axis=1))
范数
A = torch.ones(3, 4)
print(A)
print(torch.norm(A))