Runoob Tutorial ArchiveEnglish

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:

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,)

print

(

f

"Input x: {x}"

)

print

(

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

]

)

print

(

f

"\nWeight matrix W:\n{W}"

)

print

(

f

"Weight shape: {W.shape}"

)

Bias b: one bias per neuron

b

=

np.

array

(

[

0.1

,

0.2

]

)

 

shape (2,)

print

(

f

"\nBias b: {b}"

)

print

(

f

"Bias shape: {b.shape}"

)

Matrix multiplication: y = W · x + b

Note: numpy's @ operator represents matrix multiplication

y

=

W

@

x + b

print

(

f

"Output y: {y}"

)

print

(

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

print

(

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

)

(

x

)

)

/ h

Calculate the derivative at x=3

x

=

3.0

df_dx

=

numerical_derivative

(

f

,

x

)

print

(

f

"f({x}) = {f(x)}"

)

print

(

f

"f'({x}) ≈ {df_dx}"

)

print

(

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

)

print

(

f

"\nx increased from {x} to {x_new}"

)

print

(

f

"f(x) changed from {f(x)} to {f_new}"

)

print

(

f

"Actual increase: {f_new - f(x)}"

)

print

(

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

Chain rule calculation

print

(

f

"Chain rule calculation: dy/dx = {dy_dx_chain}"

)

Numerical derivative verification

def

numerical_derivative_y

(

x

,

h

=

1e-6

)

:

   

return

(

y

(

x + h

)

(

x

)

)

/ h

dy_dx_numerical

=

numerical_derivative_y

(

x

)

print

(

f

Numerical derivative verification: dy/dx ≈ {dy_dx_numerical}

)

Analytical solution: 6x^5 = 632 = 192

print

(

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

]

)

print

(

f

"Neural network output (logits): {logits}"

)

Convert to probabilities using Softmax

probabilities

=

softmax

(

logits

)

print

(

f

"Probability distribution: {probabilities}"

)

print

(

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

print

(

"\nCategory probabilities:"

)

print

(

f

" Cat: {probabilities[0]:.2%}"

)

print

(

f

" Dog: {probabilities[1]:.2%}"

)

print

(

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

]

)

print

