1.由已知断点位置来拟合
如果知道断点位置,可以采用最小二乘法拟合
import pwlf
x0 = np.array([min(x), 0.039, 0.10, max(x)])
my_pwlf = pwlf.PiecewiseLinFit(x, y)
my_pwlf.fit_with_breaks(x0)
xHat = np.linspace(min(x), max(x), num=10000)
yHat = my_pwlf.predict(xHat)
plt.figure()
plt.plot(x, y, 'o')
plt.plot(xHat, yHat, '-')
plt.show()
2.指定数量的分段拟合
使用全局优化来找到使平方误差和最小的断点位置。这里使用了scipy的差分进化算法。
# initialize piecewise linear fit with your x and y data
import pwlf
my_pwlf = pwlf.PiecewiseLinFit(x, y)
# fit the data for four line segments
res = my_pwlf.fit(4)
# predict for the determined points
xHat = np.linspace(min(x), max(x), num=10000)
yHat = my_pwlf.predict(xHat)
# plot the results
plt.figure()
plt.plot(x, y, 'o')
plt.plot(xHat, yHat, '-')
plt.show()
3.指定数量的分段快速拟合
执行指定数量的分段快速拟合,使用基于梯度下降法的最优迭代算法(深度学习优化方法)。对于少量的起点来说,它比差分进化算法更快。
# initialize piecewise linear fit with your x and y data
import pwlf
my_pwlf = pwlf.PiecewiseLinFit(x, y)
# fit the data for four line segments
# this performs 3 multi-start optimizations
res = my_pwlf.fitfast(4, pop=3)
# predict for the determined points
xHat = np.linspace(min(x), max(x), num=10000)
yHat = my_pwlf.predict(xHat)
# plot the results
plt.figure()
plt.plot(x, y, 'o')
plt.plot(xHat, yHat, '-')
plt.show()
参考文献
1.用PYTHON进行自动分段多项式拟合
2.pwlf: A Python Library for Fitting 1D Continuous Piecewise Linear Functions.