Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scipy fitting with parameters in a vector

As far as I know, the Scipy curve_fit function takes in the fitting parameters explicitly. E.g., when fitting a polynomial:

def func(x, c0, c1, c2):
    return c0 + c1 * x + c2 * x**2

Is there possibly a way (perhaps another equivalent function) to define the parameters via a vector? E.g.:

def func(x, C):
    y = 0.0
    for i, ci in enumerate(C):
        y += ci * x**i
    return y

I am trying to fit a complicated function with 24 parameters and explicitly defining parameters is rather painful.

like image 719
petervanya Avatar asked Mar 18 '26 18:03

petervanya


1 Answers

Yes, it is possible, but you must know the number of arguments beforehand (which you seem to).

Example:

from scipy.optimize import curve_fit

def func(x, *C):
    y = sum(c * x ** n for n, c in enumerate(C))
    return y

However, you need to specify the p0 argument in the call to curve_fit; in this case, since you know you have 24 parameters, if you have an initial guess for their values, you could pass an array containing 24 values. If not, you can just use np.ones(24).

like image 183
gmds Avatar answered Mar 20 '26 09:03

gmds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!