思路:确定所有的分割点(x*,y*)以及首尾的斜率(k*)
参考:两段的分段函数;三段的分段函数;scipy.optimize.curve_fit
代码:
from scipy import optimize
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float)
y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59,
84.47, 98.36, 102.25, 106.14, 110.03])
# 一个输入序列,4个未知参数,2个分段函数
def piecewise_linear(x, x0, y0, k1, k2):
# x=x0 ⇒ lambda x: k2*x + y0 - k2*x0
return np.piecewise(x, [x < x0, x >= x0], [lambda x:k1*x + y0-k1*x0,
lambda x:k2*x + y0-k2*x0])
def piecewise_linear3(x,x0,x1,y0,y1,k0,k1):
return np.piecewise(x , [x <= x0, np.logical_and(x0x1] ,
[lambda x:k0*(x-x0) + y0,#根据点斜式构建函数
lambda x:(x-x0)*(y1-y0)/(x1-x0)+y0,#根据两点式构建函数
lambda x:k1*(x-x1) + y1])
# 用已有的 (x, y) 去拟合 piecewise_linear 分段函数
p , e = optimize.curve_fit(piecewise_linear3, x, y,bounds=(0, [16,16,120,120,10,10]))
xd = np.linspace(0, 15, 100)
plt.plot(x, y, "o")
plt.plot(xd, piecewise_linear3(xd, *p))
用3段的函数拟合实际2段的数据,可能出现报错
OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning)
参考:限制参数取值
可以帮助解决报错,但是实际拟合效果和bound设置有关系,bound设置的比较好,拟合就会比较准
拟合比较准的用的bounds=(0, [6,13,20,120,4,6])
没有具体研究curve_fit所以原因还不明确。