Using scipy curve_fit for a variable number of parameters

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]

Leave a Comment