简体   繁体   中英

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). The multiplication i want to conduct is np.dot(2d, 3d[i,:,:].T) so it should return a result with shape (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? If yes, how would it work?

We can use 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(a,b.T[None]).swapaxes(1,2)

You can indeed use 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. We can avoid this using einsum as shown by @Divakar or matrix multiplication if we do the shuffling before multiplying, ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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