简体   繁体   English

使用curve_fit在python中具有共享参数的非线性回归(全局)

[英]Nonlinear regression(globally) with shared parameters in python by using curve_fit

I am trying to do a regression of a nonlinear system with a set of data.我正在尝试使用一组数据对非线性系统进行回归。

import numpy as np
xdata = np.array([3, 6, 9, 12, 24])  #ydata1 and ydata2 use the same xdata
ydata1 = np.array([5e-4, 5.03e-4, 4.56e-4, 4,89e-4, 4.85e-4])
ydata2 = np.array([1.7e-3, 1.74e-3, 1.64e-3, 1.74e-3, 1.69e-3])
xdata3 = np.array([3, 6, 9, 18])
ydata3 = np.array([2.74e-3, 2.68e-3, 2.62e-3, 2.92e-3])

These three lines use the same function except one parameter p1, would I know whether there is a simple example to illustrate how to use curve_fit to solve this system simultaneously(globally).这三行使用相同的function,除了一个参数p1,我知道是否有一个简单的例子来说明如何使用curve_fit同时(全局)解决这个系统。 Thank you so much!太感谢了!

def func(a, b, x):
    return a * b * p1 * x / ((1 + np.sqrt(b * x)) ** 2)
    ### p1 is 6, 18, 30 for ydata1, ydata2, ydata3

Use partial functools.使用部分功能工具。 Instead of using curve_fit(xdata, ydata, func) three times, you will have:而不是使用curve_fit(xdata, ydata, func)三次,您将拥有:

from functools import partial
f1 = partial(func, p1=6)
f2 = partial(func, p1=18)
f3 = partial(func, p1=30)
popt1, pcov1 = curve_fit(xdata, ydata1, f1)
popt2, pcov2 = curve_fit(xdata, ydata2, f2)
popt3, pcov3 = curve_fit(xdata3, ydata3, f3)
ydata1_fit = f1(xdata, *popt1)
ydata2_fit = f2(xdata, *popt2)
ydata3_fit = f3(xdata3, *popt3)

To avoid repetition, we could shove that into a function.为避免重复,我们可以将其放入 function。

def fitter(xdata, ydata, p1):
    f = partial(func, p1=p1)
    popt, pcov = curve_fit(xdata, ydata, f)
    ydata_fit = f(xdata, *popt)
    return ydata_fit

ydata1_fit = fitter(xdata, ydata1, 6)
ydata2_fit = fitter(xdata, ydata2, 18)
ydata3_fit = fitter(xdata3, ydata3, 30)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM