Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regularization

Regularization

Imagine we are learning to ride a bicycle. At first, we might be very nervous, gripping the handlebars tightly, our bodies stiff, trying to remember every detail of every movement. This state of over-focusing on details and trying to perfectly control every tiny movement is called, in machine learning, Overfitting。

Our model (like you when you were a beginner) is too complex, perfectly memorizing every sample in the training data—even the noise and random fluctuations—causing it to perform poorly when faced with new, unseen data (such as actually riding on the road), lacking the ability to generalize.

Regularization is the core technique born to solve this problem; its core idea is:cool down the model's enthusiasm for learning, prevent it from going down a rabbit hole, and thereby improve its adaptability to new environments. In short, regularization limits model complexity by adding an extra penalty term to the objective function (loss function) during training, preventing it from relying too heavily on specific patterns in the training data.

This article will take you to a deep understanding of the principles of regularization, common methods, and their applications in engineering practice.


Basic concepts: The bias-variance trade-off

Before diving into regularization, we need to understand the two core sources of machine learning model error: Bias and Variance. This helps us understand exactly what regularization is adjusting.

Our goal is to find the bias-variance trade-off sweet spot that minimizes total error. Regularization achieves this byadding a bit of bias (making the model slightly simpler) to significantly reduce variance, thereby improving the model's overall generalization performance—an effective approach.


L1 and L2 Regularization

The most classic regularization method is to add a penalty term based on the model's weight parameters directly to the loss function. Depending on how the penalty term is calculated, it is mainly divided into L1 and L2 regularization.

Changes in the loss function

Unregularized loss function (taking mean squared error, MSE, as an example): Loss = (1/n) * Σ(真实值 - 预测值)²

Loss function after adding the regularization term: Loss_正则化 = Loss + λ * Penalty(权重)

Where:

L1 Regularization (Lasso Regression)

Core characteristics and effects:

Code Example:

Example

from

sklearn.

linear_model

import

Lasso

from

sklearn.

datasets

import

make_regression

from

sklearn.

model_selection

import

train_test_split

Generate simulated data

X

,

y

=

make_regression

(

n_samples

=

100

,

n_features

=

10

,

noise

=

0.1

,

random_state

=

42

)

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Create an L1-regularized model (Lasso), set the regularization strength alpha (i.e., λ)

lasso_model

=

Lasso

(

alpha

=

0.1

)

The larger alpha is, the stronger the penalty, and more weights become 0

lasso_model.

fit

(

X_train

,

y_train

)

View the model coefficients (weights) and observe the sparsity

print

(

"Lasso model coefficients:"

)

for

i

,

coef

in

enumerate

(

lasso_model.

coef_

)

:

   

print

(

f

" Feature {i}: {coef:.4f}"

)

Count the number of non-zero weights

non_zero_count

=

sum

(

lasso_model.

coef_

!=

0

)

print

(

f

"\nNumber of features with non-zero weights: {non_zero_count} / {X.shape[1]}"

)

Output:

Lasso 模型系数:

  特征 0: 16.6855

  特征 1: 54.0447

  特征 2: 5.0302

  特征 3: 63.5492

  特征 4: 93.4587

  特征 5: 70.5421

  特征 6: 86.9569

  特征 7: 10.2711

  特征 8: 3.0697

  特征 9: 70.7835



非零权重的特征数量: 10 / 10

L2 Regularization (Ridge Regression)

Core characteristics and effects:

Code Example:

Example

from

sklearn.

linear_model

import

Ridge

Create an L2-regularized model (Ridge)

ridge_model

=

Ridge

(

alpha

=

1.0

)

alpha, i.e., λ

ridge_model.

fit

(

X_train

,

y_train

)

View the model coefficients and observe the weight decay

print

(

"Ridge model coefficients:"

)

for

i

,

coef

in

enumerate

(

ridge_model.

coef_

)

:

   

print

(

f

" Feature {i}: {coef:.4f}"

)

Compare the coefficient differences between Lasso and Ridge

print

(

"\nCoefficient comparison (Lasso vs Ridge):"

)

print

(

"Feature | Lasso coefficient | Ridge coefficient"

)

print

(

"-"

35

)

for

i

in

range

(

len

(

lasso_model.

coef_

)

)

:

   

print

(

f

"{i:4d} | {lasso_model.coef_[i]:11.4f} | {ridge_model.coef_[i]:11.4f}"

)

Summary comparison of L1 and L2

