参考链接:
- https://blog.youkuaiyun.com/qq_39052287/article/details/105535961
- https://www.researchgate.net/publication/331231072_pwlf_A_Python_Library_for_Fitting_1D_Continuous_Piecewise_Linear_Functions
pwlf: 一个用于拟合一维数据的分段线性拟合的 Python 库。连续的分段线性拟合有断点,断点代表线段的终止点。
- 如果断点位置已知,则使用最小二乘法拟合来求解最佳的连续分片线性函数。
- 如果断点未知,但已知所需的线段数,则使用全局优化来找到最佳断点位置。该优化过程针对不同的断点位置多次求解最小二乘法拟合。
import pwlf
# 分段拟合
data_ = data.sort_values(by='AI')
x = data_['AI']
y = data_['CV']
my_pwlf = pwlf.PiecewiseLinFit(x, y) # 使用 pwlf 进行分段线性回归
breaks = my_pwlf.fit(4) # 设置分段数量为4,即三个转折点
turning_points = list(breaks[1:-1]) # 获取转折点
turning_points.append(x.max()) # 添加最后一个索引位置以便处理最后一段
start_index = 0
for i, turning_point in enumerate(turning_points):
end_index = np.searchsorted(x, turning_point)# 找到接近转折点值的索引位置
x_segment = x[start_index:end_index]
y_segment = y[start_index:end_index]
popt, _ = curve_fit(func_liner, x_segment, y_segment)
plt.plot(np.sort(x_segment), func_liner(np.sort(x_segment), *popt),color='blue')
start_index = end_index