如何在numpy中累积用户定义的ufunc



如何使用使用定义的ufunc进行累积?

import numpy as np
def leak(x, jump):
return x * 0.9 + jump

leaku = np.frompyfunc(leak, 2, 1)
leaku.accumulate(np.array([0, 1, 1, 0, 0, 0.0]))  # ideally [0, 1.0, 1.9, 1.9*0.9, etc.]

产生

ValueError: could not find a matching type for leak (vectorized).accumulate, requested type has type code 'd'

numpy.frompyfunc只能生成具有对象dtype输出的ufunc,但ufunc.accumulate默认使用输入dtype作为中间结果的dtype。(或者out数组的dtype,如果您提供了,但没有提供。(当您传入float64 dtype的数组时,ufunc.accumulate会查找具有float64输出的ufunc循环,但它找不到。

可以传入对象dtype的数组,如np.array([0, 1, 1, 0, 0, 0.0], dtype=np.object_),也可以用leaku.accumulate(np.array([0, 1, 1, 0, 0, 0.0]), dtype=np.object_)覆盖默认的中间dtype。

注意,numpy.frompyfuncufunc与任何其他Python级别的代码一样慢,而不是"慢";NumPy速度";,并且对象阵列具有比普通阵列差得多的速度和存储器特性以及其他不方便的行为。我不建议使用numpy.frompyfunc。请考虑改用Numba。

试试这个:

result = leaku.accumulate(np.array([0, 1, 1, 0, 0, 0.0]), dtype=np.object).astype(np.float)
print(result)

输出

[0.     1.     1.9    1.71   1.539  1.3851]

最新更新