# python数据拟合

## 1.多项式拟合

### 1.2 多项式拟合实现

#导入库
import numpy as np
import matplotlib.pyplot as plt


#定义测试多项式函数
def func1(x):
return 3*x*x*x-2*x*x+4

#生成测试数组
x1 = np.array([1,2,3,4,5,6,7,8])
y1 = func1(x1)

#添加噪声
n1 = np.random.normal(0.0,1.0,8)*0.1
y1 = y1*(1+n1)


f1 = np.polyfit(x1, y1, 3)
p1 = np.poly1d(f1)
print('p1 is :\n',p1)


p1 is :
3 2
-1.897 x + 57.77 x – 204.8 x + 177.6

f 1 = − 1.897 x 3 + 57.77 x 2 − 204.8 x + 177.6 f_1=-1.897x^3+57.77x^2-204.8x+177.6 f1=1.897x3+57.77x2204.8x+177.6

xx1 = np.arange(1,9,0.2)
yvals1 = p1(xx1) #拟合y值

#绘图
plot1 = plt.plot(x1, y1, 'o',label='original values')
plot2 = plt.plot(xx1, yvals1, 'r-',label='polyfit values')
plt.xlabel('x1')
plt.ylabel('y1')
plt.legend(loc=4) #指定legend的位置右下角
plt.title('polyfitting')
plt.show()


## 2.自定义函数拟合

### 2.1 自定义函数拟合的实现

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


x2 = np.array([1,2,3,4,5,6,7,8,9,10])
y2 = np.array([0.16,0.63,1.60,3.00,8.00,33.0,73.0,125.0,211.0,310.0])
y2=y2*100


def func2(x, p, q,m):
return m*(1-np.exp(-x*(p+q)))/(1+q/p*np.exp(-(p+q)*x))


popt, pcov = curve_fit(func2, x2, y2)


p = popt[0]
q = popt[1]
m = popt[2]

yvals2 = func2(x2,p,q,m) #拟合y值
print('popt:', popt)
print('系数p:', p)
print('系数q:', q)
print('系数m:', m)
print('系数pcov:', pcov)
print('系数yvals2:', yvals2)


popt: [4.93963593e-04 7.86873973e-01 4.96871803e+04]

[-4.88182871e-06 2.28100736e-03 -1.95238501e+02]
[ 3.60534694e-01 -1.95238501e+02 1.97747550e+07]]

1518.69723981 3252.26832861 6655.68174484 12625.30614774
21284.37699301 30920.18607139]

xx2 = np.arange(1,21)
y2test = func2(xx2,p,q,m)

#绘图
plot1 = plt.plot(x2, y2, 's',label='original values')
plot2 = plt.plot(xx2, y2test, 'r',label='polyfit values')
plt.xlabel('x2')
plt.ylabel('y2')
plt.legend(loc=4) #指定legend的位置右下角
plt.title('curve_fit')
plt.show()


原文作者：BkbK-
原文地址: https://blog.csdn.net/BlacKingZ/article/details/119985295
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。