我试图仅使用张量、点和整形等来实现与 np.matmul 并行矩阵乘法相同的行为。
我要翻译的库没有支持并行乘法的 matmul,只有点和张量。
此外,我想避免迭代第一个维度,并希望使用一组矩阵乘法和 reshape 来完成此操作(希望尽可能多地使用 BLAS/GPU 运行,因为我有大量的小矩阵要计算)并行)。
这是一个例子:
import numpy as np
angles = np.array([np.pi/4, 2*np.pi/4, 2*np.pi/4])
vectors = np.array([ [1,0],[1,-1],[-1,0]])
s = np.sin(angles)
c = np.cos(angles)
rotations = np.array([[c,s],[-s,c]]).T
print rotations
print vectors
print("Correct: %s" % np.matmul(rotations, vectors.reshape(3,2,1)))
# I want to do this using tensordot/reshaping, i.e just gemm BLAS operations underneath
print("Wrong: %s" % np.tensordot(rotations, vectors, axes=(1,1)))
其输出是:
Correct: [[[ 7.07106781e-01]
[ 7.07106781e-01]]
[[ 1.00000000e+00]
[ 1.00000000e+00]]
[[ -6.12323400e-17]
[ -1.00000000e+00]]]
Wrong: [[[ 7.07106781e-01 1.11022302e-16 -7.07106781e-01]
[ -7.07106781e-01 -1.41421356e+00 7.07106781e-01]]
[[ 6.12323400e-17 -1.00000000e+00 -6.12323400e-17]
[ -1.00000000e+00 -1.00000000e+00 1.00000000e+00]]
[[ 6.12323400e-17 -1.00000000e+00 -6.12323400e-17]
[ -1.00000000e+00 -1.00000000e+00 1.00000000e+00]]]
有没有一种方法可以修改第二个表达式,以便仅使用 dot/tensordot 获得与第一个表达式相同的结果。
我相信这是可能的,并且已经看到some comments online ,但从来没有任何例子
最佳答案
我们需要保持其中一个对齐并将其也保持在输出处。因此,tensordot/dot 在这里不起作用。 More info on tensordot
可能会以某种方式解释为什么它不会。但是,我们可以使用 np.einsum
,在大多数情况下(根据我的经验),这被认为比 np.matmul
稍快。
实现看起来像这样 -
np.einsum('ijk,ik->ij',rotations, vectors)
此外,似乎所需的输出有一个尾随的单例暗淡。因此,在其中附加一个新轴 None/np.newaxis
,如下所示 -
np.einsum('ijk,ik->ij',rotations, vectors)[...,None]
关于python - 使用tensordot实现批量矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46285163/