python非线性最小二乘拟合 [英] python nonlinear least squares fitting

查看:132
本文介绍了python非线性最小二乘拟合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我的问题所涉及的数学而言,我有点超出我的深度,因此对于任何不正确的命名法,我深表歉意.

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

我正在考虑使用 scipy 函数 leastsq,但不确定它是否是正确的函数.我有以下等式:

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

我有除 kd (PLP,p0,l0) 之外的所有项的数据(8 组).我需要通过上述方程的非线性回归找到 kd 的值.从我读过的例子来看,leastsq 似乎不允许输入数据,以获得我需要的输出.

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.

感谢您的帮助

推荐答案

这是一个如何使用 scipy.optimize.leastsq 的基本示例:

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

残差的平方和是我们试图最小化的kd函数:

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)

产生类似的东西

3.49914274899

这是 optimize.leastsq 找到的 kd 的最佳拟合值.

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

这里我们使用刚刚找到的 kd 的值生成 PLP 的值:

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

PLP_fit=func(kd,p0,l0)

下面是 PLPp0 的关系图.蓝线来自数据,红线是最佳拟合曲线.

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

这篇关于python非线性最小二乘拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