[英]`ufunc` composition in NumPy
My code contains the following definition:我的代码包含以下定义:
skew_min = np.frompyfunc(lambda x, y: min(x + 1, y), nin=2, nout=1)
The essential point, is that it is ufunc
, because I call skew_min.accumulate
further.关键在于它是
ufunc
,因为我进一步调用skew_min.accumulate
。 But this definition is really awful.但是这个定义真的很糟糕。 It works slow (because of python-from-native-code calls) and produces an ill-typed result (array of pyobject instead of array of float).
它运行缓慢(因为 python-from-native-code 调用)并产生错误类型的结果(pyobject 数组而不是 float 数组)。 How I dream, there should be some FP-flavored combinators to construct
ufunc
from other ufunc
s, something like that:我多么梦想,应该有一些 FP 风格的组合器来从其他
ufunc
构造ufunc
,就像这样:
skew_min = compose_1(np.minimum, subst_1(np.add, 1))
(where made-up functions compose_1
and subst_1
perform ufunc
-tional composition and substitution, correspondingly). (其中组成的函数
compose_1
ufunc
subst_1
执行功能组合和替换)。 But I have failed to find anything resembling compose
in NumPy docs.但是我在 NumPy 文档中找不到任何类似
compose
的内容。
So, is there a nice way to compose two ufunc
s in order to build a new one?那么,有没有一种很好的方法来组合两个
ufunc
来构建一个新的?
You could use numba's @numba.vectorize
or @numba.guvectorize
( numba docs ):您可以使用 numba 的
@numba.vectorize
或@numba.guvectorize
( numba docs ):
>>> import numpy as np
>>> import numba
>>> @numba.vectorize(['f8(f8, f8)', 'i8(i8, i8)'])
... def skew_min(x: float, y: float) -> float:
... return min(x + 1, y)
...
>>> skew_min(3, 3.5)
3.5
>>> skew_min([2, 3, 4], 3.5)
array([3. , 3.5, 3.5])
>>> skew_min.outer(np.arange(3), [1.62, 2.72, 3.14])
array([[1. , 1. , 1. ],
[1.62, 2. , 2. ],
[1.62, 2.72, 3. ]])
As a bonus, numba jit-compiles the function, making it generally faster than using eg numpy.frompyfunc
or numpy.vectorize
.作为奖励,numba jit 编译 function,使其通常比使用
numpy.frompyfunc
或numpy.vectorize
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.