python中numpy对函数进行矢量化转换
2016-01-23 16:48
393 查看
在对numpy的数组进行操作时,我们应该尽量避免循环操作,尽可能利用矢量化函数来避免循环.
但是,直接将自定义函数应用在numpy数组之上会报错,我们需要将函数进行矢量化转换.
出错信息:
为了得到矢量的Theta,我们可以使用Numpy函数vectorize。在许多情况下它可以自动矢量化一个函数:
我们也可以使用该函数从头来接受矢量输入(需要更多工作但是也表现更好):
但是,直接将自定义函数应用在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)
相关文章推荐
- Python操作MySQL案例
- python多进程
- leetcode之Merge k Sorted Lists
- python之字典
- python连接MySQL时,中文乱码解决方案
- 【Python】使用pypy加速
- Python操作SQLite/MySQL/LMDB/LevelDB
- Numpy之random模块
- python strip()函数 介绍
- Anaconda、Python和Theano之间的关系
- Python学习视频
- Python之面向对象进阶篇
- Python函数式编程Demo
- python[番外篇]在win7 64位系统中安装 python MySQLdb
- python课程
- Python 批量读取文件名并写入txt中
- leetcode之Reorder List
- python--列表 、元组、字典
- ipython
- 转: 理解Python的With语句