Pass tuple as input argument for scipy.optimize.curve_fit

后端 未结 4 1812
刺人心
刺人心 2021-02-14 20:21

I have the following code:

import numpy as np
from scipy.optimize import curve_fit


def func(x, p): return p[0] + p[1] + x


popt, pcov = curve_fit(func, np.ara         


        
4条回答
  •  不要未来只要你来
    2021-02-14 20:53

    Problem

    When using curve_fit you must explicitly say the number of fit parameters. Doing something like:

    def f(x, *p):
        return sum( [p[i]*x**i for i in range(len(p))] )
    

    would be great, since it would be a general nth-order polynomial fitting function, but unfortunately, in my SciPy 0.12.0, it raises:

    ValueError: Unable to determine number of fit parameters.
    

    Solution

    So you should do:

    def f_1(x, p0, p1):
        return p0 + p1*x
    
    def f_2(x, p0, p1, p2):
        return p0 + p1*x + p2*x**2
    

    and so forth...

    Then you can call using the p0 argument:

    curve_fit(f_1, xdata, ydata, p0=(0,0))
    

提交回复
热议问题