Fitting piecewise function in Python

前端 未结 2 1671
你的背包
你的背包 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 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.]

提交回复
热议问题