在 Numpy 中的矩阵列表和向量列表之间应用矩阵点

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。它是专门为这种'batch'处理而设计的:

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 参数指定对哪些维度求和,“虚线”,在您的情况下,它将是 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)