曲线拟合数据问题

时间:2015-12-04 09:14:25

标签: python numpy scipy curve-fitting lmfit

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

xdata = np.array([177,180,183,187,189,190,196,197,201,202,203,204,206,218,225,231,234,
      252,262,266,267,268,277,286,303])

ydata = np.array([0.81,0.74,0.78,0.75,0.77,0.81,0.73,0.76,0.71,0.74,0.81,0.71,0.74,0.71,
      0.72,0.69,0.75,0.59,0.61,0.63,0.64,0.63,0.35,0.27,0.26])



def f(x, n1, n2, n3, n4, n5):
    if (n1 > 0.2 and n1 < 0.8 and
        n2 > -0.3 and n2 < 0):
        return n1 + (n2 * x + n3) * 1./ (1 + np.exp(n4 * (n5 - x)))
    return 1e38

coeffs, pcov = curve_fit(f, xdata, ydata, p0 = (0.29, -0.005, 1.0766, -0.36397, 104))

ploty = f(xdata, coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4])
for i in range(1, len(coeffs) + 1):
    print ('n%s = %s' % (i, coeffs[i - 1])) 

没有正常工作并发出此警告:

OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)

但是

正常工作
xdata = np.array([73.0, 80.0, 88.0, 93.8, 96.3, 98.5, 100.0, 101.0, 102.3,  104.0, 105.3,
                 107.0, 109.5, 111.5, 114.0, 117.0, 119.5, 121.0, 124.0])
 ydata = np.array([0.725, 0.7, 0.66, 0.63, 0.615, 0.61, 0.59, 0.56, 0.53, 0.49, 0.45, 
                   0.41, 0.35, 0.32, 0.3, 0.29, 0.29, 0.29, 0.29])

Lmfit也不起作用。

1 个答案:

答案 0 :(得分:2)

由于您还使用作为标记,因此这是使用lmfit的解决方案。您获得的参数值如下所示:

lmfit

产生以下输出: enter image description here

如您所见,拟合非常好地再现数据,参数在重新考虑的范围内;函数中不需要n1: 0.26564921 +/- 0.024765 (9.32%) (init= 0.2) n2: -0.00195398 +/- 0.000311 (15.93%) (init=-0.005) n3: 0.87261892 +/- 0.068601 (7.86%) (init= 1.0766) n4: -1.43507072 +/- 1.223086 (85.23%) (init=-0.36379) n5: 277.684530 +/- 3.768676 (1.36%) (init= 274) 语句。

以下是使用一些附加注释重现该图的完整代码:

if

编辑:

事实证明,这仅适用于0.8.3版本。如果您使用版本0.9.x,则需要相应地调整代码;检查here已从0.8.3更改为0.9.x。