我正在以迭代的方式使用
scipy.optimize.curve_fit()
。
我的问题是,当它无法适应参数时,整个程序(以及迭代)就会停止,这就是它给出的错误:
RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.
我明白为什么它一直无法适应。我的问题是,有什么方法可以在 Python 3.2.2 中编写程序,忽略此类事件并继续?
在优化无法找到解决方案的情况下,您可以使用标准 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
引发的错误情况,而无需中止程序。
从 talonmies' 的建议开始,我不得不承认两个额外的更改帮助我使我的代码正常工作:
df.reset_index(drop=True)
这是我为我的代码成功采用的最终解决方案。
# 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")