Elegant expression for row-wise dot product of two matrices

后端 未结 3 2072
生来不讨喜
生来不讨喜 2021-02-08 07:27

I have two 2-d numpy arrays with the same dimensions, A and B, and am trying to calculate the row-wise dot product of them. I could do:

np.sum(A * B, axis=1)
         


        
3条回答
  •  一整个雨季
    2021-02-08 08:00

    Even faster is inner1d from numpy.core.umath_tests:


    Code to reproduce the plot:

    import numpy
    from numpy.core.umath_tests import inner1d
    import perfplot
    
    
    perfplot.show(
            setup=lambda n: (numpy.random.rand(n, 3), numpy.random.rand(n, 3)),
            kernels=[
                lambda a: numpy.sum(a[0]*a[1], axis=1),
                lambda a: numpy.einsum('ij, ij->i', a[0], a[1]),
                lambda a: inner1d(a[0], a[1])
                ],
            labels=['sum', 'einsum', 'inner1d'],
            n_range=[2**k for k in range(20)],
            xlabel='len(a), len(b)',
            logx=True,
            logy=True
            )
    

提交回复
热议问题