[Numpy-discussion] python reduce vs numpy reduce for outer product

Erik Tollerud erik.tollerud at gmail.com
Sat Sep 26 18:17:37 EDT 2009


I'm encountering behavior that I think makes sense, but I'm not sure
if there's some numpy function I'm unaware of that might speed up this
operation.

I have a (potentially very long) sequence of vectors, but for
examples' sake, I'll stick with three: [A,B,C] with lengths na,nb, and
nc.  To get the result I want, I first reshape them to (na,1,1) ,
(1,nb,1) and (1,1,nc) and do:

>>>reduce(np.multiply,[A,B,C])

and the result is what I want... The curious thing is that

>>>np.prod.reduce([A,B,C])

throws

ValueError: setting an array element with a sequence.

Presumably this is because np.prod.reduce is trying to operate
elemnt-wise without broadcasting.  But is there a way to make the
ufunc broadcast faster than doing the python-level reduce?  (I tried
np.prod(broadcast_arrays([A,B,C]),axis=0), but that seemed slower,
presumably because it needs to allocate the full array for all three
instead of just once).

Or, if there's a better way to just start with the first 3 1d
vectorsand jump straight to the broadcast product (basically, an outer
product over arbitrary number of dimensions...)?



More information about the NumPy-Discussion mailing list