带稀疏性的线性回归示例

Beginner

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

简介

本实验展示了如何使用 scikit-learn 中的糖尿病数据集进行带稀疏性的线性回归。我们将仅拟合数据集中的两个特征,并绘制结果以说明稀疏性的概念。

虚拟机提示

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

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

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

加载糖尿病数据集

首先,我们从 scikit-learn 中加载糖尿病数据集,并将其拆分为训练集和测试集。

from sklearn import datasets
import numpy as np

X, y = datasets.load_diabetes(return_X_y=True)
indices = (0, 1)

X_train = X[:-20, indices]
X_test = X[-20:, indices]
y_train = y[:-20]
y_test = y[-20:]

拟合线性回归模型

接下来,我们对训练集拟合一个线性回归模型。

from sklearn import linear_model

ols = linear_model.LinearRegression()
_ = ols.fit(X_train, y_train)

绘制结果

最后,我们从三个不同视角绘制结果,以说明稀疏性的概念。

import matplotlib.pyplot as plt

## unused but required import for doing 3d projections with matplotlib < 3.2
import mpl_toolkits.mplot3d  ## noqa: F401


def plot_figs(fig_num, elev, azim, X_train, clf):
    fig = plt.figure(fig_num, figsize=(4, 3))
    plt.clf()
    ax = fig.add_subplot(111, projection="3d", elev=elev, azim=azim)

    ax.scatter(X_train[:, 0], X_train[:, 1], y_train, c="k", marker="+")
    ax.plot_surface(
        np.array([[-0.1, -0.1], [0.15, 0.15]]),
        np.array([[-0.1, 0.15], [-0.1, 0.15]]),
        clf.predict(
            np.array([[-0.1, -0.1, 0.15, 0.15], [-0.1, 0.15, -0.1, 0.15]]).T
        ).reshape((2, 2)),
        alpha=0.5,
    )
    ax.set_xlabel("X_1")
    ax.set_ylabel("X_2")
    ax.set_zlabel("Y")
    ax.xaxis.set_ticklabels([])
    ax.yaxis.set_ticklabels([])
    ax.zaxis.set_ticklabels([])


## Generate the three different figures from different views
elev = 43.5
azim = -110
plot_figs(1, elev, azim, X_train, ols)

elev = -0.5
azim = 0
plot_figs(2, elev, azim, X_train, ols)

elev = -0.5
azim = 90
plot_figs(3, elev, azim, X_train, ols)

plt.show()

总结

本实验展示了如何使用 scikit-learn 中的糖尿病数据集进行带稀疏性的线性回归。我们仅拟合了数据集中的两个特征,并绘制结果以说明稀疏性的概念。