gre*_*iod 10 python numpy decorator python-decorators
我试图进行矢量化(同意,不是最有效的方法来做到这一点,但我的问题是在装饰器上使用)以下函数
@np.vectorize
def diff_if_bigger(x, y):
return y - x if y > x else 0
x = np.array([5.6, 7.0])
y = 8
diff_if_bigger(x, y)
# outputs array([2, 1]) which is not what I want
Run Code Online (Sandbox Code Playgroud)
编辑:重启IPython后,输出正常.
任何人都可以解释为什么结果diff_if_bigger变成一个数组,np.int即使第一个参数x在这里是一个aray np.float,与文档中的内容相反?
现在,我想强制浮动输出,所以我这样做了
@np.vectorize('np.float')
def diff_if_bigger(x, y):
return y - x if y > x else 0
# Error !!
# TypeError: Object is not callable.
@np.vectorize(otypes='np.float')
def diff_if_bigger(x, y):
return y - x if y > x else 0
# Again error !!
# TypeError: __init__() takes at least 2 arguments (2 given)
@np.vectorize(otypes=[np.float])
def diff_if_bigger(x, y):
return y - x if y > x else 0
# Still an error !!
# TypeError: __init__() takes at least 2 arguments (2 given)
Run Code Online (Sandbox Code Playgroud)
顺便说一下,即便如此
vec_diff = np.vectorize(diff_if_bigger, otypes=[np.float])
Run Code Online (Sandbox Code Playgroud)
不起作用!!! 发生什么了??
编辑:事实上,后者在重新启动IPython后工作.
所以在我之前的两次编辑之后,我的问题现在是双重的:
1-如何将np.vectorize用作带参数的装饰器?
2-如何清理IPython状态?
nne*_*neo 12
适合我:
>>> import numpy as np
>>> @np.vectorize
... def diff_if_bigger(x, y):
... return y - x if y > x else 0
...
>>> diff_if_bigger(np.array([5.6,7.0]), 8)
array([ 2.4, 1. ])
Run Code Online (Sandbox Code Playgroud)
请注意,np.vectorize除了最简单的情况之外,它并不真正意味着装饰器.如果需要指定显式otype,请使用常用表单new_func = np.vectorize(old_func, otypes=...)或使用functools.partial获取装饰器.
另请注意np.vectorize,默认情况下,通过在第一个参数上计算函数来获取其输出类型:
输出的数据类型
vectorized是通过使用输入的第一个元素调用函数来确定的.
所以,如果你想确保它推断为输出dtype(例如使用和传递),你应该传递float并返回.floatfloatelse 0.0y = 8.0
| 归档时间: |
|
| 查看次数: |
6173 次 |
| 最近记录: |