Knowing the function form, Python fits function parameters with least squares
Example:
#-*-coding:utf-8-*-#Least squares fitting#Knowing the function form, the parameters of the fitted function#by using the LEASTSQ function to fit the data of experimental data x and Y1 with noise, we can find three parameters of sine relation between x and real data y0: A, K, ThetaImportNumPy as NP fromScipy.optimizeImportleastsqImportMatplotlib.pyplot as PLdeffunc (x,p):"""fit function A*sin (2*pi*k*x +theta)"""A, K, Theta=P#print A, K, Theta returnA*np.sin (2*np.pi*k*x+Theta)defresiduals (p, y, x):returnY-func (x, p) x= Np.linspace (0, -2*np.pi, 100) A, K, Theta= Ten, 0.34, NP.PI/6#real Data function parametersY0 =func (x, [A, K, Theta]) y1= Y0 +Np.random.randn (len (x)) P0= [7, 0.2, 0]#function Fitting ParametersPLSQ = LEASTSQ (residuals, P0, args=(y1, x))PrintU"true Parameters:", [A, K, Theta]PrintU"Fitting Parameters:", PLSQ[0]PL.CLF () pl.plot (x, y0, label=u"Real Data:") Pl.plot (x, y1, label=u"Noise Data") Pl.plot (x, func (x, Plsq[0]), label=u"Fit Data") Pl.legend () pl.show ()
Reference:
scipy-Numerical Calculation Library
Optimization (scipy.optimize)
Python Least squares fitting