【python】scipy.optimize.curve_fit
原创
©著作权归作者所有:来自51CTO博客作者安安爸Chris的原创作品,请联系作者获取转载授权,否则将追究法律责任
功能
使用非线性最小平方差来拟合一个函数
功能介绍
官方文档
输入
参数
| Value
|
f
| 函数,它必须以xdata为第一个入参
|
xdata
| 测量的独立数据
|
ydata
| 相关的数据,名义上是 f(xdata,…)的结果
|
输出
输出
| Value
|
popt
| 最优值,即拟合函数根据x输出的值
|
pcov
| popt的协方差矩阵
|
infodict
| a dictionary of optional outputs with the keys (returned only if full_output is True)
|
mesg
| 相关的信息 (returned only if full_output is True)
|
ier
| An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable mesg gives more information. (returned only if full_output is True)
|
例子
官方的例子
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def official_demo_func(x, a, b, c):
return a * np.exp(-b * x) + c
def official_demo():
x = np.linspace(0, 4, 50)
y = official_demo_func(x, 2.5, 1.3, 0.5)
rng = np.random.default_rng()
y_noise = 0.2 * rng.normal(size=x.size)
ydata = y + y_noise
plt.plot(x, ydata, 'b-', label='data')
popt, pcov = curve_fit(official_demo_func, x, ydata)
print(popt)
plt.plot(x, official_demo_func(x, *popt), 'g--',
label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
official_demo()
输出拟合结果为
[2.61499295 1.35033395 0.51541771]
它与输入的值 [2.5, 1.3, 0.5],还是很相近的。