python - 如何在 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_)
,或者您可以使用 覆盖默认的中间 dtype leaku.accumulate(np.array([0, 1, 1, 0, 0, 0.0]), dtype=np.object_)
。
请注意,numpy.frompyfunc
ufunc 与任何其他 Python 级代码一样慢,而不是“NumPy 速度”,并且对象数组的速度和内存特性比普通数组差得多,以及其他不方便的行为。我不建议使用numpy.frompyfunc
. 考虑改用 Numba。
推荐阅读
- c# - 对动作的洪水请求会导致不可预知的行为 - ASP.NET MVC
- jquery - 文本不淡入/淡出,可能是什么问题?
- python - Problems while trying to extract all the values from a nested dictionary?
- php - Don't include table in email if variable is empty - PHP
- c# - 如何从 WindowsFormsControlLibrary 创建 .exe 文件
- windows - 网络文件读取速度很慢?
- apache-flink - 逐个处理流,而不是并行处理
- c# - .NET 和 .net core 在项目之间共享文件
- python - 一本字典中多个列表的总和
- reactjs - 在按钮单击事件上调用组件