Machine Learning 简明教程

Machine Learning - Regularization

在机器学习中,正则化是一种防止过拟合的技术,过拟合发生在模型过于复杂并且过拟合训练数据而无法推广到新数据时。正则化在成本函数中引入了一个惩罚项,它鼓励模型具有更小的权重和更简单的结构,从而减少过拟合。

机器学习中常用的正则化技术有多种,包括 L1 和 L2 正则化、Dropout 正则化和早期停止。在本文中,我们将重点讨论 L1 和 L2 正则化,这是最常用的技术。

L1 Regularization

L1 正则化,又称为 LASSO 正则化,是一种技术,用于向成本函数添加一个惩罚项,该惩罚项等于权重之和的绝对值。L1 正则化惩罚的公式为 -

\lambda \times \Sigma \left|w_{i} \right|

其中 λ 是控制正则化强度的超参数,而 𝑤𝑖 是模型中的第 i 个权重。

L1 正则化惩罚的效果是鼓励模型具有稀疏权重,也就是说,消除对输出影响很小或没有影响的权重。这具有简化模型和减少过拟合的效果。

Example

要在 Python 中实现 L1 正则化,我们可以使用来自 scikit-learn 库的 Lasso 类。以下是针对线性回归使用 L1 正则化的示例 -

from sklearn.linear_model import Lasso
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# Load the Boston Housing dataset
boston = load_boston()

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42)

# Create a Lasso model with L1 regularization
lasso = Lasso(alpha=0.1)

# Train the model on the training data
lasso.fit(X_train, y_train)

# Make predictions on the test data
y_pred = lasso.predict(X_test)

# Calculate the mean squared error of the predictions
mse = mean_squared_error(y_test, y_pred)
print("Mean squared error:", mse)

在此示例中,我们加载波士顿住房数据集,将其拆分为训练和测试集,并使用 alpha 值为 0.1 创建具有 L1 正则化的 Lasso 模型。然后我们在训练数据上训练模型,并在测试数据上进行预测。最后,我们计算预测的均方误差。

执行此代码时,将生成以下输出 −

Mean squared error: 25.155593753934173

L2 Regularization

L2 正则化,也称为岭正则化,是一种向成本函数添加惩罚项的技术,该惩罚项等于权重之和的平方。L2 正则化惩罚的公式为 -

\lambda \times \Sigma\left (w_{i} \right )^{2}

其中 λ 是控制正则化强度的超参数,而 w_i 是模型中的第 i 个权重。

L2 正则化惩罚的效果是鼓励模型具有较小的权重,也就是说,减小模型中所有权重的幅度。这具有平滑模型和减少过拟合的效果。

Example

要在 Python 中实现 L2 正则化,我们可以使用来自 scikit-learn 库的 Ridge 类。以下是针对线性回归使用 L2 正则化的示例 -

from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
import numpy as np

# load the Boston housing dataset
boston = load_boston()

# create feature and target arrays
X = boston.data
y = boston.target

# standardize the feature data
scaler = StandardScaler()
X = scaler.fit_transform(X)

# split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# define the Ridge regression model with L2 regularization
model = Ridge(alpha=0.1)

# fit the model on the training data
model.fit(X_train, y_train)

# make predictions on the testing data
y_pred = model.predict(X_test)

# calculate the mean squared error
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error: ", mse)

在此示例中,我们首先加载波士顿住房数据集,并将其拆分为训练和测试集。然后,我们使用 StandardScaler 对特征数据进行标准化。

接下来,我们定义岭回归模型,并将 alpha 参数设置为 0.1,用于控制 L2 正则化的强度。

我们针对训练数据拟合模型,并在测试数据上进行预测。最后,我们计算均方误差来评估模型的性能。

执行此代码时,将生成以下输出 −

Mean Squared Error: 24.29346250596107