AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⌬Neural Networks
  1. Neurons and Activation Functions
  2. Multilayer Perceptrons and Backpropagation
  3. Training Hyperparameters: Epochs, Learning Rate, Batch Size and More
  4. Optimizers: SGD, Momentum, RMSProp, Adam/AdamW and LR Schedules
  5. Regularization, Normalization and Initialization
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Neural Networks

Multilayer Perceptrons and Backpropagation

Stack neurons into layers, run a forward pass, measure the loss, then use the chain rule to send blame backwards to every weight. The algorithm behind all neural network training.

Intermediate~25 min·6 references
Key terms
MLP (Multilayer Perceptron)BackpropagationNeuron (artificial)Activation functionLoss functionGradientSGD (Stochastic Gradient Descent)Weight initialization

A single neuron draws one straight boundary. A multilayer perceptron (MLP (Multilayer Perceptron)) stacks many neurons in layers so each layer transforms the output of the previous one. MLPs are the simplest “deep” networks — and they are still everywhere: the feed-forward blocks inside every Transformer are MLPs. Training them relies on one algorithm, Backpropagation, which efficiently computes the Gradient of the loss with respect to millions or billions of weights[1].

≈
Backprop is blame assignment in a factory
A product comes off an assembly line slightly wrong. The final inspector measures how wrong (the loss). She tells the last station how much its adjustment contributed; that station passes the remaining blame to the stations that fed it, in proportion to how much each one influenced it. Every station ends up knowing exactly which way to turn its knobs — and the blame only had to travel backwards once.

Layers and the forward pass

h = f(W₁x + b₁) ŷ = g(W₂h + b₂) L = loss(ŷ, y)
A 1-hidden-layer MLP. W₁ has shape (hidden × inputs); f is the hidden activation (e.g. ReLU); g is the output activation (identity, sigmoid or softmax).
In words: Read it left to right as a pipeline: “the hidden layer h is an activation of a weighted sum of the inputs; the prediction ŷ is an output activation of a weighted sum of h; the loss L compares ŷ with the true answer y.” Each step is the single-neuron formula done for a whole layer at once, using a matrix instead of one weight vector.
Symbols(hover a symbol in the formula)
x
input vector: the features of one example
W₁
hidden-layer weight Matrix, shape (hidden × inputs); row k holds the weights of hidden unit k
b₁
hidden-layer bias vector, one number per hidden unit
f
hidden Activation function, applied element-wise — usually ReLU
h
hidden activations: the new, learned representation of x
W₂
output weight matrix, shape (outputs × hidden)
b₂
output bias vector
g
output activation: identity for Regression, Sigmoid (logistic function) for yes/no, Softmax for several classes
ŷ
“y-hat”: the model's prediction
y
the true target (Label (target))
L
the loss: one number saying how wrong this prediction is
loss
the chosen Loss function, e.g. Mean squared error (MSE) or Cross-entropy (log loss)
▸Worked example
2 inputs → 2 hidden (ReLU) → 1 output (sigmoid), target y = 1 x = (1, 2) W₁ = [[0.5, −0.5], [1, 0.25]] b₁ = (0, −1) Hidden: W₁x + b₁ = (0.5·1 − 0.5·2 + 0, 1·1 + 0.25·2 − 1) = (−0.5, 0.5) h = ReLU(−0.5, 0.5) = (0, 0.5) ← unit 1 is switched off Output: W₂ = [1, 2], b₂ = 0.5 → W₂h + b₂ = 1·0 + 2·0.5 + 0.5 = 1.5 ŷ = σ(1.5) ≈ 0.818 Loss (binary cross-entropy, y = 1): L = −ln 0.818 ≈ 0.201 The layer-wise backprop card below continues with exactly these numbers.

Each layer is “fully connected”: every neuron sees every output of the previous layer. Count the parameters to get a feel for size: a network 2 → 8 → 8 → 1 has (2·8 + 8) + (8·8 + 8) + (8·1 + 1) = 24 + 72 + 9 = 105 parameters. An MLP on 28×28 images with a 512-unit hidden layer already has 784·512 + 512 ≈ 402 k parameters in its first layer alone. The forward pass runs data through the layers to a prediction; the Loss function (e.g. Mean squared error (MSE) or Cross-entropy (log loss)) turns the error into one number.

Backpropagation = the chain rule, organised

