Machine Learning 简明教程

Machine Learning - Regularization

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

In machine learning, regularization is a technique used to prevent overfitting, which occurs when a model is too complex and fits the training data too well, but fails to generalize to new, unseen data. Regularization introduces a penalty term to the cost function, which encourages the model to have smaller weights and a simpler structure, thereby reducing overfitting.

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

There are several types of regularization techniques commonly used in machine learning, including L1 and L2 regularization, dropout regularization, and early stopping. In this article, we will focus on L1 and L2 regularization, which are the most commonly used techniques.

L1 Regularization

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

L1 regularization, also known as Lasso regularization, is a technique that adds a penalty term to the cost function, equal to the absolute value of the sum of the weights. The formula for the L1 regularization penalty is −

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

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

where λ is a hyperparameter that controls the strength of the regularization, and 𝑤𝑖 is the i-th weight in the model.

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

The effect of the L1 regularization penalty is to encourage the model to have sparse weights, that is, to eliminate the weights that have little or no impact on the output. This has the effect of simplifying the model and reducing overfitting.

Example

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

To implement L1 regularization in Python, we can use the Lasso class from the scikit-learn library. Here is an example of how to use L1 regularization for linear regression −

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 模型。然后我们在训练数据上训练模型,并在测试数据上进行预测。最后,我们计算预测的均方误差。

In this example, we load the Boston Housing dataset, split it into training and test sets, and create a Lasso model with L1 regularization using an alpha value of 0.1. We then train the model on the training data and make predictions on the test data. Finally, we calculate the mean squared error of the predictions.

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

When you execute this code, it will produce the following output −

Mean squared error: 25.155593753934173

L2 Regularization

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

L2 regularization, also known as Ridge regularization, is a technique that adds a penalty term to the cost function, equal to the square of the sum of the weights. The formula for the L2 regularization penalty is −

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

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

where λ is a hyperparameter that controls the strength of the regularization, and wi is the ith weight in the model.

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

The effect of the L2 regularization penalty is to encourage the model to have small weights, that is, to reduce the magnitude of all the weights in the model. This has the effect of smoothing the model and reducing overfitting.

Example

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

To implement L2 regularization in Python, we can use the Ridge class from the scikit-learn library. Here is an example of how to use L2 regularization for linear regression −

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 对特征数据进行标准化。

In this example, we first load the Boston housing dataset and split it into training and testing sets. We then standardize the feature data using a StandardScaler.

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

Next, we define the Ridge regression model and set the alpha parameter to 0.1, which controls the strength of the L2 regularization.

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

We fit the model on the training data and make predictions on the testing data. Finally, we calculate the mean squared error to evaluate the performance of the model.

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

When you execute this code, it will produce the following output −

Mean Squared Error: 24.29346250596107