[Python] Use `curve_fit` with `partial` using named parameters instead of positional parameters

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use curve_fit on a function for which I want to freeze one or more parameters using partial.

    E.g. this pattern, which is working:

    from scipy.optimize import curve_fit
    from functools import partial

    # Irrelevant
    xdata = [0]*5
    ydata = xdata


    def func(x, a, b):
    return x + a + b

    pfunc = partial(func, 2)
    popt, _ = curve_fit(pfunc, xdata, ydata)
    print(popt)
    # > [-2.]


    What I want to do is provide partial with the parameter(s) as named parameters, not positional. This however seems not to work reliably.

    from scipy.optimize import curve_fit
    from functools import partial

    # Irrelevant
    xdata = [0]*5
    ydata = xdata


    def func(x, a, b):
    return x + a + b

    pfunc = partial(func, b=2)
    popt, _ = curve_fit(pfunc, xdata, ydata)
    print(popt)
    # > [-2.]

    pfunc = partial(func, a=2)
    popt, _ = curve_fit(pfunc, xdata, ydata)
    print(popt)
    # > raises ValueError: Unable to determine number of fit parameters.



    Am I doing something wrong? Is there a way to get this to work? In my application, the func may take n>=3 of which I want to fix up to (n-1).

    Continue reading...

Compartilhe esta Página