Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant expression for row-wise dot product of two matrices

Tags:

python

numpy

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)

Is there another way to do this so that numpy is doing the row-wise dot product in one step rather than two? Maybe with tensordot?

like image 385
Neil G Avatar asked Oct 02 '14 19:10

Neil G


1 Answers

Even faster is inner1d from numpy.core.umath_tests:

enter image description here


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
        )
like image 164
Nico Schlömer Avatar answered Nov 05 '22 10:11

Nico Schlömer