【python】详解numpy.vectorize的使用,将函数向量化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/brucewong0516/article/details/84776089

首先看一下文档:

numpy.vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)

Parameters:	
pyfunc :python函数或方法
otypes : 输出数据类型。必须将其指定为一个typecode字符串或一个数据类型说明符列表。每个输出应该有一个数据类型说明符。
doc : 函数的docstring。如果为None,则docstring将是 pyfunc.__doc__。
excluded : 表示函数不会向量化的位置或关键字参数的字符串或整数集。这些将直接传递给未经修改的pyfunc
cache :如果为True,则缓存第一个函数调用,该函数调用确定未提供otype的输出数。
signature : 广义通用函数签名,例如,(m,n),(n)->(m)用于矢量化矩阵 - 向量乘法。如果提供的话,pyfunc将调用(并期望返回)具有由相应核心维度的大小给出的形状的数组。默认情况下,pyfunc假定将标量作为输入和输出。
Returns:	
vectorized :向量化的数组

实例如下:

1.1 将函数向量化
def myfunc(a, b):
...     "Return a-b if a>b, otherwise return a+b"
...     if a > b:
...         return a - b
...     else:
...         return a + b
    

vfunc = np.vectorize(myfunc)

vfunc([1, 2, 3, 4], 2)
Out[87]: array([3, 4, 1, 2])
1.2 函数的docstring,如果没有定义,则用函数本身的,当然可以自定义
def myfunc(a, b):
...     "Return a-b if a>b, otherwise return a+b"
...     if a > b:
...         return a - b
...     else:
...         return a + b
    

vfunc = np.vectorize(myfunc)

vfunc.__doc__
Out[92]: 'Return a-b if a>b, otherwise return a+b'

vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
vfunc.__doc__

Out[93]: 'Vectorized `myfunc`'
1.3 输出类型是通过计算输入的第一个元素来确定的,除非它被指定
out = vfunc([1, 2, 3, 4], 2)
print(type(out[0]))
vfunc = np.vectorize(myfunc, otypes=[float])
out = vfunc([1, 2, 3, 4], 2)
print(type(out[0]))

<class 'numpy.int32'>
<class 'numpy.float64'>
1.4 用excluded可以用来防止对某些参数矢量化,这对于固定长度的类似数组的参数很有用,例如多项式的系数
def mypolyval(p, x):
...     _p = list(p)
...     res = _p.pop(0)
...     while _p:
...         res = res*x + _p.pop(0)
...     return res
>>> vpolyval = np.vectorize(mypolyval, excluded=['p'])
>>> vpolyval(p=[1, 2, 3], x=[0, 1])

Out[96]: array([3, 6])
1.5 签名参数允许矢量化作用于固定长度的非标量数组的函数。例如,您可以将其用于Pearson相关系数及其p值的矢量化计算
import scipy.stats
pearsonr = np.vectorize(scipy.stats.pearsonr,signature='(n),(n)->(),()')
pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])

Out[100]: (array([ 1., -1.]), array([0., 0.]))

pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4]])
Out[101]: (array([1.]), array([0.]))

猜你喜欢

转载自blog.csdn.net/brucewong0516/article/details/84776089
今日推荐