∂L/∂w = ∂L/∂ŷ · ∂ŷ/∂z · ∂z/∂w
The chain rule: how the loss changes with a weight = product of local derivatives along the path from w to L.
In words: “the effect of w on the loss = (effect of ŷ on the loss) × (effect of z on ŷ) × (effect of w on z).” A small change in w ripples forward through z and ŷ to L; the chain rule says the total sensitivity is the product of the sensitivities of each link. Backpropagation evaluates these factors starting at the loss and working backwards.
Symbols(hover a symbol in the formula)
∂L/∂w
what we want: the Gradient of the loss with respect to weight w — how much L changes per tiny change of w
∂L/∂ŷ
how the loss reacts to the prediction (for L = (ŷ − y)² it is 2(ŷ − y))
∂ŷ/∂z
slope of the activation at z (for Sigmoid (logistic function): ŷ(1 − ŷ), at most 0.25)
∂z/∂w
how z reacts to w; since z = w·x + b this is simply the input x
∂
“partial” Derivative: change one variable, hold all others fixed
·
ordinary multiplication of the local slopes
▸Worked example
One sigmoid neuron: x = 2, w = 0.5, b = 0, target y = 0, loss L = (ŷ − y)² Forward: z = 0.5·2 = 1 → ŷ = σ(1) ≈ 0.731 → L = 0.731² ≈ 0.534 ∂L/∂ŷ = 2(ŷ − y) = 2·0.731 ≈ 1.462 ∂ŷ/∂z = ŷ(1 − ŷ) = 0.731·0.269 ≈ 0.1966 ∂z/∂w = x = 2 ∂L/∂w = 1.462 · 0.1966 · 2 ≈ 0.575 (positive → lowering w lowers the loss) Update, η = 0.5: w ← 0.5 − 0.5·0.575 ≈ 0.213 Check: z = 0.425 → ŷ ≈ 0.605 → L ≈ 0.366 (was 0.534)

Rumelhart, Hinton and Williams (1986) showed that applying this systematically — computing gradients layer by layer from the output back to the input, reusing intermediate results — lets multilayer networks learn useful internal representations[2]. The key trick is reuse: the gradient for layer l is built from the gradient already computed for layer l+1, so one backward pass costs only about as much as one or two forward passes, no matter how many weights there are.

Worked example: one neuron, one step

  1. Setup: input x = 1.5, weight w = 0.8, bias b = 0.1, target y = 1, sigmoid activation, loss L = ½(ŷ − y)².
  2. Forward: z = 0.8·1.5 + 0.1 = 1.3 → ŷ = σ(1.3) ≈ 0.786 → L = ½(0.786 − 1)² ≈ 0.0229.
  3. Local derivatives: ∂L/∂ŷ = ŷ − y ≈ −0.214; ∂ŷ/∂z = ŷ(1 − ŷ) ≈ 0.168; ∂z/∂w = x = 1.5; ∂z/∂b = 1.
  4. Chain them: ∂L/∂w ≈ −0.214 · 0.168 · 1.5 ≈ −0.054 and ∂L/∂b ≈ −0.036. Negative means “increasing w lowers the loss”.
  5. Update with learning rate η = 0.5: w ← 0.8 − 0.5·(−0.054) ≈ 0.827, b ← 0.1 − 0.5·(−0.036) ≈ 0.118. The new prediction σ(0.827·1.5 + 0.118) ≈ 0.796 is closer to 1.

The same thing for whole layers

