[英]Numpy matrix multiplication with array of matrices
I have several numpy arrays that I would like to multiply (using dot
, so matrix multiplication). 我有几个要乘的numpy数组(使用
dot
,所以是矩阵乘法)。 I'd like to put them all into a numpy array, but I can't figure out how to do it. 我想将它们全部放入一个numpy数组中,但是我不知道该怎么做。
Eg 例如
a = np.random.randn((10,2,2))
b = np.random.randn((10,2))
So I have 10 2x2 matrices (a) and 10 2x1 matrices (b). 所以我有10个2x2矩阵(a)和10个2x1矩阵(b)。 What I could do is this:
我能做的是:
c = np.zeros((10,2))
for i in range(10):
c[i] = np.dot(a[i,:,:],b[i,:])
You get the idea. 你明白了。
But I feel like there's a usage of dot
or tensordot
or something that would do this in one line really easily. 但是我感觉好像
dot
或tensordot
量dot
的用法,或者可以很容易地在一行中做到这一点的东西。 I just can't make sense of the dot
and tensordot
functions for >2 dimensions like this. 我只是无法理解> 2维这样的
dot
和tensordot
dot
函数。
You could use np.einsum
: 您可以使用
np.einsum
:
c = np.einsum('ijk,ik->ij', a, b)
einsum
performs a sum of products. einsum
执行产品的总和。 Since matrix multiplication is a sum of products, any matrix multiplication can be expressed using einsum
. 由于矩阵乘法是乘积之和,因此可以使用
einsum
表示任何矩阵乘法。 It is based on Einstein summation notation . 它基于爱因斯坦求和符号 。
The first argument to einsum, ijk,ik->ij
is a string of subscripts
. einsum的第一个参数
ijk,ik->ij
是一串下subscripts
。 ijk
declares that a
has three axes which are denoted by i
, j
, and k
. ijk
声明a
具有三个轴,分别由i
, j
和k
。
ik
, similarly, declares that the axes of b
will be denoted i
and k
. ik
类似地声明b
的轴将表示为i
和k
。
When the subscripts repeat, those axes are locked together for purposes of summation. 下标重复时,出于求和的目的,这些轴被锁定在一起。 The part of the subscript that follows the
->
shows the axes which will remain after summation. 下标
->
显示了求和后将保留的轴。
Since the k appears on the left (of the ->
) but disappears on the right, there is summation over k
. 由于k出现在(
->
的左侧)但消失在右侧,因此存在k
总和。 It means that the sum 这意味着总和
c_ij = sum over k ( a_ijk * b_ik )
should be computed. 应该计算。 Since this sum can be computed for each
i
and j
, the result is an array with subscripts i
and j
. 由于可以为每个
i
和j
计算该和,因此结果是一个带有下标i
和j
的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.