Numpy efficient matrix self-multiplication (gram matrix)

前端 未结 2 1293
死守一世寂寞
死守一世寂寞 2020-12-11 04:23

I want to multiply B = A @ A.T in numpy. Obviously, the answer would be a symmetric matrix (i.e. B[i, j] == B[j, i]).

However, it is not cl

相关标签:
2条回答
  • 2020-12-11 04:52

    As noted in @PaulPanzer's link, dot can detect this case. Here's the timing proof:

    In [355]: A = np.random.rand(1000,1000)
    In [356]: timeit A.dot(A.T)
    57.4 ms ± 960 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    In [357]: B = A.T.copy()
    In [358]: timeit A.dot(B)
    98.6 ms ± 805 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

    Numpy dot too clever about symmetric multiplications

    0 讨论(0)
  • 2020-12-11 04:53

    You can always use sklearns's pairwise_distances

    Usage:

    from sklearn.metrics.pairwise import pairwise_distances
    gram = pairwise_distance(x, metric=metric)
    

    Where metric is a callable or a string defining one of their implemented metrics (full list in the link above)


    But, I wrote this for myself a while back so I can share what I did:

    import numpy as np
    
    def computeGram(elements, dist):
        n    = len(elements)
        gram = np.zeros([n, n])
        for i in range(n):
            for j in range(i + 1):
                gram[i, j] = dist(elements[i], elements[j])
    
        upTriIdxs       = np.triu_indices(n)
        gram[upTriIdxs] = gram.T[upTriIdxs]
    
        return gram
    

    Where dist is a callable, in your case np.inner

    0 讨论(0)
提交回复
热议问题