【问题标题】:Fitting piecewise function in Python在 Python 中拟合分段函数
【发布时间】:2012-06-23 04:40:49
【问题描述】:

我正在尝试将分段定义的函数拟合到 Python 中的数据集。我已经搜索了很长时间,但我没有找到答案是否可能。

要对我正在尝试做的事情有个印象,请查看以下示例(这对我不起作用)。在这里,我试图将移位的绝对值函数 (f(x) = |x-p|) 拟合到以 p 作为拟合参数的数据集。

import scipy.optimize as so
import numpy as np

def fitfunc(x,p):
   if x>p:
      return x-p
   else:
      return -(x-p)

fitfunc = np.vectorize(fitfunc) #vectorize so you can use func with array

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

popt, pcov = so.curve_fit(fitfunc, x, y) #fitting routine that gives error

有什么方法可以在 Python 中实现这一点吗?

在 R 中这样做的一种方法是:

# Fit of a absolute value function f(x)=|x-p|

f.lr <- function(x,p) {
    ifelse(x>p, x-p,-(x-p))
}
x <- seq(0,10)  #
y <- f.lr(x,6) + rnorm (length(x),0,2)
plot(y ~ x)
fit.lr <- nls(y ~ f.lr(x,p), start = list(p = 0), trace = T, control = list(warnOnly = T,minFactor = 1/2048))
summary(fit.lr)
coefficients(fit.lr)
p.fit <- coefficients(fit.lr)["p"]
x_fine <- seq(0,10,length.out=1000)
lines(x_fine,f.lr(x_fine,p.fit),type='l',col='red')
lines(x,f.lr(x,6),type='l',col='blue')

经过更多研究,我找到了一种方法。在这个解决方案中,我不喜欢我必须自己定义错误函数的事实。此外,我不确定为什么它必须采用这种 lambda 样式。因此,非常欢迎任何形式的建议或更复杂的解决方案。

import scipy.optimize as so
import numpy as np
import matplotlib.pyplot as plt

def fitfunc(p,x): return x - p if x > p else p - x 

def array_fitfunc(p,x):
    y = np.zeros(x.shape)
    for i in range(len(y)):
        y[i]=fitfunc(x[i],p)
    return y

errfunc = lambda p, x, y: array_fitfunc(p, x) - y # Distance to the target function

x=np.arange(1,10)
x_fine=np.arange(1,10,0.1)
y=array_fitfunc(6,x)+1*np.random.randn(len(x)) #data with noise

p1, success = so.leastsq(errfunc, -100, args=(x, y), epsfcn=1.) # -100 is the initial value for p; epsfcn sets the step width

plt.plot(x,y,'o') # fit data
plt.plot(x_fine,array_fitfunc(6,x_fine),'r-') #original function
plt.plot(x_fine,array_fitfunc(p1[0],x_fine),'b-') #fitted version
plt.show()

【问题讨论】:

    标签: python numpy scipy curve-fitting piecewise


    【解决方案1】:

    为了在这里完成这个,我将分享我自己对这个问题的最终解决方案。为了接近我原来的问题,您只需要自己定义矢量化函数,而不是使用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
    

    输出:

    [ 6.03608994]
    [[ 0.00124934]]
    

    【讨论】:

      【解决方案2】:

      你不能简单地将 fitfunc 替换为

      def fitfunc2(x, p):
          return np.abs(x-p)
      

      然后产生类似的东西

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

      使用 switch 函数和/或像 where 这样的构建块来替换分支,这应该可以扩展到更复杂的表达式,而无需调用 vectorize

      [PS:最小二乘示例中的errfunc 不需要是 lambda。你可以写

      def errfunc(p, x, y):
          return array_fitfunc(p, x) - y
      

      如果你喜欢的话。]

      【讨论】:

      • 您好帝斯曼,感谢您的回答。您能否提供一些有关使用 where 或 switch 功能的提示?理想情况下,我需要一个由两个线性函数组成的分段函数,其中两个斜率 m1、m2 和断点 p 是拟合参数,例如x

        p 为 m2x+t2。

      • @cass:类似这样的东西 - fitfunc(x,p): ret=np.copy(x)-p; ret[ret&lt;=0]=-ret[ret&lt;=0]; return ret。在这里,我使用布尔数组 ret&lt;=p 进行索引。要了解如何使用where,您还可以使用np.where(ret&lt;=p)[0] 返回的索引数组进行索引...在更复杂的情况下可能有用吗?
      猜你喜欢
      • 2012-09-11
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2020-10-31
      • 2018-10-03
      相关资源
      最近更新 更多