在PyTorch / Numpy中,如何将矩阵的行与3-D张量中的“矩阵”相乘?

时间:2019-06-01 23:58:22

标签: numpy pytorch

例如,a = torch.Tensor([[1,2],[3,4]])(对于numpy来说只是a = np.array([[1,2],[3,4]]))和b = torch.ones((2,2,2))

我想用两个a矩阵乘积2x2的每一行,并得到一个新的矩阵[[3,3],[7,7]](即[1,2]*[[1,1],[1,1]]=[3,3][3,4]*[[1,1],[1,1]]=[7,7]) 。有可能实现这一目标吗?谢谢!

2 个答案:

答案 0 :(得分:0)

您可以只使用常规矩阵乘法a @ b

a = np.array([[1,2],[3,4]])
b = np.ones((2,2,2))

print(a @ b)

输出:

[[[3. 3.]
  [7. 7.]]

 [[3. 3.]
  [7. 7.]]]

结果的每个“行”(即第一个索引)将是一个单独的2 x 2矩阵:

print((a @ b)[1])

输出:

[[3. 3.]
 [7. 7.]]

答案 1 :(得分:0)

我认为这是一个丑陋的解决方案,但这也许就是您想要实现的目标:

a = torch.Tensor([[1,2],[3,4]])
b = torch.ones((2,2,2))

A = torch.mm(a[0].view(-1, 2), b[0])
B = torch.mm(a[1].view(-1, 2), b[1])
res = torch.cat([A, B], dim=0)
print(res)

输出:

tensor([[3., 3.],
        [7., 7.]])