使用 Python Scikit-Learn 进行泰尔 - 森回归

Beginner

This tutorial is from open-source community. Access the source code

简介

在本教程中,我们将学习泰尔 - 森回归(Theil-Sen Regression)及其使用 Python 的 scikit-learn 库的实现。我们还将了解它与普通最小二乘法(OLS)和稳健随机抽样一致性(RANSAC)回归有何不同。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库并生成数据集

首先,让我们导入必要的库,并生成一个用于回归分析的合成数据集。

import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, TheilSenRegressor
from sklearn.linear_model import RANSACRegressor

np.random.seed(0)
n_samples = 200
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
X = x[:, np.newaxis]

绘制数据

现在,让我们绘制生成的数据集。

plt.scatter(x, y, color="indigo", marker="x", s=40)
plt.axis("tight")
_ = plt.title("Original Data")

拟合线性回归模型

接下来,我们将使用普通最小二乘法(OLS)、泰尔 - 森(Theil-Sen)和随机抽样一致性(RANSAC)方法拟合三个线性回归模型。

estimators = [
    ("OLS", LinearRegression()),
    ("Theil-Sen", TheilSenRegressor(random_state=42)),
    ("RANSAC", RANSACRegressor(random_state=42)),
]
colors = {"OLS": "turquoise", "Theil-Sen": "gold", "RANSAC": "lightgreen"}
lw = 2

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 left")
_ = plt.title("Regression Lines")

总结

在本教程中,我们学习了泰尔 - 森回归(Theil-Sen Regression)及其使用 Python 的 scikit-learn 库的实现。我们还了解了它与普通最小二乘法(OLS)和稳健随机抽样一致性(RANSAC)回归的区别。通过遵循上述步骤,我们能够生成一个合成数据集,拟合线性回归模型,并绘制回归线。