# [Numpy-discussion] simple reduction question

Charles R Harris charlesr.harris at gmail.com
Wed Dec 24 14:21:40 EST 2014

On Wed, Dec 24, 2014 at 10:29 AM, <josef.pktd at gmail.com> wrote:

>
>
> On Wed, Dec 24, 2014 at 10:30 AM, Julian Taylor <
>
>> On 24.12.2014 16:25, Neal Becker wrote:
>> > What would be the most efficient way to compute:
>> >
>> > c[j] = \sum_i (a[i] * b[i,j])
>> >
>> > where a[i] is a 1-d vector, b[i,j] is a 2-d array?
>> >
>> > This seems to be one way:
>> >
>> > import numpy as np
>> > a = np.arange (3)
>> > b = np.arange (12).reshape (3,4)
>> > c = np.dot (a, b).sum()
>> >
>> > but np.dot returns a vector, which then needs further reduction.  Don't
>> know if
>> > there's a better way.
>> >
>>
>> the formula maps nice to einsum:
>>
>> np.einsum("i,ij->", a, b)
>>
>> should also be reasonably efficient, but that probably depends on your
>> BLAS library and the sizes of the arrays.
>>
>
> hijacking a bit since I was just trying to replicate various
> multidimensional dot products with einsum
>
> Are the older timings for einsum still a useful guide?
>
> e.g.
>
> http://stackoverflow.com/questions/14758283/is-there-a-numpy-scipy-dot-product-calculating-only-the-diagonal-entries-of-the
>
> I didn't pay a lot of attention to the einsum changes, since I haven't
> really used it yet.
>
>
It is quite a bit slower for dot products, but very convenient for stacked
arrays, vectors, and other such things that are complicated to do with dot
products. I find the extra execution time negligible in relation to the
savings in programming effort, but the tradeoff might be different for a
library.

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141224/8056a5de/attachment.html>