Python Least squares fitting

Source: Internet
Author: User
Tags sin

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.