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.

- Bias measures the model's ownsystematic error. High bias means the model is too simple and fails to learn even the basic patterns in the training data (underfitting).
- Variance measures the model's sensitivity torandom fluctuations in the training data. High variance means the model is too complex and learns the noise in the training data as if it were a pattern (overfitting).
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:
λ(lambda) is the regularization strength coefficient, a hyperparameter greater than 0. It controls the strength of the penalty.λThe larger it is, the heavier the penalty on model complexity, and the simpler the model becomes.Penalty(权重)is the penalty term, which is defined differently for L1 and L2.
L1 Regularization (Lasso Regression)
- Penalty term: The sum of the absolute values of all the model's weight parameters.
- Formula:
Penalty = Σ|w_i|, wherew_iis the i-th weight. - Loss function:
Loss_L1 = Loss + λ * Σ|w_i|
Core characteristics and effects:
- Feature selection: L1 regularization tends to producea sparse weight matrix, meaning it directly compresses the weights of many unimportant features to 0. This effectively performs feature selection automatically, with the model retaining only the most important features.
- Geometric interpretation: Geometrically, its constraint is a "diamond" (a rhombus in two dimensions). The optimal solution point is more likely to touch the "corners" of this diamond, and points at the corners mean some coordinates are 0.
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
(
"Lasso model coefficients:"
)
for
i
,
coef
in
enumerate
(
lasso_model.
coef_
)
:
(
f
" Feature {i}: {coef:.4f}"
)
Count the number of non-zero weights
non_zero_count
=
sum
(
lasso_model.
coef_
!=
0
)
(
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)
- Penalty term: The sum of the squares of all the model's weight parameters.
- Formula:
Penalty = Σ(w_i)² - Loss function:
Loss_L2 = Loss + λ * Σ(w_i)²
Core characteristics and effects:
- Weight decay: L2 regularization tends to make all weight parametersapproach 0, but usually not equal to 0. It shrinks all weights uniformly, preventing any single weight from becoming too large.
- Improving ill-conditioned problems: For data with multicollinearity (high correlation) among features, ordinary linear regression can be unstable. L2 regularization effectively improves this problem, making the solution more stable.
- Geometric interpretation: Geometrically, its constraint is a "circle" (a circle in two dimensions). The optimal solution point is more likely to touch the "edge" of this circle rather than a sharp corner.
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
(
"Ridge model coefficients:"
)
for
i
,
coef
in
enumerate
(
ridge_model.
coef_
)
:
(
f
" Feature {i}: {coef:.4f}"
)
Compare the coefficient differences between Lasso and Ridge
(
"\nCoefficient comparison (Lasso vs Ridge):"
)
(
"Feature | Lasso coefficient | Ridge coefficient"
)
(
"-"
35
)
for
i
in
range
(
len
(
lasso_model.
coef_
)
)
:
(
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:
- In each training batch, with probability
p(e.g., 0.5) randomly drop a portion of the neurons. - Forward and backward propagation are performed only on the remaining neurons.
- At test or prediction time, all neurons are used, but their outputs must be multiplied by
(1-p)to keep the expected value consistent.
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:
- Split the data into a training set and a validation set.
- Train the model on the training set and periodically evaluate performance on the validation set (e.g., after each epoch).
- Once the performance on the validation set (e.g., loss) is found tono longer improve or even begin to decline over several consecutive epochs, stop training immediately.
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
- X.
ravel
(
)
**
2
- X.
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:
- Run the above code to observe how the unregularized model fluctuates wildly to fit the noise (overfitting), while the regularized model's curve is smoother and closer to the true function.
- Try adjusting
degree(the polynomial degree) and each model'salpha(regularization strength) parameters, and observe their impact on the model's fitting effect. - (Advanced) Split the data into training and test sets, compute each model's MSE on the test set, and verify the improvement in generalization ability brought by regularization.
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:
- Understand the Nature of the Problem: First, determine whether the model faces overfitting (high variance) by examining learning curves, validation set performance, and so on.
- Start Simple: Usually, you can try first L2 regularization, because it is stable and easy to tune. If the feature dimension is extremely high and feature selection is needed, then consider L1 or Elastic Net。
- Parameter Tuning Is Key: Regularization strength
λ(oralpha) is a crucial hyperparameter. It must be carefully selected throughCross-validationcross-validation. - Compositional use: In practice, regularization techniques are often used in combination. For example, when training deep neural networks,Dropout + L2 weight decay + early stopping is an extremely common combination.
- Domain Adaptation: For computer vision tasks, Dropout and Batch Normalization (which also has a certain regularization effect) are very effective. For sequence models (such as RNNs and Transformers), Dropout and weight decay are commonly used.
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.