是否有沿轴执行numpy.outer的矢量化方法? [英] Is there a more vectorized way to perform numpy.outer along an axis?

查看:82
本文介绍了是否有沿轴执行numpy.outer的矢量化方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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' ]]])

由于我正在计划使用大型阵列,因此是否有更多类似numpy的版本?我觉得答案就在我的鼻子底下,我在想它与reduce有关,但是numpy的版本仅适用于ufunc,而不适用于函数.甚至一个提示也将不胜感激.

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.

提前谢谢.

推荐答案

这是您要寻找的吗?

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]]])

顺便说一句,看一下实现总是有用的.帮助理解魔术". np.outer看起来像这样:

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,:]

从这里开始很容易.

另外,在您的问题中,您有:

Also, in you question, you have:

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

更好地写为:

[np.outer(xx,yy) for xx,yy in izip(x,y)]

这篇关于是否有沿轴执行numpy.outer的矢量化方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