[英]Apply matrix dot between a list of matrices and a list of vectors in Numpy
Let's suppose I have these two variables假设我有这两个变量
matrices = np.random.rand(4,3,3)
vectors = np.random.rand(4,3,1)
What I would like to perform is the following:我想要执行的是以下内容:
dot_products = [matrix @ vector for (matrix,vector) in zip(matrices,vectors)]
Therefore, I've tried using the np.tensordot
method, which at first seemed to make sense, but this happened when testing因此,我尝试使用
np.tensordot
方法,起初这似乎是有道理的,但是在测试时发生了这种情况
>>> np.tensordot(matrices,vectors,axes=([-2,-1],[-2,-1]))
...
ValueError: shape-mismatch for sum
>>> np.tensordot(matrices,vectors,axes=([-2,-1]))
...
ValueError: shape-mismatch for sum
Is it possible to achieve these multiple dot products with the mentioned Numpy method?是否可以使用提到的 Numpy 方法来实现这些多个点积? If not, is there another way that I can accomplish this using Numpy?
如果没有,还有其他方法可以使用 Numpy 来完成吗?
The documentation for @
is found at np.matmul
. @
的文档位于np.matmul
。 It is specifically designed for this kind of 'batch' processing:它专为这种“批处理”而设计:
In [76]: matrices = np.random.rand(4,3,3)
...: vectors = np.random.rand(4,3,1)
In [77]: dot_products = [matrix @ vector for (matrix,vector) in zip(matrices,vectors)]
In [79]: np.array(dot_products).shape
Out[79]: (4, 3, 1)
In [80]: (matrices @ vectors).shape
Out[80]: (4, 3, 1)
In [81]: np.allclose(np.array(dot_products), matrices@vectors)
Out[81]: True
A couple of problems with tensordot
. tensordot
的几个问题。 The axes
parameter specify which dimensions are summed, "dotted", In your case it would be the last of matrices
and 2nd to the last of vectors
. axes
参数指定对哪些维度求和,“dotted”,在您的情况下,它将是matrices
的最后一个和vectors
的第二个到最后一个。 That's the standard dot
paring.这是标准的
dot
配对。
In [82]: np.dot(matrices, vectors).shape
Out[82]: (4, 3, 4, 1)
In [84]: np.tensordot(matrices, vectors, (-1,-2)).shape
Out[84]: (4, 3, 4, 1)
You tried to specify 2 pairs of axes for summing.您尝试指定 2 对轴进行求和。 Also
dot/tensordot
does a kind of outer product
on the other dimensions. dot/tensordot
在其他维度上也做了一种outer product
。 You'd have to take the "diagonal" on the 4's.您必须在 4 上采用“对角线”。
tensordot
is not what you want for this operation. tensordot
不是你想要的这个操作。
We can be more explicit about the dimensions with einsum
:我们可以使用
einsum
更明确地了解维度:
In [83]: np.einsum('ijk,ikl->ijl',matrices, vectors).shape
Out[83]: (4, 3, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.