scipy curve_fit无法拟合曲线

时间:2016-07-25 18:16:29

标签: python scipy curve-fitting

我正在尝试使用scipy.optimize函数curve_fit来使用自定义指数函数拟合一组数据点。我的代码如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def fit(x, tau, beta):
    return np.exp(-1 * np.power(x / tau, beta))

def plot_e2e(times, e2es):
    optimalParams, covariance = curve_fit(fit, times, e2es)
    tau = optimalParams[0]
    beta = optimalParams[1]

    print 'Tau is:', tau
    print 'Beta is:', beta

if __name__ == '__main__':
    % read_e2e_data not included for proprietary reasons.
    times, e2es = read_e2e_data(fileName)
    plot_e2e(times, e2es)

这样做会引发以下异常(由于取出不相关的内容,行号可能会有所不同):

Traceback (most recent call last):
  File ".\plot_e2e.py", line 54, in <module>
    plot_e2e(times, e2es)
  File ".\plot_e2e.py", line 34, in plot_e2e
    optimalParams, covariance = curve_fit(fit, times, e2es)
  File "C:\Anaconda\lib\site-packages\scipy\optimize\minpack.py", line 586,  in curve_fit 
    raise RuntimeError(msg)
RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 600.

如果我增加curve_fit的maxfev参数,我会获得Tau(4.035e-303)的伪值。

我的时间和e2e向量是:

time = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 11.0, 14.0, 17.0, 21.0, 25.0, 30.0, 37.0, 45.0, 54.0, 65.0, 78.0, 94.0, 113.0, 136.0, 163.0, 196.0, 236.0, 283.0, 340.0, 409.0, 491.0]
e2es = [1.0, 0.999804, 0.99964, 0.999497, 0.99937, 0.999276, 0.999139, 0.998974, 0.998566, 0.998005, 0.997225, 0.997073, 0.997793, 0.998586, 1.001542, 1.004414, 1.005311, 1.001431, 1.001016, 0.998936, 0.995649, 0.993765, 0.98663, 0.985266, 0.984635, 0.982588, 0.974413, 0.973811, 0.968772, 0.970131]

如果您对可能存在的问题有任何想法,请告诉我。我一直试图调试这个问题并且已经走到了尽头。

1 个答案:

答案 0 :(得分:1)

您得到的错误基本上意味着Scipy对合适位置的搜索未能收敛。 Scipy定义了一个名为maxfev的值,其目的是在搜索中放弃多少次迭代之后。您可以更改此参数:

def plot_e2e(times, e2es):
    optimalParams, covariance = curve_fit(fit, times, e2es, maxfev=1000)
    ...

希望这会有所帮助!