Implemented using scipy.optimize.curve_fit
functions.
curve_fit
The parameters are as follows:
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
check_finite=True, bounds=(- inf, inf), method=None, jac=None, **kwargs)
Introduce the basic parameters required for use. Please refer to the official documentation for detailed parameters :
f:模型函数,ydata=f(xdata, *params),其中param为xdata与ydata映射时的参数。
xdata:自变量
ydata:因变量
curve_fit
The function is to use the nonlinear least squares method to fit xdata
, ydata
in f
the form of a function.
# 定义xy之间的映射函数
def func(x, a, b, c):
return a * np.exp(-b*x) + c
Before fitting the curve, declare a function func
. The first parameter is the independent variable x
, and the following parameters are all the parameters in the function *param
. func
Assign the function curve_fit
to the parameters in f
. Here is an example.
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
# 声明待拟合的数据
xdata = np.linspace(0, 4, 50)
y = func(xdata, 2.5, 1.3, 0.5) # 使用func先生成ydata,a=2.5,b=1.3,c=0.5
# 给ydata添加随机噪声
rng = np.random.default_rng()
y_noise = 0.2 * rng.normal(size=xdata.size)
ydata = y + y_noise
# 展示数据
plt.scatter(xdata, ydata, label='data')
# 拟合数据并展示曲线
popt, pcov = curve_fit(func, xdata, ydata)
plt.plot(xdata, func(xdata, *popt), 'r-',
label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
# 强制参数 a/b/c 的取值范围为:[0,2]/[0,1]/[0,0.3]
popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [2., 1., 0.3]))
plt.plot(xdata, func(xdata, *popt), 'g--',
label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html#scipy.optimize.curve_fit