[SciPy-user] advice on inner product, element by element

Pauli Virtanen pav@iki...
Sun Jun 29 14:27:35 CDT 2008


Sun, 29 Jun 2008 19:45:48 +0100, Joseph Anderson wrote:
[clip]
> Example code:
> 
> # parms
> cs = 4
> fs = 60 * 44100    
> 
> a = reshape(arange(fs * cs), (fs, cs)) 
> b = reshape(arange(fs * cs * cs), (fs, cs, cs))
> 
> c1 = array([inner(val_a, val_b) for val_a, val_b in zip(a, b)])
> c2 = asarray(map(inner, a, b))

Something like this:

	c3 = (a[:,None,:]*b).sum(axis=2)

Note that "None" is the same as "newaxis". (Also note that inner
does an inner product along the last dimension by default, but you
probably knew that.)

Timings:

In [49]: %time c1 = array([inner(val_a, val_b) for val_a, val_b in zip(a, b)])
CPU times: user 1.07 s, sys: 0.04 s, total: 1.10 s
Wall time: 1.34 s

In [51]: %time c2 = asarray(map(inner, a, b))
CPU times: user 0.65 s, sys: 0.01 s, total: 0.66 s
Wall time: 0.82 s

In [53]: %time c3 = (a[:,None,:]*b).sum(axis=2)
CPU times: user 0.07 s, sys: 0.00 s, total: 0.07 s
Wall time: 0.13 s

In [60]: a[:,None,:].shape
Out[60]: (88200, 1, 4)

In [61]: b.shape
Out[61]: (88200, 4, 4)

In [55]: allclose(c1, c2)
Out[55]: True

In [56]: allclose(c1, c3)
Out[56]: True



More information about the SciPy-user mailing list