如何计算numpy中两个矩阵的外积? [英] How to compute the outer product of two matrices in numpy?
本文介绍了如何计算numpy中两个矩阵的外积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在numpy中有效地实现这一点? 所有尺寸都很大,因此不能选择循环.
解决方案
使用循环版本中迭代器的文字翻译作为np.einsum
的字符串表示法,我们将获得解决方案-
np.einsum('ik,jk->ijk',A,B)
样品运行-
In [2]: N,K,M = 3,4,5
In [3]: A = np.random.rand(N,K)
In [4]: B = np.random.rand(M,K)
In [5]: np.einsum('ik,jk->ijk',A,B).shape
Out[5]: (3, 5, 4)
In [6]: (N,M,K)
Out[6]: (3, 5, 4)
I have two matrices A and B of size NxK and MxK respectively. I wish to compute a tensor C of size NxMxK such that C(i,j,k) = A(i,k)*B(j,k).
How can I implement this efficiently in numpy? All the dimensions are large, and hence, looping isn't an option.
解决方案
Using a literal translation of the iterators from the loopy version as string notation with np.einsum
, we would have the solution -
np.einsum('ik,jk->ijk',A,B)
Sample run -
In [2]: N,K,M = 3,4,5
In [3]: A = np.random.rand(N,K)
In [4]: B = np.random.rand(M,K)
In [5]: np.einsum('ik,jk->ijk',A,B).shape
Out[5]: (3, 5, 4)
In [6]: (N,M,K)
Out[6]: (3, 5, 4)
这篇关于如何计算numpy中两个矩阵的外积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文