您的位置:首页 > 编程语言 > Python开发

python中numpy对函数进行矢量化转换

2016-01-23 16:48 393 查看
  在对numpy的数组进行操作时,我们应该尽量避免循环操作,尽可能利用矢量化函数来避免循环.

  但是,直接将自定义函数应用在numpy数组之上会报错,我们需要将函数进行矢量化转换.

def Theta(x):
"""
Scalar implemenation of the Heaviside step function.
"""
if x >= 0:
return 1
else:
return 0
Theta(array([-3,-2,-1,0,1,2,3]))


  出错信息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-6658efdd2f22> in <module>()
----> 1 Theta(array([-3,-2,-1,0,1,2,3]))

<ipython-input-8-9a0cb13d93d4> in Theta(x)
3     Scalar implemenation of the Heaviside step function.
4     """
----> 5     if x >= 0:
6         return 1
7     else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


  为了得到矢量的Theta,我们可以使用Numpy函数vectorize。在许多情况下它可以自动矢量化一个函数:

Theta_vec = vectorize(Theta)
Theta_vec(array([-3,-2,-1,0,1,2,3]))
array([0, 0, 0, 1, 1, 1, 1])


  我们也可以使用该函数从头来接受矢量输入(需要更多工作但是也表现更好):

def Theta(x):
"""
Vector-aware implemenation of the Heaviside step function.
"""
return 1 * (x >= 0)
Theta(array([-3,-2,-1,0,1,2,3]))
array([0, 0, 0, 1, 1, 1, 1])
# 对标量依然行得通
Theta(-1.2), Theta(2.6)
(0, 1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: