Numpy:将矩阵与 3d 张量相乘——建议 [英] Numpy: Multiplying a matrix with a 3d tensor -- Suggestion
问题描述
我有一个形状为 MxN
的矩阵 P
和一个形状为 KxNxR
的 3d 张量 T
.我想将 P
与 T
中的每个 NxR
矩阵相乘,得到 KxMxR
3d 张量.
I have a matrix P
with shape MxN
and a 3d tensor T
with shape KxNxR
. I want to multiply P
with every NxR
matrix in T
, resulting in a KxMxR
3d tensor.
P.dot(T).transpose(1,0,2)
给出了想要的结果.这个问题有更好的解决方案(即摆脱transpose
)吗?这一定是一个很常见的操作,所以我假设其他人已经找到了不同的方法,例如使用 tensordot
(我尝试过但未能获得所需的结果).意见/观点将不胜感激!
P.dot(T).transpose(1,0,2)
gives the desired result. Is there a nicer solution (i.e. getting rid of transpose
) to this problem? This must be quite a common operation, so I assume, others have found different approaches, e.g. using tensordot
(which I tried but failed to get the desired result). Opinions/Views would be highly appreciated!
推荐答案
scipy.tensordot(P, T, axes=[1,1]).swapaxes(0,1)
这篇关于Numpy:将矩阵与 3d 张量相乘——建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!