(

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

print

(

f

"\nHidden layer linear transformation z1: {z1}"

)

Step 2: Hidden layer activation function

a1

=

relu

(

z1

)

print

(

f

"After hidden layer activation a1: {a1}"

)

Step 3: Output layer linear transformation

z2

=

W2

@

a1 + b2

print

(

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

print

(

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

print

(

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

print

(

f

"Combined into one layer calculation result: {z_combined}"

)

The results are exactly the same!

print

(

f

"\nTwo results are equal: {np.allclose(z2, z_combined)}"

)

print

(

"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:

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

exp

(

-x

)

)

def

sigmoid_derivative

(

x

)

:

   

"""The derivative of the sigmoid: σ'(x) = σ(x) * (1 - σ(x))"""

s

=

sigmoid

(

x

)

   

return

s *

(

1

)

Test some values

x_values

=

[

10

,

5

,

2

,

0

,

2

,

5

,

10

]

print

(

"x | sigmoid(x) | sigmoid'(x)"

)

print

(

"-"

40

)

for

x

in

x_values:

    s

=

sigmoid

(

x

)

d

=

sigmoid_derivative

(

x

)

   

print

(

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

print

(

f

"\nWhen x = {x_big}:"

)

print

(

f

" sigmoid(x) = {sigmoid(x_big):.10f} (almost 1)"

)

print

(

f

"sigmoid'(x) = {sigmoid_derivative(x_big):.10f} (almost 0)"

)

print

(

"Gradient has vanished! Gradients cannot propagate during backpropagation."

)

The problem with Sigmoid is very obvious:

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

tanh

(

np.

sqrt

(

2

/ np.

pi

)

(

x +

0.044715

power

(

x

,

3

)

)

)

)

   

return

x * cdf

Test

x_values

=

[

5

,

2

,

1

,

0

,

1

,

2

,

5

]

print

(

"x | ReLU | Leaky | GELU"

)

print

(

"-"

45

)

for

x

in

x_values:

    r

=

relu

(

x

)

lr

=

leaky_relu

(

x

)

g

=

gelu

(

x

)

   

print

(

f

"{x:4} | {r:4.2f} | {lr:5.2f} | {g:5.2f}"

)

Advantages of ReLU:

print

(

"\nAdvantages of ReLU:"

)

print

(

"1. Simple calculation: only max operation is needed"

)

print

(

"2. No saturation (positive range): gradient is always 1"

)

print

(

"3. Sparsity: Some neuron outputs are 0, increasing model robustness"

)

ReLU's problem: "Dying ReLU"

print

(

"The problem with ReLU: Dying ReLU"

)

print

(

"If a neuron's input is always negative, then:"

)

print

(

"- Output is always 0"

)

print

(

"- Gradient is always 0"

)

print

(

- The parameter will never update

)

print

(

- 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:

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

)

   

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

)

print

(

"Scenario 1: Model confidently predicts correctly"

)

print

(

f

" Probability distribution: {probs1[0]}"

)

print

(

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

)

print

(

"\nScenario 2: Model Uncertainty"

)

print

(

f

" Probability distribution: {probs2[0]}"

)

print

(

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

)

print

(

"\nScenario 3: Model prediction error"

)

print

(

f

" Probability distribution: {probs3[0]}"

)

print

(

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

)

print

(

"Scenario 1: Prediction Accuracy"

)

print

(

f

" Prediction: {pred1}"

)

print

(

f

" Real: {target}"

)

print

(

f

" MSE: {mse1:.2f}"

)

print

(

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

)

print

(

"\nScene 2: There is a large error"

)

print

(

f

" Predict: {pred2}"

)

print

(

f

"  Real: {target}"

)

print

(

f

"  MSE: {mse2:.2f} (magnified by large error)"

)

print

(

f

" MAE: {mae2:.2f}"

)

MSE vs MAE

print

(

"MSE vs MAE:"

)

print

(

"- MSE is more sensitive to large errors (because of squaring)"

)

print

(

"- MAE is more robust to outliers"

)

print

(

"- 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

)

print

(

f

"Language model loss: {loss:.4f}"

)

print

(

"\nMeaning of this loss:"

)

print

(

"- for each position in the sequence"

)

print

(

"- predict the next word"

)

print

(

"- 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

)

print

(

f

"Initial parameters: w = {w}, b = {b}"

)

print

(

f

"Target: {target}"

)

============================================

Step 1: Forward Propagation

============================================

y

=

w * x + b

loss

=

(

y - target

)

**

2

print

(

f

"Forward propagation:"

)

print

(

f

" y = {y}"

)

print

(

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

print

(

f

"\nBackpropagation:"

)

print

(

f

" d_loss/d_y = {d_loss_d_y}"

)

print

(

f

" d_loss/d_w = {d_loss_d_w}"

)

print

(

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

print

(

f

"\nParameter update:"

)

print

(

f

" w: {w} -> {w_new}"

)

print

(

f

" b: {b} -> {b_new}"

)

Verification: forward propagation with new parameters

y_new

=

w_new * x + b_new

loss_new

=

(

y_new - target

)

**

2

print

(

f

"Verification:"

)

print

(

f

" Old prediction: {y}, Old loss: {loss}"

)

print

(

f

" New prediction: {y_new}, New loss: {loss_new}"

)

print

(

f

" Loss decreased!"

)

Although this example is simple, it contains all the core ideas of backpropagation:

  1. Forward propagation: calculating all intermediate variables
  2. Backpropagation: calculating gradients layer by layer starting from the output using the chain rule
  3. 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,)

print

(

"Initial parameters have been set"

)

============================================

Forward propagation

============================================

print

(

"\n=== Forward Propagation ===\n"

)

First layer

z1

=

W1

@

x + b1

(3,)

a1

=

relu

(

z1

)

   

(3,)

print

(

f

"z1 = {z1}"

)

print

(

f

"a1 = {a1}"

)

Second layer

z2

=

W2

@

a1 + b2

(1,)

a2

=

z2

Regression task, no activation function in the output layer

print

(

f

"z2 = {z2}"

)

print

(

f

"a2 = {a2}"

)

Loss

loss

=

np.

mean

(

(

a2 - target

)

**

2

)

print

(

f

"loss = {loss}"

)

============================================

Backpropagation

============================================

print

(

"=== 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,)

print

(

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,)

print

(

f

"d_loss_d_W2 = {d_loss_d_W2}"

)

print

(

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,)

print

(

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,)

print

(

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,)

print

(

f

"d_loss_d_W1 = {d_loss_d_W1}"

)

print

(

f

"d_loss_d_b1 = {d_loss_d_b1}"

)

============================================

Parameter Update

============================================

print

(

"\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

print

(

"Parameters updated"

)

This example demonstrates the complete process of backpropagation.

The core rules are:

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

SGD optimization

x

=

10.0

 

Initial value

learning_rate

=

0.1

 

Learning rate

steps

=

20

print

(

f

"Initial x = {x}, f(x) = {f(x)}"

)

print

(

"-"

40

)

for

step

in

range

(

steps

)

:

    grad

=

f_grad

(

x

)

    x

=

x - learning_rate * grad

SGD update

   

print

(

f

"Step {step+1}: x = {x:.6f}, f(x) = {f(x):.6f}"

)

print

(

"-"

40

)

print

(

f

"Final x = {x:.6f}, f(x) = {f(x):.6f}"

)

print

(

"Theoretically optimal: x = 0, f(x) = 0"

)

SGD is simple but has drawbacks:

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

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

)

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

)

print

(

"Step | SGD | Momentum"

)

print

(

"-"

35

)

for

i

in

range

(

steps +

1

)

:

   

print

(

f

"{i:4} | {sgd_history[i]:9.6f} | {momentum_history[i]:9.6f}"

)

print

(

"\nObservation: Momentum converges faster!"

)

print

(

"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

The gradient of f(x) = x²

       

Update first and second moments

m

=

beta1 * m +

(

1

)

v

=

beta2 * v +

(

1

)

(

grad **

2

)

       

Bias correction

m_hat

=

m /

(

1

)

v_hat

=

v /

(

1

)

       

Parameter update

x

=

x - learning_rate * m_hat /

(

np.

sqrt

(

v_hat

)

)

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

)

print

(

"Adam optimization process:"

)

print

(

"Step | x | f(x)"

)

print

(

"-"

35

)

for

i

in

range

(

steps +

1

)

:

   

print

(

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

sum

(

weights **

2

)

grad

=

lambda_l2 * weights

   

return

reg

,

grad

Example

weights

=

np.

array

(

[

1.0

,

2.0

,

3.0

,

0.5

]

)

print

(

f

"weights: {weights}"

)

lambda_l1

=

0.1

lambda_l2

=

0.1

l1_reg

,

l1_grad

=

l1_regularization

(

weights

,

lambda_l1

)

print

(

f

"\nL1 Regularization term: {l1_reg:.4f}"

)

print

(

f

"L1 gradient: {l1_grad}"

)

l2_reg

,

l2_grad

=

l2_regularization

(

weights

,

lambda_l2

)

print

(

f

"\nL2 regularization term: {l2_reg:.4f}"

)

print

(

f

"L2 gradient: {l2_grad}"

)

print

(

"\nL1 vs L2:"

)

print

(

"- L1: tends to produce sparse solutions (many parameters become 0), can be used for feature selection"

)

print

(

"- L2: tends to keep all parameters small, but not 0"

)

print

(

"- 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

)

   

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

print

(

f

"Enter x: {x}"

)

print

(

f

"Dropout Rate: {dropout_rate}"

)

Run multiple times and observe randomness

print

(

"\nMultiple Dropout results:"

)

for

i

in

range

(

3

)

:

out

,

mask

=

dropout_forward

(

x

,

dropout_rate

,

training

=

True

)

   

print

(

f

" Iteration {i+1}: mask={mask}, out={out}"

)

Test mode

out_test

=

dropout_forward

(

x

,

dropout_rate

,

training

=

False

)

print

(

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

)

running_var

[

:

]

=

momentum * running_var +

(

1

)

       

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

]

,

]

)

print

(

f

"Input x:\n{x}"

)

Initial parameters

gamma

=

np.

ones

(

features

)

 

Initial no scaling

beta

=

np.

zeros

(

features

)

 

Initial no offset

print

(

f

"\ngamma: {gamma}"

)

print

(

f

"beta: {beta}"

)

Apply batch normalization

out

=

batch_norm

(

x

,

gamma

,

beta

,

training

=

True

)

print

(

f

"\nAfter batch normalization:\n{out}"

)

Verification: The mean of each feature should be close to 0, and the variance close to 1

print

(

f

"\nMean after normalization: {np.mean(out, axis=0)}"

)

print

(

f

"Normalized variance: {np.var(out, axis=0)}"

)

Advantages of batch normalization:

Disadvantages of Batch Normalization:

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

]

]

,

]

)

print

(

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

)

print

(

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

)

print

(

f

"\nMean of each position:\n{mean_check}"

)

print

(

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

cos

(

np.

pi

)

)

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

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

print

(

"Different learning rate schedules:"

)

print

(

"Step | Warmup | Cosine | Warmup+Cosine"

)

print

(

"-"

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

)

   

print

(

f

"{step:4} | {lr_warmup:.6f} | {lr_cosine:.6f} | {lr_combined:.6f}"

)

Effect of learning rate on training

Effect of learning rate:

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

)

print

(

f

"Training set size: {len(train_dataset)}"

)

print

(

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

)

print

(

"\nModel structure:"

)

print

(

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

)

warmup_steps

=

len

(

train_loader

)

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

cos

(

np.

pi

)

)

scheduler

=

optim.

lr_scheduler

.

LambdaLR

(

optimizer

,

lr_lambda

=

lr_lambda

)

print

(

"\nTraining configuration:"

)

print

(

f

" Epochs: {total_epochs}"

)

print

(

f

" Warmup epochs: {warmup_epochs}"

)

print

(

f

" Total steps: {total_steps}"

)

print

(

f

" Warmup steps: {warmup_steps}"

)

============================================

4. Training Loop

============================================

print

(

"\nStarting training..."

)

print

(

"-"

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'

]

   

print

(

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}"

)

print

(

"-"

50

)

print

(

f

"Training complete! Best validation accuracy: {best_val_acc:.4f}"

)

============================================

5. Inference Examples

============================================

print

(

"\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

(

)

   

print

(

f

" Sample {i+1}: {sample[:5]}..."

)

   

print

(

f

" Predicted class: {predicted_class}"

)

   

print

(

f

"    Probability: Class 0={probs[0,0]:.4f}, Class 1={probs[0,1]:.4f}"

)

This example includes all standard components of deep learning training:

This process can be directly generalized to more complex tasks and models.