返回数组的函数的numpy.vectorize [英] numpy.vectorize of function that returns an array
问题描述
我试图向量化一个具有2个输入并输出形状=(4,)的np.array的函数.该函数如下所示:
I am trying to vectorize a function which has 2 inputs, and outputs a np.array, of shape =(4,). The function looks like this:
def f(a, b):
return np.array([a+b, a-b, a, b])
我能够使用签名参数对函数进行矢量化处理,但是仅当我使用np.vectorize
的excluded
自变量排除其中一个参数时,该函数才有效:
I was able to vectorize the function, using the signature parameter, however it only works if I exclude one of the parameters using the excluded
argument of np.vectorize
:
这有效:
vec = np.vectorize(f, signature='()->(n)', excluded=[1])
x = np.arange(5)
y = 3
vec(x, y)
>> output:
array([[ 3, -3, 0, 3],
[ 4, -2, 1, 3],
[ 5, -1, 2, 3],
[ 6, 0, 3, 3],
[ 7, 1, 4, 3]])
但是,如果我删除了excluded
参数,事情就不会按计划进行.
However if I take out the excluded
argument, things don't go as planned.
这不起作用:
vec = np.vectorize(f, signature='()->(n)')
x = np.arange(5)
y = 3
vec(x, y)
>> Error:
TypeError: wrong number of positional arguments: expected 1, got 2
如何使矢量化函数能够接收一个(或两个)输入参数的输入值的数组/列表?
How can I make the vectorized function able to receive an array/list of input values for either one (or both) of the input parameters?
预期的输出将是vec
函数,该函数将允许使用多个输入来调用任一输入参数.
The expected output would be a vec
function which would enable calling it with multiple inputs for either one of the input parameters.
推荐答案
In [237]: f1 = np.vectorize(f, signature='(),()->(n)')
In [238]: f1(np.arange(5),3)
Out[238]:
array([[ 3, -3, 0, 3],
[ 4, -2, 1, 3],
[ 5, -1, 2, 3],
[ 6, 0, 3, 3],
[ 7, 1, 4, 3]])
In [241]: f1(np.arange(5),np.ones((4,5))).shape
Out[241]: (4, 5, 4)
In [242]: f1(np.arange(5),np.ones((1,5))).shape
Out[242]: (1, 5, 4)
frompyfunc
返回一个对象dtype数组:
frompyfunc
returns a object dtype array:
In [336]: f2 = np.frompyfunc(f,2,1)
In [337]: f2(np.arange(5), 3)
Out[337]:
array([array([ 3, -3, 0, 3]), array([ 4, -2, 1, 3]),
array([ 5, -1, 2, 3]), array([6, 0, 3, 3]), array([7, 1, 4, 3])],
dtype=object)
In [338]: _.shape
Out[338]: (5,)
np.vectorize
(没有signature
)使用frompyfunc
,但添加了自己的dtype
转换.
np.vectorize
, without the signature
, uses frompyfunc
, but adds its own dtype
conversion.
In [340]: f1(np.arange(5), np.arange(3))
ValueError: shape mismatch: objects cannot be broadcast to a single shape
此操作失败的原因与以下添加操作失败的原因相同
This fails for the same reason the following addition fails:
In [341]: np.arange(5)+np.arange(3)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-341-fb1c4f4372da> in <module>
----> 1 np.arange(5)+np.arange(3)
ValueError: operands could not be broadcast together with shapes (5,) (3,)
要获得(5,3)结果,我们需要使第一个参数(5,1)成为形状:
To get a (5,3) result we need to make the first argument (5,1) shape:
In [342]: np.arange(5)[:,None]+np.arange(3)
Out[342]:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])
这篇关于返回数组的函数的numpy.vectorize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!