Fitting piecewise function in Python

只愿长相守 提交于 2019-11-28 12:32:56
cass

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!