在Python中查找参数的非线性回归

时间:2017-12-18 19:23:18

标签: python non-linear-regression

我有一个函数Y = a + b *(x)^ c和一个x和y的实验值列表。如何在python中对它进行曲线拟合并找出参数a,b和c的值?

x         y
5.107     3.57
15.593    4.09
178.942   9.19
351.23    14.3
523.172   19.41
1039.449  32.17

1 个答案:

答案 0 :(得分:0)

您可以使用lmfithttps://lmfit.github.io/lmfit-py/)并定义模型函数,例如

import numpy as np
from lmfit import Model
import matplotlib.pyplot as plt

x = np.array((5.107, 15.593, 178.942, 351.23, 523.172, 1039.449))
y = np.array((3.57, 4.09, 9.19, 14.3, 19.41, 32.17))

def expfunc(x, scale, decay, offset):
     "model exponential decay with offset"
    return offset + scale*x**decay

# create model from the above model function
model = Model(expfunc)

# create parameters with initial values, 
# using names from model function
params = model.make_params(offset=0, scale=1, decay=1)

# fit data 'y' to model with params
result = model.fit(y, params, x=x)

# print and plot result 
print(result.fit_report())
result.plot_fit()
plt.show()

此拟合的拟合报告将为参数提供拟合统计数据和最佳拟合值,不确定性和相关性:

[[Model]]
    Model(expfunc)
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 27
    # data points      = 6
    # variables        = 3
    chi-square         = 0.181
    reduced chi-square = 0.060
    Akaike info crit   = -15.015
    Bayesian info crit = -15.640
[[Variables]]
    offset:   3.29036599 +/- 0.200622 (6.10%) (init= 0)
    scale:    0.06290220 +/- 0.008912 (14.17%) (init= 1)
    decay:    0.88280026 +/- 0.020216 (2.29%) (init= 1)
[[Correlations]] (unreported correlations are <  0.100)
    C(scale, decay)              = -0.997
    C(offset, scale)             = -0.722
    C(offset, decay)             =  0.686

并制作一个这样的情节:

enter image description here

FWIW,这个模型函数非常简单,您可以使用lmfit ExpressionModel从表达式的字符串构建模型,如下所示:

from lmfit.models import ExpressionModel
model = ExpressionModel('offset + scale*x**decay')

其他所有内容与上述相同。