0

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). 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
Jake
  • 11
  • 3
  • Hi, and welcome. My tip, just use `least_squares`. An example can be found [here](https://stackoverflow.com/a/44805318/803359) – mikuszefski Mar 23 '21 at 13:11

1 Answers1

0

Use partial functools. Instead of using curve_fit(xdata, ydata, func) three times, you will have:

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.

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)
Guimoute
  • 4,407
  • 3
  • 12
  • 28
  • Hi, I am grateful for your quick answer. I guess I may not make myself clear. I am trying to solve this system with two share parameters(a, b) simultaneously not independently. p1 is different for different ydata sets. Would you give me some advice? Appreciate your help. – Jake Mar 23 '21 at 04:20