Scikit 学习弹性网络回归模型

Beginner

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

简介

在本实验中,我们将使用 Scikit-learn 弹性网络回归模型来说明估计器在未见过的数据(测试数据)上的性能与在训练数据上的性能是如何不同的。我们将生成样本数据,计算训练和测试误差,并绘制结果函数。

虚拟机提示

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

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

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

生成样本数据

我们将使用 Scikit-learn 中的make_regression()函数来生成样本数据。我们将训练样本数量设置为 75,测试样本数量设置为 150,特征数量设置为 500。我们还将n_informative设置为 50,并将shuffle设置为 False。

import numpy as np
from sklearn import linear_model
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

n_samples_train, n_samples_test, n_features = 75, 150, 500
X, y, coef = make_regression(
    n_samples=n_samples_train + n_samples_test,
    n_features=n_features,
    n_informative=50,
    shuffle=False,
    noise=1.0,
    coef=True,
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=n_samples_train, test_size=n_samples_test, shuffle=False
)

计算训练误差和测试误差

我们将使用 Scikit-learn 中的弹性网络回归模型来计算训练误差和测试误差。我们将使用np.logspace()把正则化参数alpha设置为从 10 的 -5 次方到 10 的 1 次方的一系列值。我们还将把l1_ratio设置为 0.7,把max_iter设置为 10000。

alphas = np.logspace(-5, 1, 60)
enet = linear_model.ElasticNet(l1_ratio=0.7, max_iter=10000)
train_errors = list()
test_errors = list()
for alpha in alphas:
    enet.set_params(alpha=alpha)
    enet.fit(X_train, y_train)
    train_errors.append(enet.score(X_train, y_train))
    test_errors.append(enet.score(X_test, y_test))

i_alpha_optim = np.argmax(test_errors)
alpha_optim = alphas[i_alpha_optim]
print("Optimal regularization parameter : %s" % alpha_optim)

绘制结果函数

我们将使用matplotlib库来绘制结果函数。我们将使用plt.subplot()函数创建两个子图。在第一个子图中,我们将绘制训练误差和测试误差作为正则化参数的函数。我们还将在最优正则化参数处绘制一条垂直线。在第二个子图中,我们将绘制真实系数和估计系数。

import matplotlib.pyplot as plt

plt.subplot(2, 1, 1)
plt.semilogx(alphas, train_errors, label="Train")
plt.semilogx(alphas, test_errors, label="Test")
plt.vlines(
    alpha_optim,
    plt.ylim()[0],
    np.max(test_errors),
    color="k",
    linewidth=3,
    label="Optimum on test",
)
plt.legend(loc="lower right")
plt.ylim([0, 1.2])
plt.xlabel("Regularization parameter")
plt.ylabel("Performance")

## 显示估计的系数 coef_与真实系数
plt.subplot(2, 1, 2)
plt.plot(coef, label="True coef")
plt.plot(coef_, label="Estimated coef")
plt.legend()
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26)
plt.show()

总结

在本实验中,我们学习了如何使用 Scikit-learn 弹性网络回归模型来计算训练误差和测试误差,并绘制结果函数。我们还了解了估计器在未见过的数据(测试数据)上的性能与在训练数据上的性能是如何不同的。我们使用make_regression()linear_model.ElasticNet()train_test_split()np.logspace()matplotlib函数生成了样本数据,计算了训练误差和测试误差,并绘制了结果函数。