Skip to content Skip to sidebar Skip to footer

Python/curve_fit: Cannot Pass Array With Init Guess

I have this function to compute some sort of polynomial: def pipoly(df,pj): n=np.size(pj) p=pj[0] for j in range(1,n): p+=pj[j]*df**j return p pj is suppos

Solution 1:

Your statement:

pj is supposed to be an array that contains the coefficients of the polynomial;

is wrong. According to curve_fit() docs:

scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=(-inf, inf), method=None, jac=None, **kwargs)[source] Use non-linear least squares to fit a function, f, to data.

Assumes ydata = f(xdata, *params) + eps

That means that your pipoly() function, to be used by curve_fit() must take a number of arguments equal to the number of parameters of you polynomial plus one (the variable, which is the first argument). The error:

TypeError: pipoly() takes 2 positional arguments but 3 were given?

is telling you that pipoly receives 3 arguments because you probably were testing a linear polinomyal, so the three arguments were the independent variable and two parameter (the [f-f0[j] for f in f_df[if0[j]:if0[i]]] stuff is a 2-length list). As you write it, instead it takes 2 argument only.

You can easily solve your problem by adding an asterisk before pj:

defpipoly(df,*pj):
    n=len(pj) #len() is sufficient here, but np.size() works too.
    p=pj[0]
    for j inrange(1,n):
        p+=pj[j]*df**j
    return p

This way your function accepts a variable number of arguments. Here more on the meaning and the use of the asterisk in python function parameters.

Post a Comment for "Python/curve_fit: Cannot Pass Array With Init Guess"