如果我有 numpy 数组 A
和 B
,那么我可以计算它们矩阵乘积的迹:
tr = numpy.linalg.trace(A.dot(B))
然而,矩阵乘法 A.dot(B)
不必要地计算矩阵乘积中的所有非对角线元素,当在迹线中仅使用对角线元素时。相反,我可以做类似的事情:
tr = 0.0
for i in range(n):
tr += A[i, :].dot(B[:, i])
但这会在 Python 代码中执行循环,并且不像 numpy.linalg.trace
那样明显。
有没有更好的方法来计算 numpy 数组的矩阵乘积的迹?最快或最惯用的方法是什么?
最佳答案
您可以通过减少对角线元素的中间存储来改进@Bill 的解决方案:
from numpy.core.umath_tests import inner1d
m, n = 1000, 500
a = np.random.rand(m, n)
b = np.random.rand(n, m)
# They all should give the same result
print np.trace(a.dot(b))
print np.sum(a*b.T)
print np.sum(inner1d(a, b.T))
%timeit np.trace(a.dot(b))
10 loops, best of 3: 34.7 ms per loop
%timeit np.sum(a*b.T)
100 loops, best of 3: 4.85 ms per loop
%timeit np.sum(inner1d(a, b.T))
1000 loops, best of 3: 1.83 ms per loop
另一种选择是使用 np.einsum
并且根本没有明确的中间存储:
# Will print the same as the others:
print np.einsum('ij,ji->', a, b)
在我的系统上,它的运行速度比使用 inner1d
稍慢,但它可能不适用于所有系统,请参阅 this question :
%timeit np.einsum('ij,ji->', a, b)
100 loops, best of 3: 1.91 ms per loop
关于python - 在 numpy 中计算矩阵积的轨迹的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18854425/