[英]Apply matrix dot between a list of matrices and a list of vectors in Numpy
假设我有这两个变量
matrices = np.random.rand(4,3,3)
vectors = np.random.rand(4,3,1)
我想要执行的是以下内容:
dot_products = [matrix @ vector for (matrix,vector) in zip(matrices,vectors)]
因此,我尝试使用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
是否可以使用提到的 Numpy 方法来实现这些多个点积? 如果没有,还有其他方法可以使用 Numpy 来完成吗?
@
的文档位于np.matmul
。 它专为这种“批处理”而设计:
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
tensordot
的几个问题。 axes
参数指定对哪些维度求和,“dotted”,在您的情况下,它将是matrices
的最后一个和vectors
的第二个到最后一个。 这是标准的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)
您尝试指定 2 对轴进行求和。 dot/tensordot
在其他维度上也做了一种outer product
。 您必须在 4 上采用“对角线”。 tensordot
不是你想要的这个操作。
我们可以使用einsum
更明确地了解维度:
In [83]: np.einsum('ijk,ikl->ijl',matrices, vectors).shape
Out[83]: (4, 3, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.