Feature L1 Regularization (Lasso) L2 Regularization (Ridge)
Penalty term `Σ w_i
Solution characteristics Sparse solution, many weights are 0 Dense solution, weights are close to but not 0
Core Features Feature selection Weight decay, Stable solution
Geometric shape Diamond / polyhedron Circle / sphere
Compute More complex optimization (not differentiable everywhere) Simple optimization (differentiable everywhere)
Applicable scenarios Many features, and only a few are believed to be relevant All features may contribute, or there is collinearity

Elastic Net

Elastic Net is a compromise between L1 and L2 regularization, containing both penalty terms. Loss_ElasticNet = Loss + λ1 * Σ|w_i| + λ2 * Σ(w_i)²

It combines the feature-selection ability of L1 with the stability of L2, and is suitable for cases where the feature dimensionality is very high and features are correlated.

Example

from

sklearn.

linear_model

import

ElasticNet

elastic_model

=

ElasticNet

(

alpha

=

0.1

,

l1_ratio

=

0.5

)

l1_ratio controls the mixing ratio of L1 and L2

elastic_model.

fit

(

X_train

,

y_train

)


Other regularization techniques

Besides directly modifying the loss function, there are also methods that achieve regularization by changing the training process or the model structure.

Dropout (for neural networks)

Dropout is an extremely effective regularization technique in neural networks. Duringthe training process,it randomly "deactivates" a subset of the network's neurons (setting their outputs to 0).

How It Works:

Core idea: Prevents complex co-adaptation between neurons, forcing the network to learn morerobustandand distributedfeature representations. This is like a team that cannot always rely on a few core members; everyone needs the ability to work independently, so that even if someone is absent, the team can still function normally.

Code example (using TensorFlow/Keras):

Example

import

tensorflow

as

tf

from

tensorflow.

keras

.

models

import

Sequential

from

tensorflow.

keras

.

layers

import

Dense

,

Dropout

model

=

Sequential

(

[

    Dense

(

128

,

activation

=

'relu'

,

input_shape

=

(

input_dim

,

)

)

,

    Dropout

(

0.5

)

,

Add a Dropout layer after the previous layer, with a dropout rate of 50%

    Dense

(

64

,

activation

=

'relu'

)

,

    Dropout

(

0.3

)

,

Dropout rate of 30%

    Dense

(

1

,

activation

=

'sigmoid'

)

Output layer

]

)

model.

compile

(

optimizer

=

'adam'

,

loss

=

'binary_crossentropy'

,

metrics

=

[

'accuracy'

]

)

Early Stopping

Early stopping is a simple yet efficient regularization strategy. Instead of modifying the loss function, itmonitors the model's performance on the validation set。

Steps:

Core idea: Stop training at the moment the model is about to begin overfitting the training data (i.e., when the validation error starts to rise), thereby obtaining the model weights with the best generalization ability.

Example

from

tensorflow.

keras

.

callbacks

import

EarlyStopping

Define the early stopping callback function

monitor: The metric to monitor, e.g., 'val_loss'

patience: The number of epochs to tolerate; stop if validation performance does not improve within this many epochs

restore_best_weights: Whether to restore the weights from the epoch with the best monitored metric

early_stopping

=

EarlyStopping

(

    monitor

=

'val_loss'

,

    patience

=

10

,

    restore_best_weights

=

True

)

Use in model.fit

history

=

model.

fit

(

    X_train

,

y_train

,

    validation_data

=

(

X_val

,

y_val

)

,

    epochs

=

100

,

    callbacks

=

[

early_stopping

]

Pass in the list of callback functions

)


Practice exercise: Comprehensively comparing regularization effects

Let's compare the effects of different regularization methods on a regression task through a complete example.

Example

import

numpy

as

np

import

matplotlib.

pyplot

as

plt

from

sklearn.

linear_model

import

LinearRegression

,

Lasso

,

Ridge

,

ElasticNet

from

sklearn.

preprocessing

import

PolynomialFeatures

from

sklearn.

pipeline

import

make_pipeline

from

sklearn.

metrics

import

mean_squared_error

1. Generate noisy non-linear data

np.

random

.

seed

(

42

)

X

=

np.

linspace

(

3

,

3

,

100

)

.

reshape

(

1

,

1

)

y_true

=

0.5

ravel

(

)

**

2

ravel

(

)

The true quadratic relationship

y

=

y_true + np.

random

.

randn

(

100

)

0.8

Add noise

2. Create models of varying complexity (using polynomial features)

degree

=

10

Use a 10th-degree polynomial, which easily overfits

models

=

{

   

'No regularization'

: make_pipeline

(

PolynomialFeatures

(

degree

)

,

LinearRegression

(

)

)

,

   

'L1 (Lasso)'

: make_pipeline

(

PolynomialFeatures

(

degree

)

,

Lasso

(

alpha

=

0.01

,

max_iter

=

10000

)

)

,

   

'L2 (Ridge)'

: make_pipeline

(

PolynomialFeatures

(

degree

)

,

Ridge

(

alpha

=

0.1

)

)

,

   

'ElasticNet'

: make_pipeline

(

PolynomialFeatures

(

degree

)

,

ElasticNet

(

alpha

=

0.01

,

l1_ratio

=

0.5

)

)

}

3. Train and predict

X_plot

=

np.

linspace

(

3.5

,

3.5

,

200

)

.

reshape

(

1

,

1

)

plt.

figure

(

figsize

=

(

12

,

8

)

)

plt.

scatter

(

X

,

y

,

s

=

20

,

alpha

=

0.6

,

label

=

'Training data (with noise)'

)

plt.

plot

(

X

,

y_true

,

'k-'

,

linewidth

=

3

,

label

=

'True function'

)

for

name

,

model

in

models.

items

(

)

:

    model.

fit

(

X

,

y

)

    y_plot

=

model.

predict

(

X_plot

)

    mse

=

mean_squared_error

(

y

,

model.

predict

(

X

)

)

    plt.

plot

(

X_plot

,

y_plot

,

'--'

,

linewidth

=

2

,

label

=

f

'{name} (MSE: {mse:.3f})'

)

plt.

xlabel

(

'X'

)

plt.

ylabel

(

'y'

)

plt.

title

(

'Comparison of the suppression effects of different regularization methods on overfitting (10th-degree polynomial)'

)

plt.

legend

(

loc

=

'best'

)

plt.

grid

(

True

,

alpha

=

0.3

)

plt.

show

(

)

Exercise tasks:


Summary and engineering recommendations

Regularization is an essential tool in a machine learning engineer's toolbox. To apply it effectively, keep the following key points in mind:

The ultimate goal of regularization is to guide the model from "rote memorization" of the training data toward a "deep understanding" of the universal patterns behind the data, so as to make more reliable predictions in the real world. Master it, and you will hold the key to improving your model's generalization ability.