python-numpy.vectorize()

来源:互联网 发布:工业机器人技术编程 编辑:程序博客网 时间:2024/05/21 03:58

官方文档地址
class numpy.vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)
广义函数类?

Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns an single or tuple of numpy array as output. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.

定义了一个矢量函数,输入是嵌套化的对象序列或者是numpy数组,
输出是单个或元组的numpy数组。跟 map()很类似。将函数pyfunc作用在序列化的对象上。
numpy.vectorize()只是为了方便,效率比较低。
官方例子:

import numpy as np def myfunc(a, b):    'Return a-b if a>b, otherwise return a+b'    if a>b:        return a-b    else:        return a+bvfunc = np.vectorize(myfunc)print vfunc([1, 2, 3, 4], 2)#[3 4 1 2]

相当于 2 与列表中的1,2,3,4 依次 调用函数。即1,2; 2,2; 3,2; 4,2做vfunc计算。

print vfunc.__doc__#Return a-b if a>b, otherwise return a+bvfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')print vfunc.__doc__#Vectorized `myfunc`

打印以及修改函数信息。

out = vfunc([1, 2, 3, 4], 2)print out[0]#3print type(out[0])#<type 'numpy.int64'>vfunc = np.vectorize(myfunc, otypes=[np.float])out = vfunc([1, 2, 3, 4], 2)print out[0]#3.0print type(out[0])#<type 'numpy.float64'>

调用函数,默认返回的值的类型是由被调用函数的第一个值的类型决定的。比如第一个例子,第一次调用函数的参数是 1,2,则决定了输出的类型是int。
可以通过otype参数进行修改。

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.

def mypolyval(p, x):    _p = list(p)    res = _p.pop(0)    while _p:        res = res*x + _p.pop(0)    return resvpolyval = np.vectorize(mypolyval, excluded=['p'])print vpolyval(p=[1, 2, 3], x=[0, 1])#[3 6]

使用excluded参数来确保某个参数不被矢量化,比如我们有一个x的多项式,我们想依次计算每个x的值在表达式中的值时,我们的多项式参数不能够被矢量化。
也可通过add()来将某个位置上的参数不被矢量化。

vpolyval.excluded.add(0)vpolyval([1, 2, 3], x=[0, 1])#array([3, 6])

(补充)
再看一下list的pop方法:

#lsit pop This method returns the removed object from the list.aList = [123, 'xyz', 'zara', 'abc'];print "A List : ", aList.pop()print "B List : ", aList.pop(2)print "C List : ", aList.pop(0)# A List :  abc# B List :  zara# C List :  123print aList#['xyz']

pop按index从list中弹出数据。

signature参数的使用:
计算皮尔逊相关系数以及进行卷积操作。
此参数略高级。

import scipy.statspearsonr = np.vectorize(scipy.stats.pearsonr,                         signature='(n),(n)->(),()')print pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])#(array([ 1., -1.]), array([ 0.,  0.]))convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')print convolve(np.eye(4), [1, 2, 1])# array([[ 1.,  2.,  1.,  0.,  0.,  0.],#        [ 0.,  1.,  2.,  1.,  0.,  0.],#        [ 0.,  0.,  1.,  2.,  1.,  0.],#        [ 0.,  0.,  0.,  1.,  2.,  1.]])
原创粉丝点击