Home > OS >  How can I use curve_fit for functions that involve case-splitting?
How can I use curve_fit for functions that involve case-splitting?

Time:12-13

I want to use curve_fit for functions that involve case-splitting.
However python throws Error.

Does curve_fit not support such a function ? Or is there is any problem at function definition ?

Example)

from scipy.optimize import curve_fit
import numpy as np

def slope_devided_by_cases(x,a,b):
    if x < 4:
        return a*x   b
    else:
        return 4*a   b

data_x =  [1,2,3,4,5,6,7,8,9]  # x
data_y  = [45,46,42,36,27,23,21,13,11]  # y
coef, cov = curve_fit(slope_devided_by_cases, data_x, data_y)

Error)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\Users\Lisa~1\AppData\Local\Temp/ipykernel_1516/1012358816.py in <module>
     10 data_x =  [1,2,3,4,5,6,7,8,9]  # x
     11 data_y  = [45,46,42,36,27,23,21,13,11]  # y
---> 12 coef, cov = curve_fit(slope_devided_by_cases, data_x, data_y)

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    787         # Remove full_output from kwargs, otherwise we're passing it in twice.
    788         return_full = kwargs.pop('full_output', False)
--> 789         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    790         popt, pcov, infodict, errmsg, ier = res
    791         ysize = len(infodict['fvec'])

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    408     if not isinstance(args, tuple):
    409         args = (args,)
--> 410     shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
    411     m = shape[0]
    412 

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
     22 def _check_func(checker, argname, thefunc, x0, args, numinputs,
     23                 output_shape=None):
---> 24     res = atleast_1d(thefunc(*((x0[:numinputs],)   args)))
     25     if (output_shape is not None) and (shape(res) != output_shape):
     26         if (output_shape[0] != 1):

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in func_wrapped(params)
    483     if transform is None:
    484         def func_wrapped(params):
--> 485             return func(xdata, *params) - ydata
    486     elif transform.ndim == 1:
    487         def func_wrapped(params):

C:\Users\Lisa~1\AppData\Local\Temp/ipykernel_1516/1012358816.py in slope_devided_by_cases(x, a, b)
      3 
      4 def slope_devided_by_cases(x,a,b):
----> 5     if x < 4:
      6         return a*x   b
      7     else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I want to use curve_fit for functions that involve case-splitting such as above example.

CodePudding user response:

The problem is that x < 4 is not a boolean scalar value because curve_fit will evaluate your function with an np.ndarray x (your given x data points), not a scalar value. Consequently, x < 4 will give you an array of boolean values.

That said, you could rewrite your function by using NumPy's vectorized operations:

def slope_devided_by_cases(x,a,b):
    return (x < 4) * (a*x   b)   (x >= 4) * (4*a b)

Alternatively, you could use enter image description here

  • Related