Http://blog.sina.com.cn/s/blog_aed5bd1d0102vid7.html
When you're done with interpolation, it's natural to learn to fit. Refer to Http://wiki.klniu.com/wiki/Python/Modules/Scipy.
1. Polynomial-fitting Example:
Import Matplotlib.pyplot as Plt
Import NumPy as NP
#潘海东, 2014/1/13
x = Np.arange (1, 17, 1)
y = Np.array ([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])
Z1 = Np.polyfit (x, Y, 3) #用3次多项式拟合
P1 = np.poly1d (z1)
Print (p1) #在屏幕上打印拟合多项式
YVALS=P1 (x) #也可以使用yvals =np.polyval (z1,x)
Plot1=plt.plot (x, y, ' * ', label= ' original values ')
Plot2=plt.plot (x, Yvals, ' R ', label= ' polyfit values ')
Plt.xlabel (' x axis ')
Plt.ylabel (' Y axis ')
Plt.legend (loc=4) #指定legend的位置, the reader can help its usage
Plt.title (' polyfitting ')
Plt.show ()
Plt.savefig (' P1.png ')
2. Specifying function Fitting
#潘海东, 2014/1/13
#使用非线性最小二乘法拟合
Import Matplotlib.pyplot as Plt
From scipy.optimize import Curve_fit
Import NumPy as NP
#用指数形式来拟合
x = Np.arange (1, 17, 1)
y = Np.array ([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])
def func (x,a,b):
Return A*np.exp (b/x)
popt, Pcov = Curve_fit (func, x, y)
A=popt[0] #popt里面是拟合系数, readers can help their use by themselves
B=POPT[1]
Yvals=func (X,A,B)
Plot1=plt.plot (x, y, ' * ', label= ' original values ')
Plot2=plt.plot (x, Yvals, ' R ', label= ' curve_fit values ')
Plt.xlabel (' x axis ')
Plt.ylabel (' Y axis ')
Plt.legend (loc=4) #指定legend的位置, the reader can help its usage
Plt.title (' Curve_fit ')
Plt.show ()
Plt.savefig (' P2.png ')
Python curve fitting