[SciPy-User] Dot product of two arrays of vectors

Alexander Kalinin alec.kalinin@gmail....
Thu Oct 4 08:16:04 CDT 2012


Angus,

Thank you for the interesting solution! But for large arrays
np.diag(np.dot(a, b.T)) is more slower the sum:

 import time

import numpy as np


 M = 10

N = 3000

a = np.random.rand(N, 3)

b = np.random.rand(N, 3)


t0 = time.time()

for i in range(M):

np.sum(a * b, axis = 1).reshape(-1, 1)

t1 = time.time()

print "{:.3f} s.".format(t1 - t0)


t0 = time.time()

for i in range(M):

np.diag(np.dot(a, b.T))

t1 = time.time()

print "{:.3f} s.".format(t1 - t0)


Output is:

0.001 s.
0.915 s.


Sincerely,
Alexander

On Thu, Oct 4, 2012 at 4:53 PM, Angus McMorland <amcmorl@gmail.com> wrote:

> On 4 October 2012 07:25, Alexander Kalinin <alec.kalinin@gmail.com> wrote:
> > Hello, SciPy,
> >
> > Could you, please, explain me, what is the most standard way in NumPy to
> > calculate a dot product of two arrays of vectors, like in MatLab? For
> > example, consider two numpy arrays of vectors:
> >
> > a = np.array([[1, 2, 3], [4, 5, 6]])
> > b = np.array([[3, 2, 1], [6, 5, 4]])
> >
> > For the cross product we have convenient function numpy.cross:
> >>>> np.cross(a, b)
> > array([[ -4,   8,  -4],
> >        [-10,  20, -10]])
> >
> > But the numpy.dot product for the arrays of vectors do the matrix
> > multiplication:
> >>>> np.dot(a, b)
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> > ValueError: objects are not aligned
> >
> > Yes, I can emulate the dot product code like:
> >
> > np.sum(a * b, axis = 1).reshape(-1, 1)
> >
> > but may be there is exist more standard way to do the dot product?
>
> >From the docstring of dot:
>
> "For N dimensions it is a sum product over the last axis of `a` and
> the second-to-last of `b`::
>
>     dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])"
>
> meaning that you want to do
>
> np.dot(a, b.T).
>
> This gives you the dot product of all combinations of vectors (not
> just row-wise) between a and b:
>
> array([[10, 28],
>        [28, 73]]).
>
> You can extract just the row-wise dot products using diag:
>
> In: np.diag(np.dot(a, b.T))
> Out: array([10, 73])
>
> which is still faster than the summing and reshaping solution.
>
> In: %timeit np.sum(a * b, axis = 1).reshape(-1, 1)
> 100000 loops, best of 3: 5.24 us per loop
>
> In: %timeit np.diag(np.dot(a, b.T))
> 100000 loops, best of 3: 4.21 us per loop
>
> I hope that helps.
>
> Angus
> --
> AJC McMorland
> Post-doctoral research fellow
> Neurobiology, University of Pittsburgh
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20121004/71d5a053/attachment.html 


More information about the SciPy-User mailing list