What is the best way to compute the trace of a matrix product in numpy?

前端 未结 3 787
甜味超标
甜味超标 2020-12-29 07:40

If I have numpy arrays A and B, then I can compute the trace of their matrix product with:

tr = numpy.linalg.trace(A.dot(B))
         


        
3条回答
  •  执笔经年
    2020-12-29 08:08

    Note that one slight variant is to take the dot product of the vectorized matrices. In python, vectorization is done using .flatten('F'). It's slightly slower than taking the sum of the Hadamard product, on my computer, so it's a worse solution than wflynny's , but I think it's kind of interesting, since it can be more intuitive, in some situations, in my opinion. For example, personally I find that for the matrix normal distribution, the vectorized solution is easier for me to understand.

    Speed comparison, on my system:

    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)
    

    Result:

    6.246593236923218 -629.370798672
    0.06539678573608398 -629.370798672
    0.057890892028808594 -629.370798672
    0.05709719657897949 -629.370798672
    

提交回复
热议问题