首页 > 解决方案 > 如何在 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'

标签: pythonnumpy

解决方案


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_),或者您可以使用 覆盖默认的中间 dtype leaku.accumulate(np.array([0, 1, 1, 0, 0, 0.0]), dtype=np.object_)

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


推荐阅读