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
?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With