Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

scipy - python nonlinear least squares fitting

I am a little out of my depth in terms of the math involved in my problem, so I apologise for any incorrect nomenclature.

I was looking at using the scipy function leastsq, but am not sure if it is the correct function. I have the following equation:

eq = lambda PLP,p0,l0,kd : 0.5*(-1-((p0+l0)/kd) + np.sqrt(4*(l0/kd)+(((l0-p0)/kd)-1)**2))

I have data (8 sets) for all the terms except for kd (PLP,p0,l0). I need to find the value of kd by non-linear regression of the above equation. From the examples I have read, leastsq seems to not allow for the inputting of the data, to get the output I need.

Thank you for your help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a bare-bones example of how to use scipy.optimize.leastsq:

import numpy as np
import scipy.optimize as optimize
import matplotlib.pylab as plt

def func(kd,p0,l0):
    return 0.5*(-1-((p0+l0)/kd) + np.sqrt(4*(l0/kd)+(((l0-p0)/kd)-1)**2))

The sum of the squares of the residuals is the function of kd we're trying to minimize:

def residuals(kd,p0,l0,PLP):
    return PLP - func(kd,p0,l0)

Here I generate some random data. You'd want to load your real data here instead.

N=1000
kd_guess=3.5  # <-- You have to supply a guess for kd
p0 = np.linspace(0,10,N)
l0 = np.linspace(0,10,N)
PLP = func(kd_guess,p0,l0)+(np.random.random(N)-0.5)*0.1

kd,cov,infodict,mesg,ier = optimize.leastsq(
    residuals,kd_guess,args=(p0,l0,PLP),full_output=True,warning=True)

print(kd)

yields something like

3.49914274899

This is the best fit value for kd found by optimize.leastsq.

Here we generate the value of PLP using the value for kd we just found:

PLP_fit=func(kd,p0,l0)

Below is a plot of PLP versus p0. The blue line is from data, the red line is the best fit curve.

plt.plot(p0,PLP,'-b',p0,PLP_fit,'-r')
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...