numpy.vectorize返回不正确的值 [英] numpy.vectorize returns incorrect values
问题描述
我在使用numpy.vectorize
函数时遇到了一些问题.
I am having some problems with the numpy.vectorize
function.
我定义了一个对单个元素输入效果很好的函数,但是矢量化版本返回的结果不同-我在做什么错了?
I have defined a function that works well for single element input but the vectorized version returns different results - What am I doing wrong?
代码:
def c_inf_comp(z):
if z>0:
return np.exp(-1./(z*z))
else:
return 0
>>> x = np.array([-10., 10.])
>>> x
array([-10., 10.])
>>> c_inf_comp(x[0])
0
>>> c_inf_comp(x[1])
0.99004983374916811
>>> vfunz = np.vectorize(c_inf_comp)
>>> vfunz(x)
array([0, 0])
推荐答案
由于对向量进行矢量化时未指定otypes
(输出数据类型),因此NumPy假定要返回int32
数组价值观.
Because you don't specify otypes
(the output data type) when you vectorize your function, NumPy assumes you want to return an array of int32
values.
给定x
时,矢量化函数vfunz
首先会看到-10.
,返回整数0
,因此确定返回数组的dtype
应该为int32
.
When given x
the vectorized function vfunz
first sees -10.
, returns the integer 0
, and so decides that the dtype
of the returned array should be int32
.
要解决此问题,请将otypes
指定为np.float
值:
To fix this, specify otypes
to be np.float
values:
vfunz = np.vectorize(c_inf_comp, otypes=[np.float])
然后您将获得预期的结果:
You then get your expected result:
>>> vfunz(x)
array([ 0. , 0.99004983])
(或者,可以通过在c_inf_comp
的else
条件下返回浮点值(即return 0.0
来解决此问题.这样,由np.vectorize(c_inf_comp)
生成的函数将返回一个浮点值数组,即使如果它首先看到负数.)
(Alternatively, the issue can be fixed by returning a float value in the else
condition of c_inf_comp
, i.e. return 0.0
. That way, the function generated by np.vectorize(c_inf_comp)
will return an array of float values even if it sees a negative number first.)
这篇关于numpy.vectorize返回不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!