在numpy中计算矩阵乘积轨迹的最佳方法是什么?

时间:2013-09-17 15:53:45

标签: python numpy matrix

如果我有numpy数组AB,那么我可以用以下方法计算其矩阵乘积的跟踪:

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数组矩阵乘积的轨迹?什么是最快或最惯用的方式?

3 个答案:

答案 0 :(得分:11)

您可以通过将中间存储减少到对角线元素来改进@ 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

答案 1 :(得分:10)

wikipedia你可以使用hammard产品计算跟踪(逐元素乘法):

# Tr(A.B)
tr = (A*B.T).sum()

我认为这比执行numpy.trace(A.dot(B))的计算量少。

编辑:

跑一些计时器。这种方式比使用numpy.trace要快得多。

In [37]: timeit("np.trace(A.dot(B))", setup="""import numpy as np;
A, B = np.random.rand(1000,1000), np.random.rand(1000,1000)""", number=100)
Out[38]: 8.6434469223022461

In [39]: timeit("(A*B.T).sum()", setup="""import numpy as np;
A, B = np.random.rand(1000,1000), np.random.rand(1000,1000)""", number=100)
Out[40]: 0.5516049861907959

答案 2 :(得分:0)

请注意,一个轻微的变体是采用vec托管矩阵的点积。在python中,使用.flatten('F')完成矢量化。它比在我的电脑上使用Hadamard产品的总和稍慢,所以它比wflynny的解决方案更糟,但我认为它有点有趣,因为它可以在某些情况下,在我看来更直观。例如,我个人发现,对于矩阵正态分布,矢量化解决方案对我来说更容易理解。

速度比较,在我的系统上:

import numpy as np
import time

N = 1000

np.random.seed(123)
A = np.random.randn(N, N)
B = np.random.randn(N, N)

tart = time.time()
for i in range(10):
    C = np.trace(A.dot(B))
print(time.time() - start, C)

start = time.time()
for i in range(10):
    C = A.flatten('F').dot(B.T.flatten('F'))
print(time.time() - start, C)

start = time.time()
for i in range(10):
    C = (A.T * B).sum()
print(time.time() - start, C)

start = time.time()
for i in range(10):
    C = (A * B.T).sum()
print(time.time() - start, C)

结果:

6.246593236923218 -629.370798672
0.06539678573608398 -629.370798672
0.057890892028808594 -629.370798672
0.05709719657897949 -629.370798672
相关问题