注意
转到末尾 下载完整示例代码。或通过 JupyterLite 或 Binder 在浏览器中运行此示例
Theil-Sen 回归#
在合成数据集上计算 Theil-Sen 回归。
有关回归器的更多信息,请参阅Theil-Sen 估计器:基于广义中位数估计器。
与 OLS(普通最小二乘)估计器相比,Theil-Sen 估计器对异常值具有鲁棒性。在简单线性回归的情况下,其崩溃点约为 29.3%,这意味着它在二维情况下可以容忍高达 29.3% 的任意损坏数据(异常值)。
模型估计通过计算所有可能 p 个子样本点组合的子总体斜率和截距来完成。如果拟合截距,p 必须大于或等于 n_features + 1。最终的斜率和截距定义为这些斜率和截距的空间中位数。
在某些情况下,Theil-Sen 的性能优于RANSAC,后者也是一种鲁棒方法。下面的第二个示例说明了这一点,其中相对于 x 轴的异常值扰乱了 RANSAC。调整 RANSAC 的 residual_threshold
参数可以补救此问题,但通常需要关于数据和异常值性质的先验知识。由于 Theil-Sen 的计算复杂性,建议仅在样本和特征数量较小的问题中使用它。对于较大的问题,max_subpopulation
参数将所有可能 p 个子样本点组合的大小限制为随机选择的子集,从而也限制了运行时。因此,Theil-Sen 适用于较大的问题,但缺点是它在随机子集上工作时会失去一些数学特性。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import time
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression, RANSACRegressor, TheilSenRegressor
estimators = [
("OLS", LinearRegression()),
("Theil-Sen", TheilSenRegressor(random_state=42)),
("RANSAC", RANSACRegressor(random_state=42)),
]
colors = {"OLS": "turquoise", "Theil-Sen": "gold", "RANSAC": "lightgreen"}
lw = 2
仅 Y 方向的异常值#
np.random.seed(0)
n_samples = 200
# Linear model y = 3*x + N(2, 0.1**2)
x = np.random.randn(n_samples)
w = 3.0
c = 2.0
noise = 0.1 * np.random.randn(n_samples)
y = w * x + c + noise
# 10% outliers
y[-20:] += -20 * x[-20:]
X = x[:, np.newaxis]
plt.scatter(x, y, color="indigo", marker="x", s=40)
line_x = np.array([-3, 3])
for name, estimator in estimators:
t0 = time.time()
estimator.fit(X, y)
elapsed_time = time.time() - t0
y_pred = estimator.predict(line_x.reshape(2, 1))
plt.plot(
line_x,
y_pred,
color=colors[name],
linewidth=lw,
label="%s (fit time: %.2fs)" % (name, elapsed_time),
)
plt.axis("tight")
plt.legend(loc="upper right")
_ = plt.title("Corrupt y")

X 方向的异常值#
np.random.seed(0)
# Linear model y = 3*x + N(2, 0.1**2)
x = np.random.randn(n_samples)
noise = 0.1 * np.random.randn(n_samples)
y = 3 * x + 2 + noise
# 10% outliers
x[-20:] = 9.9
y[-20:] += 22
X = x[:, np.newaxis]
plt.figure()
plt.scatter(x, y, color="indigo", marker="x", s=40)
line_x = np.array([-3, 10])
for name, estimator in estimators:
t0 = time.time()
estimator.fit(X, y)
elapsed_time = time.time() - t0
y_pred = estimator.predict(line_x.reshape(2, 1))
plt.plot(
line_x,
y_pred,
color=colors[name],
linewidth=lw,
label="%s (fit time: %.2fs)" % (name, elapsed_time),
)
plt.axis("tight")
plt.legend(loc="upper left")
plt.title("Corrupt x")
plt.show()

脚本总运行时间: (0 分钟 0.518 秒)
相关示例