使用 Scikit-Learn 进行非参数保序回归

Machine LearningMachine LearningBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本教程中,我们将学习保序回归,这是一种非参数回归技术,它在最小化训练数据上的均方误差的同时,找到函数的非递减近似值。我们将使用Python中流行的机器学习库scikit-learn来实现保序回归,并将其与线性回归进行比较。

虚拟机使用提示

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/isotonic("Isotonic Regression") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/utils("Utilities") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49172{{"使用 Scikit-Learn 进行非参数保序回归"}} sklearn/isotonic -.-> lab-49172{{"使用 Scikit-Learn 进行非参数保序回归"}} sklearn/utils -.-> lab-49172{{"使用 Scikit-Learn 进行非参数保序回归"}} ml/sklearn -.-> lab-49172{{"使用 Scikit-Learn 进行非参数保序回归"}} end

导入所需库

我们将首先为本教程导入所需的库,即NumPy、Matplotlib和scikit-learn。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

from sklearn.linear_model import LinearRegression
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_random_state

生成数据

接下来,我们将生成一些数据用于回归。我们将创建一个带有同方差均匀噪声的非线性单调趋势。

n = 100
x = np.arange(n)
rs = check_random_state(0)
y = rs.randint(-50, 50, size=(n,)) + 50.0 * np.log1p(np.arange(n))

拟合保序回归和线性回归模型

现在我们将对生成的数据拟合保序回归模型和线性回归模型。

ir = IsotonicRegression(out_of_bounds="clip")
y_ = ir.fit_transform(x, y)

lr = LinearRegression()
lr.fit(x[:, np.newaxis], y)  ## x需要为二维数据以用于线性回归

绘制结果

最后,我们将绘制两个回归模型的结果,以直观展示它们对数据的拟合程度。

segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
lc = LineCollection(segments, zorder=0)
lc.set_array(np.ones(len(y)))
lc.set_linewidths(np.full(n, 0.5))

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 6))

ax0.plot(x, y, "C0.", markersize=12)
ax0.plot(x, y_, "C1.-", markersize=12)
ax0.plot(x, lr.predict(x[:, np.newaxis]), "C2-")
ax0.add_collection(lc)
ax0.legend(("训练数据", "保序回归拟合", "线性回归拟合"), loc="lower right")
ax0.set_title("对含噪声数据的保序回归拟合 (n = %d)" % n)

x_test = np.linspace(-10, 110, 1000)
ax1.plot(x_test, ir.predict(x_test), "C1-")
ax1.plot(ir.X_thresholds_, ir.y_thresholds_, "C1.", markersize=12)
ax1.set_title("预测函数 (%d 个阈值)" % len(ir.X_thresholds_))

plt.show()

总结

在本教程中,我们学习了保序回归,这是一种非参数回归技术,它在最小化训练数据上的均方误差的同时,找到函数的非递减近似值。我们还使用scikit-learn实现了保序回归,并将其与线性回归进行了比较。