Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scipy curve_fit for a variable number of parameters

I have a fitting function which has the form:

def fit_func(x_data, a, b, c, N)

where a, b, c are lists of lenth N, every entry of which is a variable parameter to be optimized in scipy.optimize.curve_fit(), and N is a fixed number used for loop index control.

Following this question I think I am able to fix N, but I currently am calling curve_fit as follows:

params_0 = [a_init, b_init, c_init]
popt, pcov = curve_fit(lambda x, a, b, c: fit_func(x, a, b, c, N), x_data, y_data, p0=params_0)

I get an error: lambda() takes exactly Q arguments (P given)

where Q and P vary depending on how I am settings things up.

So: is this even possible, for starters? Can I pass lists as arguments to curve_fit and have the behavior I am hoping for wherein it treats list elements as individual parameters? And assuming that the answer is yes, what I am doing wrong with my function call?

like image 743
KBriggs Avatar asked Aug 31 '25 04:08

KBriggs


1 Answers

The solution here is to write a wrapper function that takes your argument list and translates it to variables that the fit function understands. This is really only necessary since I am working qwith someone else's code, in a more direct application this would work without the wrapper layer. Basically

def wrapper_fit_func(x, N, *args):
    a, b, c = list(args[0][:N]), list(args[0][N:2*N]), list(args[0][2*N:3*N])
    return fit_func(x, a, b, c, N)

and to fix N you have to call it in curve_fit like this:

popt, pcov = curve_fit(lambda x, *params_0: wrapper_fit_func(x, N, params_0), x, y, p0=params_0)

where

params_0 = [a_1, ..., a_N, b_1, ..., b_N, c_1, ..., c_N]
like image 77
KBriggs Avatar answered Sep 03 '25 20:09

KBriggs