Skip to content Skip to sidebar Skip to footer

Fitting Piecewise Function In Python

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. To get an

Solution 1:

To finish this up here, I'll share my own final solution to the problem. In order to stay close to my original question, you just have to define the vectorized function yourself and not use np.vectorize.

import scipy.optimize as so
import numpy as np

deffitfunc(x,p):
   if x>p:
      return x-p
   else:
      return -(x-p)

fitfunc_vec = np.vectorize(fitfunc) #vectorize so you can use func with arraydeffitfunc_vec_self(x,p):
  y = np.zeros(x.shape)
  for i inrange(len(y)):
    y[i]=fitfunc(x[i],p)
  return y


x=np.arange(1,10)
y=fitfunc_vec_self(x,6)+0.1*np.random.randn(len(x))

popt, pcov = so.curve_fit(fitfunc_vec_self, x, y) #fitting routine that gives errorprint popt
print pcov

Output:

[ 6.03608994]
[[ 0.00124934]]

Solution 2:

Couldn't you simply replace fitfunc with

deffitfunc2(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

deferrfunc(p, x, y):
    return array_fitfunc(p, x) - y

instead, if you liked.]

Post a Comment for "Fitting Piecewise Function In Python"