import numpy as np
a = np.array([[2], [2]])
b = np.array([[3, 4, 5], [3, 4, 5]])
c = np.array([[1, 2], [1, 2]])
print('点乘结果:\n', a*b)
print('叉乘结果:\n', c.dot(b)) # np.dot(c, b)
import torch
a = torch.tensor([[1, 2], [1, 2]]) # 2*2
b = torch.tensor([[3, 4, 5], [3, 4, 5]]) # 2*3
c = torch.tensor([[5, 6, 7, 8], [5, 6, 7, 8], [5, 6, 7, 8]]) # 3*4
def matrix_mul(*matrix):
for ind, i in enumerate(matrix):
# 只用单位阵乘第一个矩阵
if ind == 0:
out = torch.eye(matrix[0].shape[0])
out = torch.mm(out, i.float())
return out
print('matrix_mul函数结果:\n', matrix_mul(a, b, c) )
print('torch.mm函数结果:\n', torch.mm(torch.mm(a, b), c))
numpy完成多个矩阵的叉乘,可以参考上述torch的方法;
torch的点乘直接用*
或者torch.mul
、torch.multiply
a = torch.tensor([[2], [2]]) # 2*2
b = torch.tensor([[3, 4, 5], [3, 4, 5]]) # 2*3
torch.multiply(a, b)
torch.mul(a, b)