向量化是不确定的 [英] vectorize is indeterminate

查看:60
本文介绍了向量化是不确定的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将numpy中的一个简单函数向量化,并获得不一致的行为.我希望我的代码对于值<返回0. 0.5,否则保持不变.奇怪的是,在命令行中脚本的不同运行会产生不同的结果:有时它可以正常工作,有时我得到全0.在d< = T的情况下,我使用三行中的哪一行都没有关系.它似乎与要返回的第一个值是否为0相关.有什么想法吗?谢谢.

I'm trying to vectorize a simple function in numpy and getting inconsistent behavior. I expect my code to return 0 for values < 0.5 and the unchanged value otherwise. Strangely, different runs of the script from the command line yield varying results: sometimes it works correctly, and sometimes I get all 0's. It doesn't matter which of the three lines I use for the case when d <= T. It does seem to be correlated with whether the first value to be returned is 0. Any ideas? Thanks.

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

推荐答案

如果这确实是您要解决的问题,那么有一个更好的解决方案:

If this really is the problem you want to solve, then there's a much better solution:

A[A<=0.5] = 0.0

但是,代码的问题是,如果条件通过,则返回的是整数 0,而不是 float 0.0.从文档中:

The problem with your code, however, is that if the condition passes, you are returning the integer 0, not the float 0.0. From the documentation:

vectorized输出的数据类型是通过使用输入的第一个元素调用该函数来确定的.通过指定otypes参数可以避免这种情况.

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

因此,当第一个条目是<0.5时,它将尝试创建一个整数而不是浮点数组. 您应该将return 0更改为

So when the very first entry is <0.5, it tries to create an integer, not float, array. You should change return 0 to

return 0.0

或者,如果您不想触摸my_func,则可以使用

Alternately, if you don't want to touch my_func, you can use

f = np.vectorize(my_func, otypes=[np.float])

这篇关于向量化是不确定的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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