用于线性建模的岭回归

Machine LearningMachine LearningBeginner
立即练习

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

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

简介

在本实验中,我们将学习如何使用岭回归(Ridge Regression)进行带有L2正则化的线性回归,以防止过拟合。我们将使用scikit-learn,这是一个广受欢迎的用于Python的机器学习库。

虚拟机使用提示

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

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/metrics("Metrics") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49269{{"用于线性建模的岭回归"}} sklearn/metrics -.-> lab-49269{{"用于线性建模的岭回归"}} sklearn/datasets -.-> lab-49269{{"用于线性建模的岭回归"}} ml/sklearn -.-> lab-49269{{"用于线性建模的岭回归"}} end

导入必要的库

我们将从导入本实验所需的库开始。

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error

生成随机数据

我们将使用scikit-learn中的make_regression函数生成随机数据。我们将把n_samples设置为10,n_features设置为10,random_state设置为1。此函数将返回我们的输入特征X、目标变量y以及真实系数值w。

X, y, w = make_regression(
    n_samples=10, n_features=10, coef=True, random_state=1, bias=3.5
)

初始化岭回归模型

我们将使用其默认超参数初始化岭回归模型。

clf = Ridge()

使用不同的正则化强度训练模型

我们将使用循环,用不同的正则化强度来训练模型。我们会通过在set_params函数中更改alpha的值来设置正则化强度。我们将保存每个alpha值对应的系数和误差。

coefs = []
errors = []

alphas = np.logspace(-6, 6, 200)

for a in alphas:
    clf.set_params(alpha=a)
    clf.fit(X, y)
    coefs.append(clf.coef_)
    errors.append(mean_squared_error(clf.coef_, w))

绘制结果

我们将使用Matplotlib绘制系数和误差随正则化强度变化的函数图像。

plt.figure(figsize=(20, 6))

plt.subplot(121)
ax = plt.gca()
ax.plot(alphas, coefs)
ax.set_xscale("log")
plt.xlabel("alpha")
plt.ylabel("weights")
plt.title("Ridge coefficients as a function of the regularization")
plt.axis("tight")

plt.subplot(122)
ax = plt.gca()
ax.plot(alphas, errors)
ax.set_xscale("log")
plt.xlabel("alpha")
plt.ylabel("error")
plt.title("Coefficient error as a function of the regularization")
plt.axis("tight")

plt.show()

总结

在本实验中,我们学习了如何使用带有L2正则化的岭回归来防止过拟合。我们生成了随机数据,使用不同的正则化强度训练了岭回归模型,并绘制了系数和误差随正则化强度变化的函数图像。