我正在尝试对 numpy 中的一个简单函数进行矢量化处理,但出现了不一致的行为。我希望我的代码为 < 0.5 的值返回 0,否则返回不变的值。奇怪的是,从命令行运行不同的脚本会产生不同的结果:有时它工作正常,有时我得到全 0。当 d <= T 时,我使用三行中的哪一行并不重要。它似乎与要返回的第一个值是否为 0 相关。有什么想法吗?谢谢。
import numpy as np
def my_func(d, T=0.5):
if d > T: return d
#if d <= T: return 0
else: return 0
#return 0
N = 4
A = np.random.uniform(size=N**2)
A.shape = (N,N)
print A
f = np.vectorize(my_func)
print f(A)
$ python x.py
[[ 0.86913815 0.96833127 0.54539153 0.46184594]
[ 0.46550903 0.24645558 0.26988519 0.0959257 ]
[ 0.73356391 0.69363161 0.57222389 0.98214089]
[ 0.15789303 0.06803493 0.01601389 0.04735725]]
[[ 0.86913815 0.96833127 0.54539153 0. ]
[ 0. 0. 0. 0. ]
[ 0.73356391 0.69363161 0.57222389 0.98214089]
[ 0. 0. 0. 0. ]]
$ python x.py
[[ 0.37127366 0.77935622 0.74392301 0.92626644]
[ 0.61639086 0.32584431 0.12345342 0.17392298]
[ 0.03679475 0.00536863 0.60936931 0.12761859]
[ 0.49091897 0.21261635 0.37063752 0.23578082]]
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
请您参考如下方法:
如果这确实是您要解决的问题,那么还有更好的解决方案:
A[A<=0.5] = 0.0
但是,您的代码存在的问题是,如果条件通过,您返回的是 integer 0,而不是 float 0.0。来自文档:
The data type of the output of
vectorizedis determined by calling the function with the first element of the input. This can be avoided by specifying theotypesargument.
所以当第一个条目是 <0.5 ,它会尝试创建一个整数数组,而不是 float 组。 你应该改变 return 0到
return 0.0
或者,如果您不想触摸 my_func , 你可以使用
f = np.vectorize(my_func, otypes=[np.float])
