如何在python中使用scipy.optimize中的leastsq函数将直线和二次线拟合到数据集x和y

use*_*673 10 python numpy scipy least-squares

如何使用scipy.optimize中的leastsq函数将直线和二次方拟合到下面的数据集中?我知道如何使用polyfit来做到这一点.但我需要使用leastsq函数.

以下是x和y数据集:

x: 1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7

y: 6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

Rob*_*bas 19

leastsq()方法查找最小化错误函数的参数集(yExperimental和yFit之间的差异).我使用一个元组来传递线性和二次拟合的参数和lambda函数.

leastsq从第一次猜测(参数的初始元组)开始,并尝试最小化错误函数.最后,如果leastsq成功,它将返回最适合数据的参数列表.(我打印看到它).我希望它能得到最好的问候

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


def main():
   # data provided
   x=np.array([1.0,2.5,3.5,4.0,1.1,1.8,2.2,3.7])
   y=np.array([6.008,15.722,27.130,33.772,5.257,9.549,11.098,28.828])
   # here, create lambda functions for Line, Quadratic fit
   # tpl is a tuple that contains the parameters of the fit
   funcLine=lambda tpl,x : tpl[0]*x+tpl[1]
   funcQuad=lambda tpl,x : tpl[0]*x**2+tpl[1]*x+tpl[2]
   # func is going to be a placeholder for funcLine,funcQuad or whatever 
   # function we would like to fit
   func=funcLine
   # ErrorFunc is the diference between the func and the y "experimental" data
   ErrorFunc=lambda tpl,x,y: func(tpl,x)-y
   #tplInitial contains the "first guess" of the parameters 
   tplInitial1=(1.0,2.0)
   # leastsq finds the set of parameters in the tuple tpl that minimizes
   # ErrorFunc=yfit-yExperimental
   tplFinal1,success=leastsq(ErrorFunc,tplInitial1[:],args=(x,y))
   print " linear fit ",tplFinal1
   xx1=np.linspace(x.min(),x.max(),50)
   yy1=func(tplFinal1,xx1)
   #------------------------------------------------
   # now the quadratic fit
   #-------------------------------------------------
   func=funcQuad
   tplInitial2=(1.0,2.0,3.0)

   tplFinal2,success=leastsq(ErrorFunc,tplInitial2[:],args=(x,y))
   print "quadratic fit" ,tplFinal2
   xx2=xx1

   yy2=func(tplFinal2,xx2)
   plt.plot(xx1,yy1,'r-',x,y,'bo',xx2,yy2,'g-')
   plt.show()

if __name__=="__main__":
   main()
Run Code Online (Sandbox Code Playgroud)