在 numpy dot(...)
中功能documentation据说:
If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
这与 matmul(...)
明显不同函数,其中最后两个维度上的矩阵乘积简单地沿第一个维度广播(如果矩阵超过 2 个维度)。
然而,虽然 matmul 行为的实用性很明显,但我想知道 dot(...)
给出的结果可能有哪些应用。对于二维以上的矩阵。有没有实际应用dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
有用吗?
最佳答案
我不记得有任何关于为什么选择这种方法的讨论。可能只是为了计算方便。它的局限性导致了 einsum
和后来的 matmul
的发展。
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
einsum 等价
np.einsum('ijl,klm->ijkm', a, b)
通过转置和 reshape ,它可以写成
np.einsum('pl,lo', A, B) # p=ij, o=km
然后可以将 A
,B
传递给传统的 BLAS 函数。该功能甚至可能内置到 BLAS 中。
关于python - 超过 2 维的 numpy 点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73544747/