[英]python: Multiply slice i of a matrix stack by column i of a matrix efficiently
import numpy as np
M,N,R = 2,3,4
# For a 3-dimensional array A:
A = np.reshape(np.r_[0:M*N*R], [M,N,R], order = 'C')
# and 2-dimensional array B:
B = np.reshape(np.r_[0:M*R], [R,M], order = 'C')
I would like the N*M
matrix that results from multiplying slice i
of A
by column i
of B
. 我想
N*M
矩阵,从乘以切片导致i
的A
通过柱i
的B
。 I have tried np.dot
, and np.einsum
and have been unable to obtain what I need. 我已经尝试过
np.dot
和np.einsum
,但是无法获得我所需要的。
Could anybody help, please? 有人可以帮忙吗? Thanks!
谢谢!
With np.einsum
, we would have - 使用
np.einsum
,我们将-
np.einsum('ijk,ki->ji',A,B)
Let's verify the results using the given sample and using matrix-multiplication with np.dot
- 让我们使用给定的样本并使用
np.dot
与矩阵相乘来验证结果-
In [35]: A.shape
Out[35]: (2, 3, 4)
In [36]: B.shape
Out[36]: (4, 2)
In [37]: A[0].dot(B[:,0])
Out[37]: array([ 28, 76, 124])
In [38]: A[1].dot(B[:,1])
Out[38]: array([226, 290, 354])
In [39]: np.einsum('ijk,ki->ji',A,B)
Out[39]:
array([[ 28, 226],
[ 76, 290],
[124, 354]])
For aspects related to when to use einsum
over dot-based
tools like np.dot
/ np.tensordot
, here's a related post
. 对于有关何时使用方面
einsum
了dot-based
的工具,如np.dot
/ np.tensordot
,这里有一个related post
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.