Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more vectorized way to perform numpy.outer along an axis?

Tags:

python

numpy

>>> x = np.array([['a0', 'a1'],['b0','b1']])
>>> y = np.array([['x0', 'x1'],['y0','y1']])
>>> iterable = [np.outer(x[i],y[i]) for i in xrange(x.shape[0])]
>>> elbareti = np.asarray(iterable)
>>> elbareti
array([[[ 'a0'*'x0', 'a0'*'x1' ],
        [ 'a1'*'x0', 'a1'*'x1' ]],

       [[ 'b0'*'y0', 'b0'*'y1' ],
        [ 'b1'*'y0', 'b1'*'y1' ]]])

Since i'm planning on working with large arrays, is there a more numpy-like version of this? I feel like the answer is right under my nose and I'm thinking it has something to do with reduce, but numpy's version only works with ufuncs, not functions. Even a hint would be greatly appreciated.

Thanks in advance.

like image 768
Noob Saibot Avatar asked May 11 '13 18:05

Noob Saibot


1 Answers

Is this what you're looking for?

x = np.array([[1,2], [3,4]])
y = np.array([[5,6], [7,8]])

x[:,:,np.newaxis] * y[:,np.newaxis,:]

array([[[ 5,  6],
        [10, 12]],

       [[21, 24],
        [28, 32]]])

EDIT:

Btw, it's alway useful to look the implementation. Helps understanding the "magic". np.outer looks like this:

return a.ravel()[:,newaxis]*b.ravel()[newaxis,:]

From here, it's easy.

Also, in you question, you have:

[np.outer(x[i],y[i]) for i in xrange(x.shape[0])]

Better written as:

[np.outer(xx,yy) for xx,yy in izip(x,y)]
like image 141
shx2 Avatar answered Sep 19 '22 10:09

shx2