python中scipy.optimize,如何在Python中使用scipy.optimize中的scipy.optimize的Minimumsq函数以将直线和二次线都适合数据集x和y...

How would i fit a straight line and a quadratic to the data set below using the leastsq function from scipy.optimize? I know how to use polyfit to do it. But i need to use leastsq function.

Here are the x and y data sets:

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

Can someone help me out please?

解决方案

The leastsq() method finds the set of parameters that minimize the error function ( difference between yExperimental and yFit).

I used a tuple to pass the parameters and lambda functions for the linear and quadratic fits.

leastsq starts from a first guess ( initial Tuple of parameters) and tries to minimize the error function. At the end, if leastsq succeeds, it returns the list of parameters that best fit the data. ( I printed to see it).

I hope it works

best regards

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值