本文均为基于torch实现,用于入门者学习
import torch
生成一个矩阵打乱并求逆
a = torch.randperm(25).reshape(-1,5).float()
torch.linalg.inv(a)
- 注意:这里必须要转成浮点数
矩阵对应元素相乘与矩阵相乘
A = torch.arange(20).reshape(5,4)
B = A.T
print(A*A) #对应元素相乘
print(A@B) #矩阵乘法
求均值
A = A.float()
B = B.float()
A.mean(),a.sum()/a.numel()
- 注意:有关sum,mean等操作均要求对象是浮点数
- numel的意思是number of element
A.mean(dim = 0)
A.sum(dim = 0)/A.shape[0]
- 按列求和,求出来是一个行向量
A.mean(axis = 1).reshape(-1,1)
- 按行求和,求出来是一个列向量
- reshape(-1,1),第二个1指摆一列,第一个-1指自动计算行数