Fitting piecewise function in Python

前端 未结 2 1669
你的背包
你的背包 2020-12-11 07:29

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.<

相关标签:
2条回答
  • 2020-12-11 07:54

    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
    
    def fitfunc(x,p):
       if x>p:
          return x-p
       else:
          return -(x-p)
    
    fitfunc_vec = np.vectorize(fitfunc) #vectorize so you can use func with array
    
    def fitfunc_vec_self(x,p):
      y = np.zeros(x.shape)
      for i in range(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 error
    print popt
    print pcov
    

    Output:

    [ 6.03608994]
    [[ 0.00124934]]
    
    0 讨论(0)
  • 2020-12-11 08:12

    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.]

    0 讨论(0)
提交回复
热议问题