简体   繁体   English

如何在 Python 中使用 numpy 将 3D 矩阵和 2D 矩阵相乘?

[英]How do I multiply a 3D matrix and 2D matrix using numpy in Python?

My 3d array has shape (3, 2, 3), my 2d array is (2, 3).我的 3d 阵列的形状为 (3, 2, 3),我的二维阵列为 (2, 3)。 The multiplication i want to conduct is np.dot(2d, 3d[i,:,:].T) so it should return a result with shape (3, 2, 2).我想要进行的乘法是 np.dot(2d, 3d[i,:,:].T) 所以它应该返回一个形状为 (3, 2, 2) 的结果。 I could write a loop, but it is not the most efficient way, I have read there is an operation called np.tensordot, but would it work for my case?我可以写一个循环,但这不是最有效的方法,我读过有一个名为 np.tensordot 的操作,但它适用于我的情况吗? If yes, how would it work?如果是,它将如何工作?

We can use np.einsum -我们可以使用np.einsum -

# a, b are 3D and 2D arrays respectively
np.einsum('ijk,lk->ilj', a, b)

Alternatively, with np.matmul/@-operator on Python3.x -或者,使用np.matmul/@-operator on Python3.x -

np.matmul(a,b.T[None]).swapaxes(1,2)

You can indeed use tensordot :您确实可以使用tensordot

np.tensordot(a2D,a3D,((-1,),(-1,))).transpose(1,0,2)

or或者

np.tensordot(a3D,a2D,((-1,),(-1,))).transpose(0,2,1)

Disadvantage: as we have to shuffle axes in the end the result arrays will be non-contiguous.缺点:由于我们最终必须对轴进行洗牌,结果 arrays 将是不连续的。 We can avoid this using einsum as shown by @Divakar or matrix multiplication if we do the shuffling before multiplying, ie:如果我们在乘法之前进行改组,我们可以使用einsum所示的 einsum 或矩阵乘法来避免这种情况,即:

a2D@a3D.transpose(0,2,1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM