Deep Learning Fundamentals
Deep Learning Fundamentals
Deep learning is not some mysterious black technology; it is essentially a mathematical function approximator—given it a large amount of input and output data, it automatically finds the complex relationships between them.
For example: if you give it a million pictures of cats, and each picture is labeled "cat," deep learning automatically figures out what pixel combinations look like a cat.
Another example: if you give it a billion sentences of human language, with the next word of each sentence as the target, deep learning automatically learns what the most likely next word is given the preceding text.
The core advantage of deep learning is that its performance continuously improves as the amount of data increases. This is something traditional machine learning cannot achieve.
In this chapter, we will break down every component of deep learning step by step, starting from scratch:
- Mathematical Foundations of Neural Networks
- Forward propagation calculation process
- Role of activation functions
- Loss function design
- Principle of backpropagation
- Optimizer selection
- Regularization techniques
- Normalization methods
- Learning rate scheduling
Finally, we implement a complete Multi-Layer Perceptron (MLP) using PyTorch to connect all the knowledge points.
This chapter will involve some mathematics, but don't worry—we will explain every formula intuitively instead of making you memorize it. The focus is on understanding why it is designed this way, not how to calculate it.
Mathematical Foundations of Neural Networks
Deep learning is built upon three branches of mathematics: linear algebra, calculus, and probability theory.
You don't need to be a math expert, but you need to understand several core concepts.
Linear Algebra: Matrix Multiplication
The most fundamental operation in neural networks is matrix multiplication.
Why use matrices? Because they can concisely represent the process of "multiple inputs being transformed by multiple neurons."
First, let's look at an intuitive example:
Example
============================================
Intuitive understanding of matrix multiplication
============================================
import
numpy
as
np
Assume the input is a 3-dimensional vector: [height, weight, age]
The units are: centimeters, kilograms, years
x
=
np.
array
(
[
175
,
70
,
25
]
)
Input vector, shape (3,)
(
f
"Input x: {x}"
)
(
f
"Input shape: {x.shape}"
)
Weight matrix W: 2 neurons, each neuron receives 3 inputs
Shape is (output dimension, input dimension) = (2, 3)
W
=
np.
array
(
[
[
0.1
,
0.2
,
0.3
]
,
Weight of the first neuron
[
0.4
,
0.5
,
0.6
]
,
The weight of the second neuron
]
)
(
f
"\nWeight matrix W:\n{W}"
)
(
f
"Weight shape: {W.shape}"
)
Bias b: one bias per neuron
b
=
np.
array
(
[
0.1
,
0.2
]
)
shape (2,)
(
f
"\nBias b: {b}"
)
(
f
"Bias shape: {b.shape}"
)
Matrix multiplication: y = W · x + b
Note: numpy's @ operator represents matrix multiplication
y
=
W
@
x + b
(
f
"Output y: {y}"
)
(
f
"Output shape: {y.shape}"
)
Manually calculate and verify
y1
=
0.1
175
0.2
70
0.3
25
0.1
First neuron
y2
=
0.4
175
0.5
70
0.6
25
0.2
The second neuron
(
f
"Manual verification calculation: [{y1}, {y2}]"
)
The geometric meaning of matrix multiplication is "linear transformation"—it can rotate, scale, or stretch vector spaces.
But linear transformations alone are not enough.
If every layer is just matrix multiplication, then no matter how deep the network is, the entire network is equivalent to a single-layer network because a combination of multiple linear transformations is still a linear transformation.
This is why we need activation functions—to introduce non-linearity.
Calculus: Derivatives and the Chain Rule
The core of training a neural network is "gradient descent"—finding the direction of parameters that minimizes the loss.
The gradient is the "derivative of a multivariate function"—it tells us how much the loss will change for a small change in each parameter.
Let's look at a simple example first:
Example
============================================
Intuitive understanding of the derivative
============================================
def
f
(
x
)
:
"""A simple function: f(x) = x²"""
return
x **
2
def
numerical_derivative
(
f
,
x
,
h
=
1e-6
)
:
Numerical derivative: approximate the derivative using a small increment h
Derivative definition: f'(x) = lim(h→0) [f(x+h) - f(x)] / h
"""
return
(
f
(
x + h
)
- f
(
x
)
)
/ h
Calculate the derivative at x=3
x
=
3.0
df_dx
=
numerical_derivative
(
f
,
x
)
(
f
"f({x}) = {f(x)}"
)
(
f
"f'({x}) ≈ {df_dx}"
)
(
f
"Analytical solution (exact value): 2 * {x} = {2 * x}"
)
Understanding the meaning of the derivative:
A derivative of 6 means: when x increases by 1 at x=3, f(x) increases by approximately 6
x_new
=
x +
0.01
f_new
=
f
(
x_new
)
(
f
"\nx increased from {x} to {x_new}"
)
(
f
"f(x) changed from {f(x)} to {f_new}"
)
(
f
"Actual increase: {f_new - f(x)}"
)
(
f
"Derivative prediction: {df_dx * 0.01}"
)
For multivariate functions, we need to calculate the partial derivative of each variable and then combine them into a vector, which is the gradient.
The chain rule is the mathematical foundation of backpropagation. It allows us to "decompose layer by layer" the derivative of a composite function.
Example
============================================
Intuitive understanding of the chain rule
============================================
Consider composite functions: y = f(g(x))
Where: g(x) = x², f(z) = z³
Then: y = (x²)³ = x⁶
def
g
(
x
)
:
return
x **
2
def
f
(
z
)
:
return
z **
3
def
y
(
x
)
:
return
f
(
g
(
x
)
)
Manually calculate the derivative (chain rule):
dy/dx = df/dz * dz/dx = 3z² * 2x = 3*(x²)² * 2x = 6x⁵
x
=
2.0
z
=
g
(
x
)
z = 4
dy_dx_chain
=
3
(
z **
2
)
2
- x
Chain rule calculation
(
f
"Chain rule calculation: dy/dx = {dy_dx_chain}"
)
Numerical derivative verification
def
numerical_derivative_y
(
x
,
h
=
1e-6
)
:
return
(
y
(
x + h
)
- y
(
x
)
)
/ h
dy_dx_numerical
=
numerical_derivative_y
(
x
)
(
f
Numerical derivative verification: dy/dx ≈ {dy_dx_numerical}
)
Analytical solution: 6x^5 = 632 = 192
(
f
"Parsed solution: 6 * {x}^5 = {6 * (x ** 5)}"
)
The core idea of the chain rule is to break down a complex function into simple functions, calculate the derivative of each, and then multiply them.
Backpropagation is the application of the chain rule in neural networks—propagating gradients layer by layer backward from the output.
Probability theory: Conditional probability
In classification problems, the neural network output is often a "probability distribution"—the probability of each class given an input.
The conditional probability P(Y|X) represents "the probability of Y occurring given that X has occurred."
For example: P(rain|overcast) represents "the probability of rain when overcast."
In deep learning, we use neural networks to estimate this conditional probability:
Instance
============================================
Using a neural network to output a probability distribution
============================================
import
numpy
as
np
def
softmax
(
x
)
:
"""Softmax function: converts any real number into a probability distribution
The sum of all output values is 1, and each value is between [0, 1]
"""
Subtract the maximum value to prevent numerical overflow
exp_x
=
np.
exp
(
x - np.
max
(
x
)
)
return
exp_x / np.
sum
(
exp_x
)
Assume the last layer of the neural network outputs 3 "scores" (logits)
correspond to "cat", "dog", "bird"
logits
=
np.
array
(
[
2.0
,
1.0
,
0.5
]
)
(
f
"Neural network output (logits): {logits}"
)
Convert to probabilities using Softmax
probabilities
=
softmax
(
logits
)
(
f
"Probability distribution: {probabilities}"
)
(
f
"Probability sum: {np.sum(probabilities)}"
)
Interpretation:
P(Cat|Input Image) ≈ 0.67
P(Dog|Input Image) ≈ 0.24
P(Bird|Input Image) ≈ 0.09
(
"\nCategory probabilities:"
)
(
f
" Cat: {probabilities[0]:.2%}"
)
(
f
" Dog: {probabilities[1]:.2%}"
)
(
f
" Bird: {probabilities[2]:.2%}"
)
Three core mathematical fundamentals:
| Mathematical branch | Core concept | Application in deep learning |
|---|---|---|
| Linear algebra | Matrix multiplication, vectors, tensors | Represents network structure, efficient forward propagation computation |
| Calculus | Derivatives, chain rule, gradients | Backpropagation, parameter update |
| Probability theory | Conditional probability, probability distribution | Modeling uncertainty, designing loss functions |
Forward Propagation
Forward propagation is the process of input data "flowing" through the neural network, from the input layer to the hidden layer and then to the output layer.
Computation Graph
Representing the neural network as a computation graph makes the logic of forward and backward propagation clearer.
A computation graph consists of nodes (operations) and edges (data flow).
Computation graph of a simple two-layer neural network:
Example
============================================
Understanding forward propagation with computational graphs
============================================
import
numpy
as
np
def
relu
(
x
)
:
"""ReLU activation function: max(0, x)"""
return
np.
maximum
(
0
,
x
)
A simple two-layer neural network
Input layer (2) → Hidden layer (3) → Output layer (2)
Input: x = [x1, x2]
x
=
np.
array
(
[
1.0
,
2.0
]
)
(
f
"Enter x: {x}"
)
First layer: Input -> Hidden layer
W1
=
np.
array
(
[
[
0.1
,
0.2
]
,
First hidden neuron
[
0.3
,
0.4
]
,
Second hidden neuron
[
0.5
,
0.6
]
,
The 3rd hidden neuron
]
)
b1
=
np.
array
(
[
0.1
,
0.2
,
0.3
]
)
Second layer: Hidden layer -> Output layer
W2
=
np.
array
(
[
[
0.1
,
0.2
,
0.3
]
,
First output neuron
[
0.4
,
0.5
,
0.6
]
,
Second output neuron
]
)
b2
=
np.
array
(
[
0.1
,
0.2
]
)
Forward propagation computation graph
Step 1: Hidden layer linear transformation
z1
=
W1
@
x + b1
(
f
"\nHidden layer linear transformation z1: {z1}"
)
Step 2: Hidden layer activation function
a1
=
relu
(
z1
)
(
f
"After hidden layer activation a1: {a1}"
)
Step 3: Output layer linear transformation
z2
=
W2
@
a1 + b2
(
f
"Output layer linear transformation z2: {z2}"
)
Step 4: Output layer activation (usually Softmax for classification problems)
a2
=
softmax
(
z2
)
Use the softmax function defined earlier
(
f
"After the output layer activation, a2: {a2}"
)
The advantage of the computational graph is that every step is clear, and during backpropagation, gradients only need to be calculated in the reverse order.
Neural networks from the perspective of matrix multiplication
From the perspective of matrix multiplication, a neural network is a series of "linear transformations + nonlinear activations".
Each layer can be abstracted as:
aᵢ = activation(Wᵢ · aᵢ₋₁ + bᵢ)
where a₀ is the input x.
This formula is concise yet powerful—it can represent almost all neural network structures from simple logistic regression to complex Transformers.
Note the dimension matching of matrix multiplication: if the input vector is n-dimensional and the next layer has m neurons, the shape of the weight matrix W must be m×n. After W·x, an m-dimensional vector is obtained.
The role of the activation function
As mentioned before: without an activation function, a deep network is equivalent to a single-layer network.
Proving this with a simple example:
Instance
============================================
Why activation function is needed
============================================
import
numpy
as
np
Assume there is a two-layer network, but neither has an activation function
Input
x
=
np.
array
(
[
1.0
,
2.0
]
)
First layer weights and biases
W1
=
np.
array
(
[
[
0.1
,
0.2
]
,
[
0.3
,
0.4
]
]
)
b1
=
np.
array
(
[
0.1
,
0.2
]
)
Second layer weights and biases
W2
=
np.
array
(
[
[
0.5
,
0.6
]
,
[
0.7
,
0.8
]
]
)
b2
=
np.
array
(
[
0.3
,
0.4
]
)
Calculate on two layers respectively
z1
=
W1
@
x + b1
z2
=
W2
@
z1 + b2
(
f
Calculate results for two layers: {z2}
)
Merge into one layer calculation
Mathematically, it can be proven that: z2 = (W2·W1)·x + (W2·b1 + b2)
W_combined
=
W2
@
W1
b_combined
=
W2
@
b1 + b2
z_combined
=
W_combined
@
x + b_combined
(
f
"Combined into one layer calculation result: {z_combined}"
)
The results are exactly the same!
(
f
"\nTwo results are equal: {np.allclose(z2, z_combined)}"
)
(
"Conclusion: Without an activation function, a deep network = a single-layer network"
)
The activation function is the key component that makes deep networks meaningful—it introduces non-linearity, allowing the network to learn complex patterns.
Detailed explanation of activation functions
The activation function determines how a neuron's output responds to its input.
A good activation function should satisfy several conditions:
- Non-linearity: This is essential
- Differentiable: This allows gradient calculation
- Computationally simple: Both forward and backward propagation must be fast
- No saturation: Gradients will not vanish or explode
Let's look at the most commonly used activation functions.
Sigmoid: Saturation and vanishing gradients
Sigmoid is one of the earliest used activation functions. It compresses any real number into the range (0, 1).
Formula: σ(x) = 1 / (1 + e⁻ˣ)
Example
============================================
Sigmoid activation function
============================================
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
def
sigmoid
(
x
)
:
"""Sigmoid function"""
return
1
/
(
1
- np.
exp
(
-x
)
)
def
sigmoid_derivative
(
x
)
:
"""The derivative of the sigmoid: σ'(x) = σ(x) * (1 - σ(x))"""
s
=
sigmoid
(
x
)
return
s *
(
1
- s
)
Test some values
x_values
=
[
10
,
5
,
2
,
0
,
2
,
5
,
10
]
(
"x | sigmoid(x) | sigmoid'(x)"
)
(
"-"
40
)
for
x
in
x_values:
s
=
sigmoid
(
x
)
d
=
sigmoid_derivative
(
x
)
(
f
"{x:4} | {s:10.6f} | {d:12.6f}"
)
Observation: When x is very large or very small, the derivative approaches 0
This is the "vanishing gradient" problem
x_big
=
10.0
(
f
"\nWhen x = {x_big}:"
)
(
f
" sigmoid(x) = {sigmoid(x_big):.10f} (almost 1)"
)
(
f
"sigmoid'(x) = {sigmoid_derivative(x_big):.10f} (almost 0)"
)
(
"Gradient has vanished! Gradients cannot propagate during backpropagation."
)
The problem with Sigmoid is very obvious:
- When |x| > 6, the gradient is almost 0, leading to gradient vanishing
- The output is not centered at 0, which affects optimization
- Calculating exponentials is slow
Due to these issues, Sigmoid is rarely used in hidden layers in modern deep learning.
ReLU and its variants
ReLU (Rectified Linear Unit) is the most commonly used activation function now.
Formula: ReLU(x) = max(0, x)
Simple but very effective.
Example
============================================
ReLU and its variants
============================================
import
numpy
as
np
def
relu
(
x
)
:
"""ReLU: max(0, x)"""
return
np.
maximum
(
0
,
x
)
def
relu_derivative
(
x
)
:
"""The derivative of ReLU: 1 if x > 0, otherwise 0"""
return
(
x
0
)
.
astype
(
float
)
def
leaky_relu
(
x
,
alpha
=
0.01
)
:
"""Leaky ReLU: x is x when x > 0, otherwise it is alpha*x"""
return
np.
where
(
x
0
,
x
,
alpha * x
)
def
gelu
(
x
)
:
"""GELU: Gaussian Error Linear Unit
This is an activation function commonly used in Transformers
Approximation formula: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715*x^3)))
"""
cdf
=
0.5
(
1.0
- np.
tanh
(
np.
sqrt
(
2
/ np.
pi
)
(
x +
0.044715
- np.
power
(
x
,
3
)
)
)
)
return
x * cdf
Test
x_values
=
[
5
,
2
,
1
,
0
,
1
,
2
,
5
]
(
"x | ReLU | Leaky | GELU"
)
(
"-"
45
)
for
x
in
x_values:
r
=
relu
(
x
)
lr
=
leaky_relu
(
x
)
g
=
gelu
(
x
)
(
f
"{x:4} | {r:4.2f} | {lr:5.2f} | {g:5.2f}"
)
Advantages of ReLU:
(
"\nAdvantages of ReLU:"
)
(
"1. Simple calculation: only max operation is needed"
)
(
"2. No saturation (positive range): gradient is always 1"
)
(
"3. Sparsity: Some neuron outputs are 0, increasing model robustness"
)
ReLU's problem: "Dying ReLU"
(
"The problem with ReLU: Dying ReLU"
)
(
"If a neuron's input is always negative, then:"
)
(
"- Output is always 0"
)
(
"- Gradient is always 0"
)
(
- The parameter will never update
)
(
- This neuron is 'dead'
)
Comparison of several common activation functions:
| Activation function | Formula | Advantages | Disadvantages | Applicable Scenarios |
|---|---|---|---|---|
| Sigmoid | 1/(1+e⁻ˣ) | Output is in (0,1), can be interpreted as probability | Gradient vanishing, non-zero center, slow computation | Binary classification output layer (rarely used in hidden layers) |
| ReLU | max(0, x) | Fast computation, non-saturation, sparsity | Dying ReLU, non-zero center output | Most hidden layers (default selection) |
| Leaky ReLU | max(αx, x) | Solving the dying ReLU problem | α needs to be manually selected | Alternatives when ReLU fails |
| GELU | x·Φ(x) | Smooth, works well in Transformers | Slightly more complex computation | Transformer, BERT, GPT, etc. |
| Swish/SwiGLU | x·σ(βx) | Superior to ReLU in deep networks | Computational complexity | Large models such as PaLM, LLaMA |
Selection principles
Activation function selection recommendations:
- Hidden layer: Prioritize ReLU, it is simple and effective
- If you encounter dying ReLU: Try Leaky ReLU or GELU
- Transformer: GELU or SwiGLU are standard choices
- Binary classification output layer: Sigmoid (output probability)
- Multi-class classification output layerSoftmax (output probability distribution)
- Regression output layerNo activation (output any real number)
Don't obsess too much over the choice of activation function. ReLU is usually good enough. You can switch to others when you confirm ReLU is the bottleneck.
Loss function
The loss function measures the gap between the "model's prediction" and the "true answer."
The goal of training is to make this gap as small as possible.
Cross-entropy loss (classification)
The most commonly used loss function for classification problems is Cross-Entropy Loss.
Its intuitive meaning is: "How much difference there is between the probability distribution predicted by the model and the true distribution."
Example
============================================
Cross-Entropy Loss
============================================
import
numpy
as
np
def
cross_entropy_loss
(
probs
,
target_one_hot
)
:
Cross-entropy loss
probs: The probability distribution predicted by the model, shape (batch_size, num_classes)
target_one_hot: One-hot encoding of the true labels, same shape as above
"""
Add epsilon to prevent log(0)
epsilon
=
1e-12
probs
=
np.
clip
(
probs
,
epsilon
,
1.0
- epsilon
)
Cross-entropy = -sum(target * log(pred))
return
-np.
sum
(
target_one_hot * np.
log
(
probs
)
)
/
len
(
probs
)
def
softmax
(
x
)
:
"Softmax function"
exp_x
=
np.
exp
(
x - np.
max
(
x
,
axis
=
1
,
keepdims
=
True
)
)
return
exp_x / np.
sum
(
exp_x
,
axis
=
1
,
keepdims
=
True
)
Example: a three-class classification problem, the classes are "cat", "dog", and "bird"
Assume the true label is "cat" (index 0), one-hot encoding
target
=
np.
array
(
[
[
1
,
0
,
0
]
]
)
The correct answer is class 0
Scenario 1: The model confidently predicts "cat"
logits1
=
np.
array
(
[
[
5.0
,
0.5
,
0.1
]
]
)
Cat score is highest
probs1
=
softmax
(
logits1
)
loss1
=
cross_entropy_loss
(
probs1
,
target
)
(
"Scenario 1: Model confidently predicts correctly"
)
(
f
" Probability distribution: {probs1[0]}"
)
(
f
" Loss: {loss1:.6f} (very small)"
)
Scenario 2: Model uncertainty
logits2
=
np.
array
(
[
[
1.0
,
0.9
,
0.8
]
]
)
The scores of the three categories are similar
probs2
=
softmax
(
logits2
)
loss2
=
cross_entropy_loss
(
probs2
,
target
)
(
"\nScenario 2: Model Uncertainty"
)
(
f
" Probability distribution: {probs2[0]}"
)
(
f
" Loss: {loss2:.6f} (Medium)"
)
Scenario 3: Model prediction error
logits3
=
np.
array
(
[
[
0.1
,
5.0
,
0.5
]
]
)
Dog has the highest score
probs3
=
softmax
(
logits3
)
loss3
=
cross_entropy_loss
(
probs3
,
target
)
(
"\nScenario 3: Model prediction error"
)
(
f
" Probability distribution: {probs3[0]}"
)
(
f
" Loss: {loss3:.6f} (very large)"
)
A simplified version of cross-entropy loss: when labels are class indices instead of one-hot encoding, a more efficient calculation method can be used:
loss = -log(probs[target_class])
This is why CrossEntropyLoss in PyTorch directly accepts class indices as labels.
MSE Loss (Regression)
The most commonly used loss for regression problems (predicting continuous values) is Mean Squared Error (MSE).
Formula: MSE = mean((pred - target)²)
Example
============================================
MSE Loss
============================================
import
numpy
as
np
def
mse_loss
(
pred
,
target
)
:
"""Mean Squared Error Loss"""
return
np.
mean
(
(
pred - target
)
**
2
)
def
mae_loss
(
pred
,
target
)
:
"Mean absolute error loss"
return
np.
mean
(
np.
abs
(
pred - target
)
)
Example: Predicting housing prices (unit: ten thousand yuan)
Actual housing prices
target
=
np.
array
(
[
100
,
200
,
150
]
)
Scenario 1: Prediction is very accurate
pred1
=
np.
array
(
[
102
,
195
,
148
]
)
mse1
=
mse_loss
(
pred1
,
target
)
mae1
=
mae_loss
(
pred1
,
target
)
(
"Scenario 1: Prediction Accuracy"
)
(
f
" Prediction: {pred1}"
)
(
f
" Real: {target}"
)
(
f
" MSE: {mse1:.2f}"
)
(
f
" MAE: {mae1:.2f}"
)
Scenario 2: predicting a large error
pred2
=
np.
array
(
[
102
,
280
,
148
]
)
The prediction for the second house was 800,000 too high
mse2
=
mse_loss
(
pred2
,
target
)
mae2
=
mae_loss
(
pred2
,
target
)
(
"\nScene 2: There is a large error"
)
(
f
" Predict: {pred2}"
)
(
f
" Real: {target}"
)
(
f
" MSE: {mse2:.2f} (magnified by large error)"
)
(
f
" MAE: {mae2:.2f}"
)
MSE vs MAE
(
"MSE vs MAE:"
)
(
"- MSE is more sensitive to large errors (because of squaring)"
)
(
"- MAE is more robust to outliers"
)
(
"- MSE is generally used more"
)
Loss for language models predicting the next word
The training objective for large language models (like GPT) is simple: given the preceding text, predict the next word.
This is essentially a multi-class classification problem—each word in the vocabulary is a class.
Example
============================================
Language model loss function
============================================
import
numpy
as
np
def
language_model_loss
(
logits
,
targets
,
vocab_size
)
:
"""Language model loss
Essentially the cross-entropy loss for each position
"""
batch_size
,
seq_len
,
_
=
logits.
shape
total_loss
=
0.0
Calculate loss for each position in the sequence
for
i
in
range
(
seq_len
)
:
prediction score at this position
step_logits
=
logits
[
:
,
i
,
:
]
Convert to probability
step_probs
=
softmax
(
step_logits
)
Index of the target word
step_target
=
targets
[
:
,
i
]
Only take the probability of the target word
for
b
in
range
(
batch_size
)
:
target_idx
=
step_target
[
b
]
target_prob
=
step_probs
[
b
,
target_idx
]
loss = -log(p)
total_loss +
=
-np.
log
(
target_prob +
1e-12
)
return
total_loss /
(
batch_size * seq_len
)
A simple example
vocab_size
=
10000
Assume vocabulary size is 10k
batch_size
=
2
seq_len
=
3
Model output: (batch_size, seq_len, vocab_size)
logits
=
np.
random
.
randn
(
batch_size
,
seq_len
,
vocab_size
)
Ground truth: the word index that should be predicted at each position
targets
=
np.
array
(
[
[
123
,
456
,
789
]
,
The target word of the first sequence
[
234
,
567
,
890
]
,
The target word of the second sequence
]
)
loss
=
language_model_loss
(
logits
,
targets
,
vocab_size
)
(
f
"Language model loss: {loss:.4f}"
)
(
"\nMeaning of this loss:"
)
(
"- for each position in the sequence"
)
(
"- predict the next word"
)
(
"- Calculate the average cross-entropy of all positions"
)
Summary of common loss functions:
| Task type | Loss function | Output layer activation | Label format |
|---|---|---|---|
| Binary classification | Binary Cross-Entropy | Sigmoid | 0 or 1 |
| Multi-class classification | Cross-Entropy | Softmax | Category Index |
| Multi-label Classification | Binary Cross-Entropy | Sigmoid | Multiple 0/1 |
| Regression | MSE / MAE | None | Continuous values |
| Language model | Cross-Entropy | Softmax | Word index |
Backpropagation
Backpropagation is the core algorithm for training neural networks.
Its goal is to calculate the gradient of the loss function with respect to each parameter, and then update the parameters using gradient descent.
Chain rule derivation
We will derive backpropagation step by step using a simple example.
Example
============================================
Manual implementation of backpropagation
============================================
import
numpy
as
np
def
relu
(
x
)
:
return
np.
maximum
(
0
,
x
)
def
relu_derivative
(
x
)
:
return
(
x
0
)
.
astype
(
float
)
def
mse_loss
(
pred
,
target
)
:
return
np.
mean
(
(
pred - target
)
**
2
)
A very simple neural network: a single linear transformation layer
y = w * x + b
Loss = (y - target)^2
Input and target
x
=
np.
array
(
2.0
)
target
=
np.
array
(
7.0
)
initialization parameters
w
=
np.
array
(
1.0
)
b
=
np.
array
(
0.0
)
(
f
"Initial parameters: w = {w}, b = {b}"
)
(
f
"Target: {target}"
)
============================================
Step 1: Forward Propagation
============================================
y
=
w * x + b
loss
=
(
y - target
)
**
2
(
f
"Forward propagation:"
)
(
f
" y = {y}"
)
(
f
" loss = {loss}"
)
============================================
Step 2: Backpropagation (Manual Gradient Calculation)
============================================
We need to calculate: d_loss/d_w, d_loss/d_b
Use the chain rule step by step:
loss = (y - target)^2
d_loss/d_y = 2 * (y - target)
d_loss_d_y
=
2
(
y - target
)
y = w * x + b
d_y/d_w = x
d_y/d_b = 1
d_y_d_w
=
x
d_y_d_b
=
1.0
Chain rule:
d_loss/d_w = d_loss/d_y * d_y/d_w
d_loss/d_b = d_loss/d_y * d_y/d_b
d_loss_d_w
=
d_loss_d_y * d_y_d_w
d_loss_d_b
=
d_loss_d_y * d_y_d_b
(
f
"\nBackpropagation:"
)
(
f
" d_loss/d_y = {d_loss_d_y}"
)
(
f
" d_loss/d_w = {d_loss_d_w}"
)
(
f
" d_loss/d_b = {d_loss_d_b}"
)
============================================
Step 3: Gradient Descent Parameter Update
============================================
learning_rate
=
0.1
w_new
=
w - learning_rate * d_loss_d_w
b_new
=
b - learning_rate * d_loss_d_b
(
f
"\nParameter update:"
)
(
f
" w: {w} -> {w_new}"
)
(
f
" b: {b} -> {b_new}"
)
Verification: forward propagation with new parameters
y_new
=
w_new * x + b_new
loss_new
=
(
y_new - target
)
**
2
(
f
"Verification:"
)
(
f
" Old prediction: {y}, Old loss: {loss}"
)
(
f
" New prediction: {y_new}, New loss: {loss_new}"
)
(
f
" Loss decreased!"
)
Although this example is simple, it contains all the core ideas of backpropagation:
- Forward propagation: calculating all intermediate variables
- Backpropagation: calculating gradients layer by layer starting from the output using the chain rule
- Parameter update: updating parameters using gradient descent
Gradient flow in the computation graph
For multi-layer neural networks, gradients flow backward in the computation graph.
The gradient of each layer depends on the gradient passed from the subsequent layer.
Instance
============================================
Backpropagation of a two-layer network
============================================
import
numpy
as
np
def
relu
(
x
)
:
return
np.
maximum
(
0
,
x
)
def
relu_derivative
(
x
)
:
return
(
x
0
)
.
astype
(
float
)
A two-layer network
Input (2) → Hidden layer (3) → Output (1)
Data
x
=
np.
array
(
[
1.0
,
2.0
]
)
Input
target
=
np.
array
(
[
5.0
]
)
Target output
Parameter initialization
W1
=
np.
array
(
[
[
0.1
,
0.2
]
,
[
0.3
,
0.4
]
,
[
0.5
,
0.6
]
]
)
(3, 2)
b1
=
np.
array
(
[
0.1
,
0.2
,
0.3
]
)
(3,)
W2
=
np.
array
(
[
[
0.7
,
0.8
,
0.9
]
]
)
(1, 3)
b2
=
np.
array
(
[
0.4
]
)
(1,)
(
"Initial parameters have been set"
)
============================================
Forward propagation
============================================
(
"\n=== Forward Propagation ===\n"
)
First layer
z1
=
W1
@
x + b1
(3,)
a1
=
relu
(
z1
)
(3,)
(
f
"z1 = {z1}"
)
(
f
"a1 = {a1}"
)
Second layer
z2
=
W2
@
a1 + b2
(1,)
a2
=
z2
Regression task, no activation function in the output layer
(
f
"z2 = {z2}"
)
(
f
"a2 = {a2}"
)
Loss
loss
=
np.
mean
(
(
a2 - target
)
**
2
)
(
f
"loss = {loss}"
)
============================================
Backpropagation
============================================
(
"=== Backpropagation ==="
)
Output layer gradient
d_loss_d_a2
=
2
(
a2 - target
)
(1,)
d_a2_d_z2
=
1.0
No activation function
d_loss_d_z2
=
d_loss_d_a2 * d_a2_d_z2
(1,)
(
f
"d_loss_d_z2 = {d_loss_d_z2}"
)
Second layer parameter gradient
d_z2_d_W2
=
a1
(3,), because z2 = W2@a1 + b2
d_z2_d_b2
=
1.0
(1,)
d_z2_d_a1
=
W2
[
0
]
(3,)
Calculate parameter gradient
d_loss_d_W2
=
d_loss_d_z2.
reshape
(
1
,
1
)
@
d_z2_d_W2.
reshape
(
1
,
1
)
(1, 3)
d_loss_d_b2
=
d_loss_d_z2 * d_z2_d_b2
(1,)
(
f
"d_loss_d_W2 = {d_loss_d_W2}"
)
(
f
"d_loss_d_b2 = {d_loss_d_b2}"
)
Gradient to the hidden layer
d_loss_d_a1
=
d_loss_d_z2
@
d_z2_d_a1
(3,)
(
f
"d_loss_d_a1 = {d_loss_d_a1}"
)
Hidden layer gradient
d_a1_d_z1
=
relu_derivative
(
z1
)
(3,)
d_loss_d_z1
=
d_loss_d_a1 * d_a1_d_z1
(3,)
(
f
"d_loss_d_z1 = {d_loss_d_z1}"
)
First layer parameter gradient
d_z1_d_W1
=
x
(2,)
d_z1_d_b1
=
1.0
(3,)
Calculate parameter gradient
d_loss_d_W1
=
d_loss_d_z1.
reshape
(
1
,
1
)
@
d_z1_d_W1.
reshape
(
1
,
1
)
(3, 2)
d_loss_d_b1
=
d_loss_d_z1 * d_z1_d_b1
(3,)
(
f
"d_loss_d_W1 = {d_loss_d_W1}"
)
(
f
"d_loss_d_b1 = {d_loss_d_b1}"
)
============================================
Parameter Update
============================================
(
"\n=== Parameter Update ==="
)
learning_rate
=
0.01
W1_new
=
W1 - learning_rate * d_loss_d_W1
b1_new
=
b1 - learning_rate * d_loss_d_b1
W2_new
=
W2 - learning_rate * d_loss_d_W2
b2_new
=
b2 - learning_rate * d_loss_d_b2
(
"Parameters updated"
)
This example demonstrates the complete process of backpropagation.
The core rules are:
- For a linear layer y = Wx + b: dL/dW = (dL/dy)·xᵀ, dL/db = dL/dy
- For an activation function y = f(z): dL/dz = dL/dy ⊙ f'(z) (⊙ is element-wise multiplication)
- Gradients propagate from back to front, and each layer "accumulates" the gradient using the chain rule.
The good news is that modern deep learning frameworks (like PyTorch, TensorFlow) automatically calculate backpropagation for you. You only need to define the forward pass, and the framework will handle all gradient calculations using autograd.
Gradient Descent Optimizer
After calculating the gradient, we need to use the optimizer to update the parameters.
The simplest optimizer is Stochastic Gradient Descent (SGD), but there are many more advanced optimizers.
SGD: Stochastic Gradient Descent
Formula: θ = θ - η·∇L(θ)
Where η is the learning rate.
Example
============================================
SGD optimizer
============================================
import
numpy
as
np
def
f
(
x
)
:
"""We want to minimize the function: f(x) = x²"""
return
x **
2
def
f_grad
(
x
)
:
"""Gradient: f'(x) = 2x"""
return
2
- x
SGD optimization
x
=
10.0
Initial value
learning_rate
=
0.1
Learning rate
steps
=
20
(
f
"Initial x = {x}, f(x) = {f(x)}"
)
(
"-"
40
)
for
step
in
range
(
steps
)
:
grad
=
f_grad
(
x
)
x
=
x - learning_rate * grad
SGD update
(
f
"Step {step+1}: x = {x:.6f}, f(x) = {f(x):.6f}"
)
(
"-"
40
)
(
f
"Final x = {x:.6f}, f(x) = {f(x):.6f}"
)
(
"Theoretically optimal: x = 0, f(x) = 0"
)
SGD is simple but has drawbacks:
- Uses the same learning rate for all parameters
- Convergence can be very slow
- Easily gets stuck in local minima or saddle points
- Sensitive to noise
Momentum: Momentum acceleration
Momentum introduces the concept of "velocity"—giving inertia to gradient updates.
Formula:
v = β·v + (1-β)·∇L(θ)
θ = θ - η·v
β is usually set to 0.9.
Example
============================================
Momentum optimizer
============================================
import
numpy
as
np
def
f
(
x
)
:
"""Objective function"""
return
x **
2
def
f_grad
(
x
)
:
"Gradient"
return
2
- x
def
sgd_optimize
(
x_init
,
learning_rate
,
steps
)
:
"""Pure SGD"""
x
=
x_init
history
=
[
x
]
for
_
in
range
(
steps
)
:
grad
=
f_grad
(
x
)
x
=
x - learning_rate * grad
history.
append
(
x
)
return
np.
array
(
history
)
def
momentum_optimize
(
x_init
,
learning_rate
,
beta
,
steps
)
:
"""Momentum"""
x
=
x_init
v
=
0.0
Initial velocity
history
=
[
x
]
for
_
in
range
(
steps
)
:
grad
=
f_grad
(
x
)
v
=
beta * v +
(
1
- beta
)
- grad
x
=
x - learning_rate * v
history.
append
(
x
)
return
np.
array
(
history
)
Comparison
x_init
=
10.0
learning_rate
=
0.1
beta
=
0.9
steps
=
20
sgd_history
=
sgd_optimize
(
x_init
,
learning_rate
,
steps
)
momentum_history
=
momentum_optimize
(
x_init
,
learning_rate
,
beta
,
steps
)
(
"Step | SGD | Momentum"
)
(
"-"
35
)
for
i
in
range
(
steps +
1
)
:
(
f
"{i:4} | {sgd_history[i]:9.6f} | {momentum_history[i]:9.6f}"
)
(
"\nObservation: Momentum converges faster!"
)
(
"Because it accumulates past gradients, it has inertia."
)
Adam: Adaptive Learning Rate
Adam (Adaptive Moment Estimation) is one of the most commonly used optimizers.
It combines the ideas of Momentum (first moment) and RMSProp (second moment) to maintain an adaptive learning rate for each parameter.
Formula:
m = β₁·m + (1-β₁)·∇L(θ)
v = β₂·v + (1-β₂)·(∇L(θ))²
m̂ = m / (1-β₁ᵗ)
v̂ = v / (1-β₂ᵗ)
θ = θ - η·m̂ / (√v̂ + ε)
Hyperparameter default values: $\beta_1=0.9$, $\beta_2=0.999$, $\epsilon=1e-8$, $\eta=1e-3$.
Instance
============================================
Adam optimizer
============================================
import
numpy
as
np
def
adam_optimize
(
x_init
,
learning_rate
,
beta1
,
beta2
,
epsilon
,
steps
)
:
"Adam Optimizer"
x
=
x_init
m
=
0.0
First moment
v
=
0.0
Second moment
history
=
[
x
]
for
t
in
range
(
1
,
steps +
1
)
:
grad
=
2
- x
The gradient of f(x) = x²
Update first and second moments
m
=
beta1 * m +
(
1
- beta1
)
- grad
v
=
beta2 * v +
(
1
- beta2
)
(
grad **
2
)
Bias correction
m_hat
=
m /
(
1
- beta1 ** t
)
v_hat
=
v /
(
1
- beta2 ** t
)
Parameter update
x
=
x - learning_rate * m_hat /
(
np.
sqrt
(
v_hat
)
- epsilon
)
history.
append
(
x
)
return
np.
array
(
history
)
Parameters
x_init
=
10.0
learning_rate
=
0.5
beta1
=
0.9
beta2
=
0.999
epsilon
=
1e-8
steps
=
20
Optimization
history
=
adam_optimize
(
x_init
,
learning_rate
,
beta1
,
beta2
,
epsilon
,
steps
)
(
"Adam optimization process:"
)
(
"Step | x | f(x)"
)
(
"-"
35
)
for
i
in
range
(
steps +
1
)
:
(
f
"{i:4} | {history[i]:9.6f} | {history[i]**2:9.6f}"
)
AdamW: Weight Decay Correction
AdamW is an improved version of Adam—it separates weight decay from the gradient.
This is useful in regularization.
Optimizer Comparison:
| Optimizer | Formula | Advantages | Disadvantages | Applicable Scenarios |
|---|---|---|---|---|
| SGD | θ = θ - η·∇L | Simple, stable | Slow convergence, sensitive to learning rate | Large data volume, rich tuning experience |
| SGD + Momentum | v = βv + (1-β)∇L | |||
| θ = θ - ηv | Accelerate convergence, reduce oscillation | Need to tune β | Generally better than pure SGD | |
| Adam | Adaptive learning rate | Fast convergence, requires less tuning | May generalize less than SGD | Most scenarios (default selection) |
| AdamW | Adam + weight decay | Better regularization | Requires tuning the weight decay coefficient | Transformer, Large Models |
Optimizer selection suggestions: Try Adam first, set the learning rate to 1e-3 (3e-4 is a more conservative choice). If the results are not satisfactory, then try tuning parameters or switching to another optimizer.
Regularization techniques
The goal of regularization is to prevent overfitting—to allow the model to perform well on unseen data.
L1/L2 Regularization
L1 and L2 regularization are the most basic regularization methods.
They add a penalty on the parameters to the loss function:
L_total = L + λ·L_reg
L1 Regularization (Lasso): L_reg = |w|
L2 Regularization (Ridge): L_reg = w²
Instance
============================================
L1/L2 Regularization
============================================
import
numpy
as
np
def
l1_regularization
(
weights
,
lambda_l1
)
:
"""L1 Regularization: returns regularization term and gradient"""
reg
=
lambda_l1 * np.
sum
(
np.
abs
(
weights
)
)
grad
=
lambda_l1 * np.
sign
(
weights
)
return
reg
,
grad
def
l2_regularization
(
weights
,
lambda_l2
)
:
"""L2 Regularization: returns regularization term and gradient"""
reg
=
0.5
- lambda_l2 * np.
sum
(
weights **
2
)
grad
=
lambda_l2 * weights
return
reg
,
grad
Example
weights
=
np.
array
(
[
1.0
,
2.0
,
3.0
,
0.5
]
)
(
f
"weights: {weights}"
)
lambda_l1
=
0.1
lambda_l2
=
0.1
l1_reg
,
l1_grad
=
l1_regularization
(
weights
,
lambda_l1
)
(
f
"\nL1 Regularization term: {l1_reg:.4f}"
)
(
f
"L1 gradient: {l1_grad}"
)
l2_reg
,
l2_grad
=
l2_regularization
(
weights
,
lambda_l2
)
(
f
"\nL2 regularization term: {l2_reg:.4f}"
)
(
f
"L2 gradient: {l2_grad}"
)
(
"\nL1 vs L2:"
)
(
"- L1: tends to produce sparse solutions (many parameters become 0), can be used for feature selection"
)
(
"- L2: tends to keep all parameters small, but not 0"
)
(
"- L2 is more commonly used in deep learning (or weight decay in AdamW)"
)
Dropout
Dropout is a simple yet effective regularization technique: randomly "turning off" a portion of neurons during training.
This forces the model to learn more robust features—it cannot rely on any specific neuron.
Example
============================================
Dropout
============================================
import
numpy
as
np
def
dropout_forward
(
x
,
dropout_rate
,
training
=
True
)
:
"""Dropout forward propagation"""
if
not
training:
Do not dropout during testing, return directly
return
x
Generate mask: randomly select a portion of neurons and set them to 0
mask
=
(
np.
random
.
rand
(
*x.
shape
)
dropout_rate
)
.
astype
(
float
)
Scaling: No scaling is needed during testing, so divide by (1-dropout_rate) during training
scale
=
1.0
/
(
1.0
- dropout_rate
)
Apply dropout
out
=
x * mask * scale
return
out
,
mask
Test
x
=
np.
array
(
[
1.0
,
2.0
,
3.0
,
4.0
,
5.0
]
)
dropout_rate
=
0.4
(
f
"Enter x: {x}"
)
(
f
"Dropout Rate: {dropout_rate}"
)
Run multiple times and observe randomness
(
"\nMultiple Dropout results:"
)
for
i
in
range
(
3
)
:
out
,
mask
=
dropout_forward
(
x
,
dropout_rate
,
training
=
True
)
(
f
" Iteration {i+1}: mask={mask}, out={out}"
)
Test mode
out_test
=
dropout_forward
(
x
,
dropout_rate
,
training
=
False
)
(
f
"Test mode (no Dropout): {out_test}"
)
Data Augmentation
Data augmentation is one of the most effective regularization methods—creating more training samples by transforming existing data.
For images, common data augmentations include: flipping, rotating, scaling, cropping, color jittering, etc.
For text, common data augmentations include: synonym replacement, random insertion, random deletion, back-translation, etc.
Summary of Regularization Techniques:
| Methods | Principles | Advantages | Disadvantages |
|---|---|---|---|
| L2 Regularization | Penalize large weights | Simple, stable | Limited effect |
| Dropout | Randomly turn off neurons | Simple and effective | Slow down training |
| Data augmentation | Increase training data diversity | Significant effect | Requires domain knowledge |
| Early Stopping | Stop if validation set does not improve | Simple and effective | Requires monitoring the validation set |
| Batch normalization | Normalization layer input | Accelerate training, regularization | Increase computational overhead |
Batch Normalization vs Layer Normalization
Normalization techniques can accelerate training and make optimization more stable.
Internal Covariate Shift
When training deep networks, the input distribution of each layer changes as the parameters of the previous layer change. This is called "Internal Covariate Shift".
This causes training to slow down because each layer must constantly adapt to new distributions.
The goal of normalization techniques is to keep the input distribution of each layer stable.
Batch Normalization
Batch normalization (BatchNorm) performs normalization across the batch dimension.
Formula:
μ = 1/N · sum(xᵢ)
σ² = 1/N · sum((xᵢ - μ)²)
x̂ᵢ = (xᵢ - μ) / √(σ² + ε)
yᵢ = γ·x̂ᵢ + β
where $\gamma$ and $\beta$ are learnable parameters.
Example
============================================
Batch Normalization
============================================
import
numpy
as
np
def
batch_norm
(
x
,
gamma
,
beta
,
epsilon
=
1e-5
,
training
=
True
,
running_mean
=
None
,
running_var
=
None
,
momentum
=
0.1
)
:
Batch normalization
x: input, shape (batch_size, features)
gamma: scaling parameter
beta: offset parameter
"""
if
training:
Training mode: use statistics of the current batch
batch_mean
=
np.
mean
(
x
,
axis
=
0
)
batch_var
=
np.
var
(
x
,
axis
=
0
)
Update running statistics (for testing)
if
running_mean
is
not
None
and
running_var
is
not
None
:
running_mean
[
:
]
=
momentum * running_mean +
(
1
- momentum
)
- batch_mean
running_var
[
:
]
=
momentum * running_var +
(
1
- momentum
)
- batch_var
Normalization
x_normalized
=
(
x - batch_mean
)
/ np.
sqrt
(
batch_var + epsilon
)
else
:
Test mode: use running statistics
x_normalized
=
(
x - running_mean
)
/ np.
sqrt
(
running_var + epsilon
)
Scaling and offset
out
=
gamma * x_normalized + beta
return
out
Test
batch_size
=
4
features
=
3
A batch of data
x
=
np.
array
(
[
[
1.0
,
2.0
,
3.0
]
,
[
2.0
,
3.0
,
4.0
]
,
[
3.0
,
4.0
,
5.0
]
,
[
4.0
,
5.0
,
6.0
]
,
]
)
(
f
"Input x:\n{x}"
)
Initial parameters
gamma
=
np.
ones
(
features
)
Initial no scaling
beta
=
np.
zeros
(
features
)
Initial no offset
(
f
"\ngamma: {gamma}"
)
(
f
"beta: {beta}"
)
Apply batch normalization
out
=
batch_norm
(
x
,
gamma
,
beta
,
training
=
True
)
(
f
"\nAfter batch normalization:\n{out}"
)
Verification: The mean of each feature should be close to 0, and the variance close to 1
(
f
"\nMean after normalization: {np.mean(out, axis=0)}"
)
(
f
"Normalized variance: {np.var(out, axis=0)}"
)
Advantages of batch normalization:
- Accelerate training
- Allows for a larger learning rate
- Reduces sensitivity to initialization
- Has a slight regularization effect
Disadvantages of Batch Normalization:
- Depends on batch size—poor performance with small batches
- Behaves differently during training and testing
- Not suitable for sequence models (such as RNN, Transformer)
Layer Normalization
Layer normalization (LayerNorm) normalizes across the feature dimension, not the batch dimension.
This makes it independent of batch size, making it very suitable for sequence models.
Example
============================================
Layer Normalization
============================================
import
numpy
as
np
def
layer_norm
(
x
,
gamma
,
beta
,
epsilon
=
1e-5
)
:
Layer normalization
x: input, shape (batch_size, features) or (batch_size, seq_len, features)
"""
Calculate mean and variance over the last dimension (feature dimension)
mean
=
np.
mean
(
x
,
axis
=
1
,
keepdims
=
True
)
var
=
np.
var
(
x
,
axis
=
1
,
keepdims
=
True
)
Normalization
x_normalized
=
(
x - mean
)
/ np.
sqrt
(
var + epsilon
)
Scaling and offsetting
out
=
gamma * x_normalized + beta
return
out
Test
batch_size
=
2
seq_len
=
3
features
=
4
Simulate the input in a Transformer: (batch_size, seq_len, features)
x
=
np.
array
(
[
[
[
1.0
,
2.0
,
3.0
,
4.0
]
,
[
2.0
,
3.0
,
4.0
,
5.0
]
,
[
3.0
,
4.0
,
5.0
,
6.0
]
]
,
[
[
4.0
,
5.0
,
6.0
,
7.0
]
,
[
5.0
,
6.0
,
7.0
,
8.0
]
,
[
6.0
,
7.0
,
8.0
,
9.0
]
]
,
]
)
(
f
"Input x shape: {x.shape}"
)
Initial parameters
gamma
=
np.
ones
(
features
)
beta
=
np.
zeros
(
features
)
Application layer normalization
out
=
layer_norm
(
x
,
gamma
,
beta
)
(
f
"Shape after layer normalization: {out.shape}"
)
Verification: mean of each position is close to 0, variance is close to 1
mean_check
=
np.
mean
(
out
,
axis
=
1
)
var_check
=
np.
var
(
out
,
axis
=
1
)
(
f
"\nMean of each position:\n{mean_check}"
)
(
f
"Variance at each position:\n{var_check}"
)
Comparison of two normalization methods:
| Method | Normalization dimension | Depends on batch | Applicable scenarios | Representative model |
|---|---|---|---|---|
| BatchNorm | batch dimension | Is | CNN, fixed batch size | ResNet, VGG |
| LayerNorm | Feature dimension | No | Transformer, RNN, variable-length sequences | GPT, BERT, LLaMA |
For Transformer and large language models, LayerNorm is the standard choice. It calculates statistics independently at each position, does not depend on batch size, and does not require maintaining running statistics.
Learning rate scheduling
Learning rate is one of the most important hyperparameters—too large and it won't converge, too small and it converges too slowly.
Learning Rate Scheduling dynamically adjusts the learning rate during training.
Warmup
In the early stages of training, it first "warms up" with a small learning rate to let the model stabilize, and then increases it to the target learning rate.
This is especially important for Transformers.
Cosine Annealing
Cosine Annealing makes the learning rate gradually decrease following the shape of the cosine function.
Example
============================================
Learning Rate Scheduling
============================================
import
numpy
as
np
def
warmup_schedule
(
step
,
warmup_steps
,
base_lr
)
:
"Linear Warmup Scheduling"
if
step
<
warmup_steps:
return
base_lr *
(
step +
1
)
/ warmup_steps
return
base_lr
def
cosine_annealing_schedule
(
step
,
total_steps
,
base_lr
,
min_lr
=
0.0
)
:
"Cosine Annealing Scheduler"
return
min_lr +
0.5
(
base_lr - min_lr
)
(
1
- np.
cos
(
np.
pi
- step / total_steps
)
)
def
warmup_cosine_schedule
(
step
,
warmup_steps
,
total_steps
,
base_lr
,
min_lr
=
0.0
)
:
"""Warm-up + Cosine Annealing"""
if
step
<
warmup_steps:
return
base_lr *
(
step +
1
)
/ warmup_steps
return
min_lr +
0.5
(
base_lr - min_lr
)
(
1
- np.
cos
(
np.
pi
(
step - warmup_steps
)
/
(
total_steps - warmup_steps
)
)
)
Parameters
total_steps
=
100
warmup_steps
=
10
base_lr
=
1e-3
min_lr
=
1e-5
(
"Different learning rate schedules:"
)
(
"Step | Warmup | Cosine | Warmup+Cosine"
)
(
"-"
55
)
for
step
in
range
(
0
,
total_steps +
1
,
10
)
:
lr_warmup
=
warmup_schedule
(
step
,
warmup_steps
,
base_lr
)
lr_cosine
=
cosine_annealing_schedule
(
step
,
total_steps
,
base_lr
,
min_lr
)
lr_combined
=
warmup_cosine_schedule
(
step
,
warmup_steps
,
total_steps
,
base_lr
,
min_lr
)
(
f
"{step:4} | {lr_warmup:.6f} | {lr_cosine:.6f} | {lr_combined:.6f}"
)
Effect of learning rate on training
Effect of learning rate:
- Too large: unstable training, may diverge
- Too small: slow convergence, may get stuck in local optima
- Appropriate: fast and stable convergence
A common strategy is the "Learning Rate Finder": train for a few steps with learning rates ranging from small to large to see which learning rate causes the loss to decrease the fastest.
Summary of Learning Rate Scheduling Methods:
| Scheduling Method | Characteristics | Applicable Scenarios |
|---|---|---|
| Fixed Learning Rate | Simplest | Small models, simple tasks |
| Step Decay | Decay every few steps | CNN, etc. |
| Cosine Annealing | Smooth decay | Most scenarios |
| Warmup + Cosine | Increase then decrease | Transformer, Large Models (Recommended) |
| Reduce on Plateau | Decrease if validation set does not improve | Need to monitor the validation set |
Practical: Implement MLP from scratch using PyTorch
Now we will integrate all the knowledge points from before to implement a complete Multi-Layer Perceptron (MLP) using PyTorch and train it on a simple classification task.
Example
============================================
PyTorch implementation of the complete MLP training process
============================================
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
from
torch.
utils
.
data
import
Dataset
,
DataLoader
import
numpy
as
np
============================================
1. Prepare data
============================================
class
SimpleDataset
(
Dataset
)
:
"""A simple binary classification dataset"""
def
init
(
self
,
n_samples
=
1000
,
n_features
=
10
)
:
Generate synthetic data
np.
random
.
seed
(
42
)
self
.
X
=
np.
random
.
randn
(
n_samples
,
n_features
)
.
astype
(
np.
float32
)
Simple classification rule: y = 1 if sum(x[:5]) > 0 else 0
self
.
y
=
(
np.
sum
(
self
.
X
[
:
,
:
5
]
,
axis
=
1
)
0
)
.
astype
(
np.
int64
)
def
len
(
self
)
:
return
len
(
self
.
X
)
def
getitem
(
self
,
idx
)
:
return
torch.
tensor
(
self
.
X
[
idx
]
)
,
torch.
tensor
(
self
.
y
[
idx
]
)
Create dataset and data loader
train_dataset
=
SimpleDataset
(
n_samples
=
800
)
val_dataset
=
SimpleDataset
(
n_samples
=
200
)
train_loader
=
DataLoader
(
train_dataset
,
batch_size
=
32
,
shuffle
=
True
)
val_loader
=
DataLoader
(
val_dataset
,
batch_size
=
32
,
shuffle
=
False
)
(
f
"Training set size: {len(train_dataset)}"
)
(
f
"Validation set size: {len(val_dataset)}"
)
============================================
2. Define Model
============================================
class
MLP
(
nn.
Module
)
:
"""Multilayer Perceptron"""
def
init
(
self
,
input_dim
,
hidden_dims
,
output_dim
,
dropout_rate
=
0.1
)
:
super
(
)
.
init
(
)
layers
=
[
]
prev_dim
=
input_dim
Hidden layer
for
hidden_dim
in
hidden_dims:
layers.
append
(
nn.
Linear
(
prev_dim
,
hidden_dim
)
)
layers.
append
(
nn.
ReLU
(
)
)
layers.
append
(
nn.
LayerNorm
(
hidden_dim
)
)
Layer normalization
layers.
append
(
nn.
Dropout
(
dropout_rate
)
)
Dropout
prev_dim
=
hidden_dim
Output layer
layers.
append
(
nn.
Linear
(
prev_dim
,
output_dim
)
)
self
.
model
=
nn.
Sequential
(
*layers
)
def
forward
(
self
,
x
)
:
return
self
.
model
(
x
)
Create model
model
=
MLP
(
input_dim
=
10
,
hidden_dims
=
[
64
,
32
]
,
output_dim
=
2
,
dropout_rate
=
0.1
)
(
"\nModel structure:"
)
(
model
)
============================================
3. Define loss function and optimizer
============================================
criterion
=
nn.
CrossEntropyLoss
(
)
Cross-entropy loss
optimizer
=
optim.
AdamW
(
model.
parameters
(
)
,
lr
=
1e-3
,
weight_decay
=
1e-4
)
AdamW optimizer
Learning rate scheduling: warmup + cosine annealing
total_epochs
=
20
warmup_epochs
=
2
total_steps
=
len
(
train_loader
)
- total_epochs
warmup_steps
=
len
(
train_loader
)
- warmup_epochs
def
lr_lambda
(
step
)
:
if
step
<
warmup_steps:
return
(
step +
1
)
/ warmup_steps
else
:
progress
=
(
step - warmup_steps
)
/
(
total_steps - warmup_steps
)
return
0.5
(
1
- np.
cos
(
np.
pi
- progress
)
)
scheduler
=
optim.
lr_scheduler
.
LambdaLR
(
optimizer
,
lr_lambda
=
lr_lambda
)
(
"\nTraining configuration:"
)
(
f
" Epochs: {total_epochs}"
)
(
f
" Warmup epochs: {warmup_epochs}"
)
(
f
" Total steps: {total_steps}"
)
(
f
" Warmup steps: {warmup_steps}"
)
============================================
4. Training Loop
============================================
(
"\nStarting training..."
)
(
"-"
50
)
global_step
=
0
best_val_acc
=
0.0
for
epoch
in
range
(
total_epochs
)
:
Training phase
model.
train
(
)
train_loss
=
0.0
train_correct
=
0
train_total
=
0
for
batch_X
,
batch_y
in
train_loader:
Forward propagation
logits
=
model
(
batch_X
)
loss
=
criterion
(
logits
,
batch_y
)
Backpropagation
optimizer.
zero_grad
(
)
loss.
backward
(
)
optimizer.
step
(
)
scheduler.
step
(
)
Statistics
train_loss +
=
loss.
item
(
)
predicted
=
torch.
argmax
(
logits
,
dim
=
1
)
train_total +
=
batch_y.
size
(
0
)
train_correct +
=
(
predicted
==
batch_y
)
.
sum
(
)
.
item
(
)
global_step +
=
1
train_loss /
=
len
(
train_loader
)
train_acc
=
train_correct / train_total
Validation phase
model.
eval
(
)
val_loss
=
0.0
val_correct
=
0
val_total
=
0
with
torch.
no_grad
(
)
:
for
batch_X
,
batch_y
in
val_loader:
logits
=
model
(
batch_X
)
loss
=
criterion
(
logits
,
batch_y
)
val_loss +
=
loss.
item
(
)
predicted
=
torch.
argmax
(
logits
,
dim
=
1
)
val_total +
=
batch_y.
size
(
0
)
val_correct +
=
(
predicted
==
batch_y
)
.
sum
(
)
.
item
(
)
val_loss /
=
len
(
val_loader
)
val_acc
=
val_correct / val_total
Save the best model
if
val_acc
best_val_acc:
best_val_acc
=
val_acc
This is where the model checkpoint can be saved
Print logs
current_lr
=
optimizer.
param_groups
[
0
]
[
'lr'
]
(
f
"Epoch {epoch+1:2d} | lr: {current_lr:.6f} | "
f
"Train Loss: {train_loss:.4f} | Train Acc: {train_acc:.4f} | "
f
"Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.4f}"
)
(
"-"
50
)
(
f
"Training complete! Best validation accuracy: {best_val_acc:.4f}"
)
============================================
5. Inference Examples
============================================
(
"\nInference example:"
)
model.
eval
(
)
Several test samples
test_samples
=
[
np.
array
(
[
1.0
,
1.0
,
1.0
,
1.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
dtype
=
np.
float32
)
,
Should be 1
np.
array
(
[
1.0
,
1.0
,
1.0
,
1.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
dtype
=
np.
float32
)
,
Should be 0
]
for
i
,
sample
in
enumerate
(
test_samples
)
:
with
torch.
no_grad
(
)
:
input_tensor
=
torch.
tensor
(
sample
)
.
unsqueeze
(
0
)
logits
=
model
(
input_tensor
)
probs
=
torch.
softmax
(
logits
,
dim
=
1
)
predicted_class
=
torch.
argmax
(
probs
,
dim
=
1
)
.
item
(
)
(
f
" Sample {i+1}: {sample[:5]}..."
)
(
f
" Predicted class: {predicted_class}"
)
(
f
" Probability: Class 0={probs[0,0]:.4f}, Class 1={probs[0,1]:.4f}"
)
This example includes all standard components of deep learning training:
- Data processing: Dataset, DataLoader
- Model definition: MLP with LayerNorm and Dropout
- Loss function: CrossEntropyLoss
- Optimizer: AdamW
- Learning Rate Scheduling: Warmup + Cosine
- Training Loop: Training Phase + Validation Phase
- Model Saving and Inference
This process can be directly generalized to more complex tasks and models.