python中有一个库来做分段线性回归吗?我想自动为我的数据添加多行以获得如下内容:
顺便提一句。我知道分段的数量。
大概numpy.piecewise()
可以使用 Numpy 的工具。
此处显示了更详细的描述:
如何在 Python 中应用分段线性拟合?
如果这不是所需要的,那么您可能会在这些问题中找到一些有用的信息:
https ://datascience.stackexchange.com/questions/8266/is-there-a-library-that-would-perform-segmented- linear-regression-in-python
和这里:
https ://datascience.stackexchange.com/questions/8457/python-library-for-segmented-regression-aka-piecewise-regression
正如上面评论中提到的,分段线性回归带来了许多自由参数的问题。因此,我决定放弃使用 n_segments * 3 - 1 个参数(即 n_segments - 1 个段位置、n_segment y-offests、n_segment 斜率)并执行数值优化的方法。相反,我寻找已经具有大致恒定斜率的区域。
算法
使用决策树而不是聚类算法来获取连接段而不是(非相邻)点集。分割的细节可以通过决策树参数进行调整(目前max_leaf_nodes
)。
代码
import numpy as np
import matplotlib.pylab as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
# parameters for setup
n_data = 20
# segmented linear regression parameters
n_seg = 3
np.random.seed(0)
fig, (ax0, ax1) = plt.subplots(1, 2)
# example 1
#xs = np.sort(np.random.rand(n_data))
#ys = np.random.rand(n_data) * .3 + np.tanh(5* (xs -.5))
# example 2
xs = np.linspace(-1, 1, 20)
ys = np.random.rand(n_data) * .3 + np.tanh(3*xs)
dys = np.gradient(ys, xs)
rgr = DecisionTreeRegressor(max_leaf_nodes=n_seg)
rgr.fit(xs.reshape(-1, 1), dys.reshape(-1, 1))
dys_dt = rgr.predict(xs.reshape(-1, 1)).flatten()
ys_sl = np.ones(len(xs)) * np.nan
for y in np.unique(dys_dt):
msk = dys_dt == y
lin_reg = LinearRegression()
lin_reg.fit(xs[msk].reshape(-1, 1), ys[msk].reshape(-1, 1))
ys_sl[msk] = lin_reg.predict(xs[msk].reshape(-1, 1)).flatten()
ax0.plot([xs[msk][0], xs[msk][-1]],
[ys_sl[msk][0], ys_sl[msk][-1]],
color='r', zorder=1)
ax0.set_title('values')
ax0.scatter(xs, ys, label='data')
ax0.scatter(xs, ys_sl, s=3**2, label='seg lin reg', color='g', zorder=5)
ax0.legend()
ax1.set_title('slope')
ax1.scatter(xs, dys, label='data')
ax1.scatter(xs, dys_dt, label='DecisionTree', s=2**2)
ax1.legend()
plt.show()
有piecewise-regression
python 库可以做到这一点。Github 链接。
带有 1 个断点的简单示例。为了演示,首先生成一些示例数据:
import numpy as np
alpha_1 = -4
alpha_2 = -2
constant = 100
breakpoint_1 = 7
n_points = 200
np.random.seed(0)
xx = np.linspace(0, 20, n_points)
yy = constant + alpha_1*xx + (alpha_2-alpha_1) * np.maximum(xx - breakpoint_1, 0) + np.random.normal(size=n_points)
然后拟合分段模型:
import piecewise_regression
pw_fit = piecewise_regression.Fit(xx, yy, n_breakpoints=1)
pw_fit.summary()
并绘制它:
import matplotlib.pyplot as plt
pw_fit.plot()
plt.show()
示例 2-4 断点。现在让我们看一些与原始问题类似的数据,有 4 个断点。
import numpy as np
gradients = [0,2,1,2,-1,0]
constant = 0
breakpoints = [-4, -2, 1, 4]
n_points = 200
np.random.seed(0)
xx = np.linspace(-10, 10, n_points)
yy = constant + gradients[0]*xx + np.random.normal(size=n_points)*0.5
for bp_n in range(len(breakpoints)):
yy += (gradients[bp_n+1] - gradients[bp_n]) * np.maximum(xx - breakpoints[bp_n], 0)
拟合模型并绘制它:
import piecewise_regression
import matplotlib.pyplot as plt
pw_fit = piecewise_regression.Fit(xx, yy, n_breakpoints=4)
pw_fit.plot()
plt.xlabel("x")
plt.ylabel("y")
plt.ylim(-10, 20)
plt.show()
此Google Colab 笔记本中的代码示例
您只需要按升序排列 X 并创建几个线性回归。您可以使用 sklearn 中的 LinearRegression。
例如,将曲线分成 2 将是这样的:
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
X = np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5])
Y = X**2
X=X.reshape(-1,1)
reg1 = LinearRegression().fit(X[0:6,:], Y[0:6])
reg2 = LinearRegression().fit(X[6:,:], Y[6:])
fig = plt.figure('Plot Data + Regression')
ax1 = fig.add_subplot(111)
ax1.plot(X, Y, marker='x', c='b', label='data')
ax1.plot(X[0:6,],reg1.predict(X[0:6,]), marker='o',c='g', label='linear r.')
ax1.plot(X[6:,],reg2.predict(X[6:,]), marker='o',c='g', label='linear r.')
ax1.set_title('Data vs Regression')
ax1.legend(loc=2)
plt.show()
我做了一个类似的实现,这里是代码: https ://github.com/mavaladezt/Segmented-Algorithm