numpy.
vectorize
广义函数类。
定义一个向量化函数,该函数以嵌套的对象序列或numpy数组作为输入,并返回一个numpy数组或numpy数组的元组。矢量化函数计算 pyfunc 除了使用numpy的广播规则外,它还使用类似于python map函数的输入数组的连续元组。
输出的数据类型 vectorized 通过使用输入的第一个元素调用函数来确定。这可以通过指定 otypes 参数。
python函数或方法。
输出数据类型。必须将其指定为类型代码字符字符串或数据类型说明符列表。每个输出应该有一个数据类型说明符。
函数的docstring。如果没有,docstring将是 pyfunc.__doc__ .
pyfunc.__doc__
表示位置参数或关键字参数的字符串或整数集,函数将不向量化。这些将直接传递给 pyfunc 未修改的
1.7.0 新版功能.
如果 True ,然后缓存确定输出数量的第一个函数调用,如果 otypes 未提供。
广义通用函数签名,例如, (m,n),(n)->(m) 用于矢量化矩阵矢量乘法。如果提供, pyfunc 将使用(并预期返回)数组调用,数组的形状由相应的核心维度的大小给定。默认情况下, pyfunc 假定以标量作为输入和输出。
(m,n),(n)->(m)
pyfunc
1.12.0 新版功能.
矢量化函数。
参见
frompyfunc
接受任意python函数并返回ufunc
笔记
这个 vectorize 功能的提供主要是为了方便,而不是为了性能。该实现本质上是一个for循环。
如果 otypes 如果未指定,则将使用带有第一个参数的函数调用来确定输出的数目。如果 cache 是 True 以防止调用函数两次。但是,要实现缓存,必须包装原始函数,这将减慢后续调用的速度,因此只有在函数昂贵时才这样做。
新的关键字参数接口和 excluded 参数支持会进一步降低性能。
工具书类
通用函数API
实例
>>> 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])
docstring从输入函数获取到 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 :
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=['p']) >>> vpolyval(p=[1, 2, 3], x=[0, 1]) array([3, 6])
位置参数也可以通过指定其位置排除:
>>> vpolyval.excluded.add(0) >>> vpolyval([1, 2, 3], x=[0, 1]) array([3, 6])
这个 signature 参数允许对作用于固定长度的非标量数组的函数进行矢量化。例如,您可以将其用于皮尔逊相关系数及其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.]])
方法
__call__ * ARGs, * * 克瓦格斯)
__call__
返回结果为的数组 pyfunc 广播(矢量化)结束 args 和 kwargs 歪投球 excluded .