gpt4 book ai didi

python - Numba jit 与 scipy

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:55 25 4
gpt4 key购买 nike

所以我想加速我在 numba 的帮助下编写的程序 jit .然而jit似乎与许多 scipy 函数不兼容,因为它们使用 try ... except ...结构jit无法处理(我对这一点是否正确?)

我想到的一个相对简单的解决方案是复制我需要的 scipy 源代码并删除 try except部分(我已经知道它不会出错,所以 try 部分将始终有效)

但是我不喜欢这个解决方案,我不确定它是否可行。

我的代码结构如下所示

import scipy.integrate as integrate
from scipy optimize import curve_fit
from numba import jit

def fitfunction():
...

@jit
def function(x):
# do some stuff
try:
fit_param, fit_cov = curve_fit(fitfunction, x, y, p0=(0,0,0), maxfev=500)
for idx in some_list:
integrated = integrate.quad(lambda x: fitfunction(fit_param), lower, upper)
except:
fit_param=(0,0,0)
...

现在这会导致以下错误:

LoweringError: Failed at object (object mode backend)

我假设这是由于 jit无法处理 try except (如果我只将 jit 放在 curve_fitintegrate.quad 部分并围绕我自己的 try except 结构工作,它也不起作用)

import scipy.integrate as integrate
from scipy optimize import curve_fit
from numba import jit

def fitfunction():
...

@jit
def integral(lower, upper):
return integrate.quad(lambda x: fitfunction(fit_param), lower, upper)

@jit
def fitting(x, y, pzero, max_fev)
return curve_fit(fitfunction, x, y, p0=pzero, maxfev=max_fev)


def function(x):
# do some stuff
try:
fit_param, fit_cov = fitting(x, y, (0,0,0), 500)
for idx in some_list:
integrated = integral(lower, upper)
except:
fit_param=(0,0,0)
...

有没有办法使用jitscipy.integrate.quadcurve_fit无需手动删除所有 try except来自 scipy 代码的结构?

它甚至会加速代码吗?

最佳答案

Numba 只是不是一个用于加速代码的通用库。有一类问题可以用 numba 以更快的方式解决(特别是如果你有数组循环,数字运算)但其他一切要么(1)不受支持要么(2)只是稍微快一点甚至很多较慢。

[...] would it even speed up the code?

SciPy 已经是一个高性能库,所以在大多数情况下,我预计 numba 的性能会更差(或者很少:稍微好一点)。你可能会做一些profiling找出瓶颈是否真的存在于您jit 的代码中,然后您可以得到一些改进。但我怀疑瓶颈将出现在 SciPy 的编译代码中,并且该编译代码可能已经进行了高度优化(因此您真的不太可能找到可以“仅”与该代码竞争的实现)。

Is there a way to use jit with scipy.integrate.quad and curve_fit without manually deleting all try except structures from the scipy code?

正如您正确假设的那样,目前 numba 根本不支持 tryexcept

2.6.1. Language

2.6.1.1. Constructs

Numba strives to support as much of the Python language as possible, but some language features are not available inside Numba-compiled functions. The following Python language features are not currently supported:

[...]

  • Exception handling (try .. except, try .. finally)

所以这里的答案是

关于python - Numba jit 与 scipy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55317665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com