Numpy vectorize作为带参数的装饰器

时间:2013-02-20 17:56:34

标签: 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

编辑:重启IPython后,输出正常。

任何人都可以解释为什么diff_if_bigger的结果被转换为np.int的数组,即使第一个参数x在这里是np.float的aray,与之相反的是什么在doc ????

现在,我想强制浮动输出,所以我做了这个

 @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)

顺便说一句,即便如此

 vec_diff = np.vectorize(diff_if_bigger, otypes=[np.float])

不起作用!!!那是怎么回事?

编辑:事实上,后者在重新启动IPython后工作了。

所以在我之前的两次编辑之后,我的问题现在是双重的:

1-如何将np.vectorize用作带参数的装饰器?

2-如何清理IPython状态?

1 个答案:

答案 0 :(得分:10)

适合我:

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

请注意,除最简单的情况外,np.vectorize并不是真正的装饰者。如果您需要指定明确的otype,请使用常用表单new_func = np.vectorize(old_func, otypes=...)或使用functools.partial来获取装饰器。

另请注意,np.vectorize默认情况下通过评估第一个参数的函数来获取其输出类型:

  

vectorized输出的数据类型是通过使用输入的第一个元素调用函数来确定的。

因此,如果您想确保将float推断为输出dtype(例如,使用float并传递{{1},则应传递float并返回else 0.0 }})。

相关问题