機器學習 - 正則化



在機器學習中,正則化是一種用於防止過擬合的技術。過擬合是指模型過於複雜,擬合訓練資料過於良好,但無法推廣到新的、未見過的資料。正則化在成本函式中引入懲罰項,鼓勵模型具有較小的權重和更簡單的結構,從而減少過擬合。

機器學習中常用的正則化技術有多種,包括L1和L2正則化、dropout正則化和提前停止。在本文中,我們將重點關注L1和L2正則化,這是最常用的技術。

L1正則化

L1正則化,也稱為Lasso正則化,是一種在成本函式中新增懲罰項的技術,該懲罰項等於權重總和的絕對值。L1正則化懲罰的公式為:

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

其中λ是一個控制正則化強度的超引數,𝑤𝑖是模型中的第i個權重。

L1正則化懲罰的作用是鼓勵模型具有稀疏權重,即消除對輸出影響很小或沒有影響的權重。這具有簡化模型和減少過擬合的作用。

示例

為了在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正則化

L2正則化,也稱為Ridge正則化,是一種在成本函式中新增懲罰項的技術,該懲罰項等於權重平方和。L2正則化懲罰的公式為:

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

其中λ是一個控制正則化強度的超引數,wi是模型中的第i個權重。

L2正則化懲罰的作用是鼓勵模型具有較小的權重,即減小模型中所有權重的幅度。這具有平滑模型和減少過擬合的作用。

示例

為了在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標準化特徵資料。

接下來,我們定義Ridge迴歸模型並將alpha引數設定為0.1,它控制L2正則化的強度。

我們在訓練資料上擬合模型,並在測試資料上進行預測。最後,我們計算均方誤差以評估模型的效能。

輸出

執行此程式碼時,將產生以下輸出:

Mean Squared Error: 24.29346250596107
廣告