SciPy curve_fit运行时错误,停止迭代

发布于 2025-01-03 03:21:08 字数 231 浏览 1 评论 0原文

我以迭代方式使用 scipy.optimize.curve_fit() 。

我的问题是,当它无法适应整个程序(从而迭代)的参数时,它会停止,这就是它给出的错误:

RuntimeError:找不到最佳参数:对函数的调用次数已达到 maxfev = 800.

我明白为什么它一直无法适应。我的问题是,有什么方法可以在 Python 3.2.2 中编写程序,忽略此类事件并继续?

I am using scipy.optimize.curve_fit() in an iterative way.

My problem is that when ever it is unable to fit the parameters the whole program (and thus the iteration) stops, this is the error it gives:

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

I understand that why it has been unable to fit. My problem is that is there any way I can write the program in Python 3.2.2 that will ignore such occurrences and just continue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

躲猫猫 2025-01-10 03:21:08

在优化无法找到解决方案的情况下,您可以使用标准 Python 异常处理来捕获 curve_fit 引发的错误。因此,类似于:

try:
    popt,pcov = scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None)

except RuntimeError:
    print("Error - curve_fit failed")

该构造将让您捕获并处理由 curve_fit 引发的错误情况,而无需中止程序。

You can use standard Python exception handling to trap the error raised by curve_fit in cases where the optimization fails to find a solution. So something like:

try:
    popt,pcov = scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None)

except RuntimeError:
    print("Error - curve_fit failed")

That construct will let you catch and handle the error condition raised by curve_fit without having your program abort.

柒七 2025-01-10 03:21:08

talonmies的建议开始,我不得不承认两个额外的更改帮助我使我的代码正常工作:

  • 首先,我重置了数据帧的索引
df.reset_index(drop=True)
  • 然后,我还将方法从默认更改为“dogbox

这是我为我的代码成功采用的最终解决方案。

# Define power law function for fitting
def power_law(x, a, b):
    return a * np.power(x, b)

try:
    popt, _ = curve_fit(power_law, df.index + 1, df['normalized_num_impression'], method='dogbox')
except RuntimeError:
    print("Error - curve_fit failed")

Starting by talonmies' suggestion, I have to admit that two additional changes helped me make my code work:

  • First, I reset the index of my dataframe
df.reset_index(drop=True)
  • Then, I also changed the method from default to "dogbox"

This is the final solution I successfully adopted for my code.

# Define power law function for fitting
def power_law(x, a, b):
    return a * np.power(x, b)

try:
    popt, _ = curve_fit(power_law, df.index + 1, df['normalized_num_impression'], method='dogbox')
except RuntimeError:
    print("Error - curve_fit failed")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文