python numpy分段线性拟合不稳健?

问题描述

我已经将优雅的解决方案应用于 How to apply piecewise linear fit in Python? 中给出的分段线性拟合。

如图所示(下面给出了源代码),我得到的结果是橙色线,而我期望的是绿色线。平方误差的总和为 3918(橙色)与 377(绿色)。这是因子 10 的差异,应该远高于任何认公差值或任何机器精度。奇怪的是,我确实有类似的数据点,它们大约相对于蓝点向上或向下移动。有了这些,回归表现得非常好。我的意思是可以调整 curve_fit 函数的 kwgargs,因为我确实有关于这个问题的更多信息。但是为什么认值的“免费”回归如此糟糕?在迭代求解过程中是否存在任何数值不稳定性,从而导致远离局部最小值?如果有人提出解释和解决方案,我会非常高兴。

enter image description here

from numpy import array,linspace,piecewise
from scipy import optimize
import matplotlib.pyplot as plt


def piecewise_linear(x,x0,y0,k1,k2):
    return piecewise(x,[x < x0],[lambda x:k1*x + y0-k1*x0,lambda x:k2*x + y0-k2*x0])


x = array([130.,125.,115.,110.,105.,95.,85.,75.,65.,55.,45.,35.,25.,15.,5.,0.])
y = array([  5.,70.,90.,100.,135.,145.,155.,165.,175.,189.,199.,209.,213.])
xs = linspace(min(x),max(x),num=100)
ps = optimize.curve_fit(piecewise_linear,x,y)
# result: ps = array([-124.37010926,393.31034095,-90.9686379,-1.35547041])
# i.e. x_0 is supposed to be in the second quadrant
# OptimizeWarning: Covariance of the parameters Could not be estimated



fig,ax = plt.subplots()
ax.plot(x,y,marker='o',linestyle='None')
ax.plot(xs,piecewise_linear(xs,*ps[0]),label='calculated')
# quick guess / approximate expectation
expected_ps = array([110,90,-1.1,-4])
ax.plot(xs,*expected_ps),label='approx. expected')
ax.legend()
plt.show()

sum_of_squared_errors = lambda params: sum((piecewise_linear(x,*params) - y)**2)
print('errors estimate:',sum_of_squared_errors(ps[0]))  # 3918
print('errors expected',sum_of_squared_errors(expected_ps))  # 377

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)