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.
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].
Layers and the forward pass
- 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
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
- 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
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
- Setup: input x = 1.5, weight w = 0.8, bias b = 0.1, target y = 1, sigmoid activation, loss L = ½(ŷ − y)².
- Forward: z = 0.8·1.5 + 0.1 = 1.3 → ŷ = σ(1.3) ≈ 0.786 → L = ½(0.786 − 1)² ≈ 0.0229.
- Local derivatives: ∂L/∂ŷ = ŷ − y ≈ −0.214; ∂ŷ/∂z = ŷ(1 − ŷ) ≈ 0.168; ∂z/∂w = x = 1.5; ∂z/∂b = 1.
- Chain them: ∂L/∂w ≈ −0.214 · 0.168 · 1.5 ≈ −0.054 and ∂L/∂b ≈ −0.036. Negative means “increasing w lowers the loss”.
- 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
- 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
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].
- 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.
- 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.
- 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.
- 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.
- Activation matters: on spiral with 3 hidden layers, compare sigmoid with ReLU or tanh. Sigmoid typically learns much more slowly — vanishing gradients in action.
- One step at a time: pause and use “step” to apply single updates; notice how the edges' thickness changes slightly after every step.
- 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.
- 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.
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.])- 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
- 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
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
optimizer.zero_grad() in your loop. What do you expect?References
- [1]Deep Learning — Chapter 6: Deep Feedforward Networks (6.5 Back-Propagation)BookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [2]Learning representations by back-propagating errorsPaperRumelhart, Hinton & Williams1986nature.com
- [3]CS231n: Backpropagation, IntuitionsCourseStanford CS231ncs231n.github.io
- [4]Automatic Differentiation with torch.autogradDocsPyTorch Tutorialsdocs.pytorch.org
- [5]micrograd: a tiny scalar-valued autograd engineArticleKarpathy2020github.com
- [6]Dive into Deep Learning — Forward Propagation, Backward Propagation, and Computational GraphsBookZhang, Lipton, Li & Smolad2l.ai