numpy.vectorize#
- class numpy.vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None, cache=False, signature=None)[源代码]#
返回一个行为类似于 pyfunc 的对象,但接受数组作为输入.
定义一个向量化函数,该函数接受对象或 numpy 数组的嵌套序列作为输入,并返回单个 numpy 数组或 numpy 数组的元组.向量化函数像 Python 的 map 函数一样,在输入数组的连续元组上评估 pyfunc ,只不过它使用 numpy 的广播规则.
vectorized 的输出数据类型由使用输入中的第一个元素调用函数来确定.可以通过指定 otypes 参数来避免这种情况.
- 参数:
- pyfunccallable, optional
一个 Python 函数或方法.可以省略以生成带有关键字参数的装饰器.
- otypesstr 或 dtype 的列表,可选
输出数据类型.它必须指定为类型代码字符的字符串或数据类型说明符的列表.每个输出都应该有一个数据类型说明符.
- docstr, optional
该函数的文档字符串.如果为 None,则文档字符串将为
pyfunc.__doc__.- excluded集合,可选
表示函数将不被向量化的位置或关键字参数的字符串或整数集合. 这些将直接传递给 pyfunc 而不进行修改.
- cachebool, 可选
如果为 True ,则缓存确定输出数量的第一个函数调用(如果未提供 otypes ).
- signaturestring, optional
广义通用函数签名,例如,
(m,n),(n)->(m)用于向量化矩阵-向量乘法.如果提供,将使用(并期望返回)由相应核心维度的大小给出的形状的数组调用pyfunc.默认情况下,假定pyfunc将标量作为输入和输出.
- 返回:
- outcallable
如果提供了
pyfunc,则为向量化函数,否则为装饰器.
参见
frompyfunc接受任意 Python 函数并返回一个 ufunc
注释
提供
vectorize函数主要是为了方便,而不是为了性能.该实现本质上是一个 for 循环.如果未指定 otypes ,则将使用对具有第一个参数的函数的调用来确定输出的数量.如果 cache 为 True ,则将缓存此调用的结果,以防止两次调用该函数.但是,为了实现缓存,必须包装原始函数,这将减慢后续调用,因此仅在您的函数开销很大时才执行此操作.
新的关键字参数接口和 excluded 参数支持进一步降低了性能.
参考
[1]示例
>>> 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 + b
>>> vfunc = np.vectorize(myfunc) >>> vfunc([1, 2, 3, 4], 2) array([3, 4, 1, 2])
文档字符串取自
vectorize的输入函数,除非另有说明:>>> vfunc.__doc__ 'Return a-b if a>b, otherwise return a+b' >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') >>> vfunc.__doc__ 'Vectorized `myfunc`'
输出类型由评估输入的第一个元素来确定,除非另有说明:
>>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <class 'numpy.int64'> >>> vfunc = np.vectorize(myfunc, otypes=[float]) >>> out = vfunc([1, 2, 3, 4], 2) >>> type(out[0]) <class 'numpy.float64'>
可以使用 excluded 参数来防止对某些参数进行向量化.这对于固定长度的类数组参数(例如
polyval中的多项式系数)非常有用:>>> 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={0, 'p'}) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6]) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6])
`signature ` 参数允许对作用于固定长度的非标量数组的函数进行向量化.例如,您可以将其用于 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]]) (array([ 1., -1.]), array([ 0., 0.]))
或者用于向量化卷积:
>>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>> 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.]])
支持装饰器语法.装饰器可以作为函数调用来提供关键字参数:
>>> @np.vectorize ... def identity(x): ... return x ... >>> identity([0, 1, 2]) array([0, 1, 2]) >>> @np.vectorize(otypes=[float]) ... def as_float(x): ... return x ... >>> as_float([0, 1, 2]) array([0., 1., 2.])
方法
__call__(args, \kwargs)将 self 作为函数调用.