δ_L = ∂L/∂ŷ ⊙ g′(z_L) δ_l = (W_{l+1}ᵀ δ_{l+1}) ⊙ f′(z_l) ∂L/∂W_l = δ_l · a_{l−1}ᵀ ∂L/∂b_l = δ_l
δ_l is the “error signal” at layer l; ⊙ is element-wise multiplication; a_{l−1} is the previous layer's activation. Notice f′ appears at every layer — the root of vanishing gradients.
In words: Four recipes. (1) The error signal at the output layer = how the loss reacts to the prediction × the slope of the output activation. (2) The error at any earlier layer = the next layer's error sent backwards through its weights (Wᵀ) × the slope of this layer's activation. (3) A weight's gradient = its layer's error × the input that weight saw. (4) A bias's gradient = the error itself. Careful: in δ_L the subscript L means “last layer”, while in ∂L it means the loss.
Symbols(hover a symbol in the formula)
δ_L
delta at the last (output) layer: the error signal, one number per output unit
δ_l
delta at layer l = ∂L/∂z_l: how much the loss would change if that layer's pre-activations changed
δ_{l+1}
error signal of the next layer — already computed, which is the reuse trick of backprop
∂L/∂ŷ
derivative of the loss with respect to the prediction
⊙
element-wise (Hadamard) product: multiply matching entries, e.g. (1, 2) ⊙ (3, 4) = (3, 8)
g′
derivative (slope) of the output activation g
z_L
pre-activations of the output layer
W_{l+1}
weight matrix of the next layer (the one that consumed this layer's output)
ᵀ
transpose: swap rows and columns; Wᵀ sends the error backwards along the same connections
f′
derivative of the hidden activation f (for ReLU: 1 if z > 0, else 0)
z_l
pre-activations of layer l
∂L/∂W_l
gradient for the weight matrix of layer l — same shape as W_l
a_{l−1}
activations entering layer l (previous layer's output; for the first layer, the input x)
∂L/∂b_l
gradient for the bias vector of layer l
·
here an outer product: column δ_l times row a_{l−1}ᵀ gives a whole matrix
▸Worked example
Same network as the forward-pass card: x = (1, 2), z₁ = (−0.5, 0.5), h = (0, 0.5), W₂ = [1, 2], ŷ = 0.818, y = 1, binary cross-entropy Layers: l = 1 hidden, l = 2 output (= L); a₀ = x, a₁ = h Output: ∂L/∂ŷ = −1/ŷ ≈ −1.223, g′ = ŷ(1 − ŷ) ≈ 0.149 δ₂ = −1.223 · 0.149 ≈ −0.182 (sigmoid + cross-entropy always simplifies to ŷ − y) ∂L/∂W₂ = δ₂ · hᵀ = −0.182 · (0, 0.5) = (0, −0.091) ∂L/∂b₂ = −0.182 Hidden: W₂ᵀ δ₂ = (1·(−0.182), 2·(−0.182)) = (−0.182, −0.365) f′(z₁) = ReLU′(−0.5, 0.5) = (0, 1) δ₁ = (−0.182, −0.365) ⊙ (0, 1) = (0, −0.365) ∂L/∂W₁ = δ₁ · xᵀ = [[0, 0], [−0.365, −0.730]] ∂L/∂b₁ = (0, −0.365) The switched-off ReLU unit gets exactly zero gradient — this is how a “dead ReLU” stops learning.

Two practical consequences. Memory: the backward pass needs the activations a_{l−1} saved from the forward pass, so training uses much more memory than inference[6]. Autodiff: you never write these formulas by hand — frameworks like PyTorch record the operations in the forward pass and run reverse-mode automatic differentiation when you call loss.backward()[4]. Karpathy's tiny “micrograd” engine implements this in about 100 lines and is a great way to see it work[5].

Why hidden layers help

XOR is the classic example: the points (0,0) and (1,1) are class 0, (0,1) and (1,0) are class 1. No line separates them. With one hidden layer of just two units, the network first maps the inputs into a new space (roughly “x₁ OR x₂” and “x₁ AND x₂”) where the classes are linearly separable, and the output neuron draws a line there. Deeper layers repeat this trick: each layer builds features out of the previous layer's features, which is how networks learn spirals, faces or grammar[3].

Loading interactive…
A real MLP trained in your browser. Background colour = the network's prediction; the diagram shows weights (colour = sign, thickness = size).
  1. XOR needs a hidden layer: choose XOR with 0 hidden layers and press play — the boundary stays a straight line and loss plateaus. Add 1 hidden layer with 4 neurons: the boundary bends into two regions and XOR gets solved.
  2. Spiral needs capacity: try spiral with 1 layer × 2 neurons (fails), then 3 layers × 8 neurons (succeeds, slowly). Watch the boundary bend more as depth grows.
  3. Learning rate: on circle, set a very high learning rate — the loss chart jumps around or explodes. Set it very low — the boundary barely moves. Find the largest value that still decreases smoothly.
  4. Overfitting: raise the noise and use many neurons. Training loss keeps falling while test loss stops improving or rises. Add L2 regularization and watch the boundary become smoother.
  5. Activation matters: on spiral with 3 hidden layers, compare sigmoid with ReLU or tanh. Sigmoid typically learns much more slowly — vanishing gradients in action.
  6. One step at a time: pause and use “step” to apply single updates; notice how the edges' thickness changes slightly after every step.
knobNumber of hidden layers (depth)
What it is
How many hidden layers sit between input and output.
↑ If you increase it
The network can compose more levels of features and fit more complex shapes with fewer total units. Training becomes harder (vanishing/exploding gradients, more tuning) and each step is slower; beyond a few layers, plain MLPs usually need normalization or residual connections.
↓ If you decrease it
Simpler, faster, easier to train, but may underfit: with 0 hidden layers the model is just linear/logistic regression.
Typical values
1–3 for tabular data; much deeper only with residual connections.
knobNeurons per layer (width)
What it is
The number of units in each hidden layer — the size of each intermediate representation.
↑ If you increase it
More capacity and usually smoother, faster optimisation. Parameter count grows roughly with width², so memory and compute rise; on small datasets, risk of Overfitting grows.
↓ If you decrease it
Fewer parameters and less overfitting, but too narrow a layer becomes a bottleneck that cannot represent the needed features (underfitting).
Typical values
32–512 for tabular MLPs; often powers of 2 for hardware efficiency.
python
import torch
import torch.nn as nn

torch.manual_seed(0)
X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y = torch.tensor([[0.], [1.], [1.], [0.]])          # XOR

model = nn.Sequential(
    nn.Linear(2, 8), nn.Tanh(),                      # hidden layer
    nn.Linear(8, 1),                                 # output logit (no sigmoid here)
)
loss_fn = nn.BCEWithLogitsLoss()                     # applies sigmoid internally, stably
opt = torch.optim.SGD(model.parameters(), lr=0.5)

for step in range(2000):
    logits = model(X)              # 1) forward pass
    loss = loss_fn(logits, y)      # 2) scalar loss
    opt.zero_grad()                # 3) clear gradients from the previous step
    loss.backward()                # 4) backprop: fills p.grad for every parameter
    opt.step()                     # 5) w <- w - lr * grad

with torch.no_grad():
    print(torch.sigmoid(model(X)).round().flatten())  # expected: tensor([0., 1., 1., 0.])
The five-line training loop you will see in every PyTorch project. Gradients come from autograd[4].
!
Common pitfalls
Watch out for these:
  • Forgetting `zero_grad()`: PyTorch accumulates gradients, so each step adds to the last — updates become huge and erratic.
  • Initialising all weights to the same value (e.g. zero): every hidden unit computes the same thing and gets the same gradient, so they stay identical forever (the symmetry problem). Use random Weight initialization.
  • Shape bugs: a target of shape (N,) vs predictions of shape (N, 1) can silently broadcast to an (N, N) loss. Check shapes.
  • Unscaled inputs: features in the thousands next to features near 0 make optimisation slow — standardise inputs (Feature scaling (normalisation / standardisation)).
▸Go deeper: gradient checking and a short history
∂L/∂w ≈ (L(w + ε) − L(w − ε)) / (2ε), ε ≈ 10⁻⁵
Centred finite differences: a slow but reliable way to verify a hand-written backward pass.
In words: “to estimate the slope at w, nudge w a tiny bit up and a tiny bit down, see how much the loss changes, and divide by the distance 2ε between the two probes.” It needs no calculus — only two extra forward passes per parameter — so it is used to check that backprop's gradients are right, never to train (far too slow for millions of weights).
Symbols(hover a symbol in the formula)
∂L/∂w
the true Gradient for one parameter w — what your backprop code should return
≈
approximately equal
L(w + ε)
loss after nudging w up by ε (all other parameters unchanged)
L(w − ε)
loss after nudging w down by ε
2ε
total distance between the two probe points
ε
epsilon — a tiny step; too large → approximation error, too small → floating-point rounding error
10⁻⁵
0.00001 — a common choice when computing in float64
▸Worked example
Toy loss L(w) = w³ at w = 2; the exact slope is 3w² = 12 ε = 0.01: L(2.01) = 8.120601, L(1.99) = 7.880599 (8.120601 − 7.880599) / 0.02 = 12.0001 (error ≈ ε² = 0.0001) ε = 0.1: (9.261 − 6.859) / 0.2 = 12.01 (worse: ε too big) Compare with backprop using relative error |a − b| / max(|a|, |b|): backprop 12 vs numeric 12.0001 → ≈ 8·10⁻⁶, tiny ✓ (shrinks further with smaller ε) buggy backprop 11.4 vs 12 → 0.05, a real bug ✗

If you implement backprop yourself, compare it against finite differences on a few weights; the relative error should be around 10⁻⁷ or smaller in float64[3]. Historically, reverse-mode differentiation was described by Linnainmaa (1970) and applied to neural networks by Werbos (1974); the 1986 Nature paper by Rumelhart, Hinton and Williams made it widely known and showed hidden units learning meaningful features[2].

Quiz

1.
Why is backpropagation efficient compared with computing each weight's gradient separately?
2.
All weights of an MLP are initialised to 0.5. What happens during training?
3.
How many parameters does a 3 → 4 → 2 MLP (with biases) have?
4.
You forget to call optimizer.zero_grad() in your loop. What do you expect?
5.
Why does training a network need much more memory than running inference with it?
Score: 0/5

References

  1. [1]
    Deep Learning — Chapter 6: Deep Feedforward Networks (6.5 Back-Propagation)
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  2. [2]
    Learning representations by back-propagating errors
    PaperRumelhart, Hinton & Williams1986nature.com
  3. [3]
    CS231n: Backpropagation, Intuitions
    CourseStanford CS231ncs231n.github.io
  4. [4]
    Automatic Differentiation with torch.autograd
    DocsPyTorch Tutorialsdocs.pytorch.org
  5. [5]
    micrograd: a tiny scalar-valued autograd engine
    ArticleKarpathy2020github.com
  6. [6]
    Dive into Deep Learning — Forward Propagation, Backward Propagation, and Computational Graphs
    BookZhang, Lipton, Li & Smolad2l.ai
← Previous
Neurons and Activation Functions
Next →
Training Hyperparameters: Epochs, Learning Rate, Batch Size and More