# python之拟合的实现

```import numpy as np

def linear_regression(x,y):
#y=bx+a，线性回归
num=len(x)
b=(np.sum(x*y)-num*np.mean(x)*np.mean(y))/(np.sum(x*x)-num*np.mean(x)**2)
a=np.mean(y)-b*np.mean(x)
return np.array([b,a])
def f(x):
return 2*x+1
x=np.linspace(-5,5)
y=f(x)+np.random.randn(len(x))#加入噪音
y_fit=np.polyfit(x,y,1)#一次多项式拟合，也就是线性回归
print(linear_regression(x,y))
print(y_fit)```

[1.9937839 1.24167225]

[1.9937839 1.24167225]

```import numpy as np
from matplotlib import pyplot as plt

def f(x):
return x**2+1
def f_fit(x,y_fit):
a,b,c=y_fit.tolist()
return a*x**2+b*x+c
x=np.linspace(-5,5)
y=f(x)+np.random.randn(len(x))#加入噪音
y_fit=np.polyfit(x,y,2)#二次多项式拟合
y_show=np.poly1d(y_fit)#函数优美的形式
print(y_show)#打印
y1=f_fit(x,y_fit)
plt.plot(x,f(x),'r',label='original')
plt.scatter(x,y,c='g',label='before_fitting')#散点图
plt.plot(x,y1,'b--',label='fitting')
plt.title('polyfitting')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()#显示标签
plt.show()```

2

1.001 x - 0.04002 x + 0.8952

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

def f(x):
return 2*np.sin(x)+3
def f_fit(x,a,b):
return a*np.sin(x)+b
def f_show(x,p_fit):
a,b=p_fit.tolist()
return a*np.sin(x)+b
x=np.linspace(-2*np.pi,2*np.pi)
y=f(x)+0.5*np.random.randn(len(x))#加入了噪音
p_fit,pcov=curve_fit(f_fit,x,y)#曲线拟合
print(p_fit)#最优参数
print(pcov)#最优参数的协方差估计矩阵
y1=f_show(x,p_fit)
plt.plot(x,f(x),'r',label='original')
plt.scatter(x,y,c='g',label='before_fitting')#散点图
plt.plot(x,y1,'b--',label='fitting')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()```

[1.91267059 3.04489528]

[[ 9.06910892e-03 -1.83703696e-11]

[-1.83703696e-11 4.44386331e-03]]

1、https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

2、https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.curve_fit.html