I\'m trying to fit a piecewise defined function to a data set in Python. I\'ve searched for quite a while now, but I haven\'t found an answer whether it is possible or not.<
Couldn't you simply replace fitfunc with
def fitfunc2(x, p):
return np.abs(x-p)
which then produces something like
>>> x = np.arange(1,10)
>>> y = fitfunc2(x,6) + 0.1*np.random.randn(len(x))
>>>
>>> so.curve_fit(fitfunc2, x, y)
(array([ 5.98273313]), array([[ 0.00101859]]))
Using a switch function and/or building blocks like where
to replace branches, this should scale up to more complicated expressions without needing to call vectorize
.
[PS: the errfunc
in your least squares example doesn't need to be a lambda. You could write
def errfunc(p, x, y):
return array_fitfunc(p, x) - y
instead, if you liked.]