Deep Learning
Neural Networks and Backpropagation: Perceptrons, MLPs, Activation Functions and Gradients
Intermediate 35 min For: Beginners / Developers / Researchers
Key takeaways
- ▸A neuron computes a weighted sum plus a bias and passes it through a non-linear activation: a = f(w·x + b). Arranging neurons in layers that feed into one another gives a multilayer perceptron (MLP); the feed-forward network inside every Transformer layer has the same structure.
- ▸Non-linear activations are essential: without them, stacked linear layers multiply out to a single linear map and depth adds nothing. A single-layer perceptron cannot represent XOR; one hidden layer with a non-linear activation solves it.
- ▸Backpropagation is the systematic application of the chain rule to a computational graph. The forward pass stores intermediate results; the backward pass starts from the loss and computes, layer by layer, the gradient of the loss with respect to each layer's output. One backward pass yields the gradients of all parameters at a cost of the same order as the forward pass (Kaplan et al. estimate about twice the forward compute).
- ▸Whether gradients reach early layers depends on the product of per-layer derivatives: the sigmoid's derivative is at most 0.25, so gradients shrink quickly with depth. ReLU-type activations, width-scaled initialisation (Glorot and Bengio, 2010; He et al., 2015), residual connections and normalisation together make deep networks trainable.
- ▸After writing backpropagation by hand, check the gradients: approximate them numerically with central differences and compare the relative error with the analytic gradients. In this lesson's example the maximum relative error is about 1.6×10⁻⁹, and the hand-written gradients also match PyTorch autograd.
Summary: A neural network is made of many simple units, each computing a weighted sum followed by a non-linear transformation. Training uses backpropagation to compute the gradient of the loss with respect to every parameter in one pass, then updates the parameters by gradient descent. This lesson moves from the perceptron to multilayer perceptrons and activation functions, forward propagation, backpropagation, gradient checking, and initialisation and vanishing gradients, and closes by mapping these parts onto large models. Every number quoted comes from the runnable examples at the end.
This lesson belongs to the Neural Networks & Backpropagation unit. The prerequisites are PyTorch and Autograd and Overfitting, Generalisation and Data Splits; the backpropagation section uses the chain rule from Calculus and Optimization. Continue with Tokens and Embeddings and Transformers and Attention. Related algorithm cards: perceptron, backpropagation, GELU, autoencoder, SGD and ResNet.
Neurons and the perceptron
An artificial neuron performs two steps on an input vector x:
z = w · x + b = w₁x₁ + w₂x₂ + … + wₙxₙ + b weighted sum plus bias
a = f(z) activation function f
The weights w and bias b are the parameters to be learned. The perceptron proposed by Rosenblatt (1958) uses a step function for f (output 1 if z > 0, otherwise 0) and adjusts its connection weights in an error-driven way. Modern textbooks usually write the perceptron learning rule as follows: for each misclassified sample, move w in the direction that reduces the error, w ← w + (y − ŷ)·x and b ← b + (y − ŷ).
A single perceptron's decision boundary w·x + b = 0 is a hyperplane, so it can only separate linearly separable data. The classic counterexample is XOR: inputs (0,0) and (1,1) map to 0, (0,1) and (1,0) map to 1, and no straight line in the plane separates the two classes. Minsky and Papert analysed this kind of limitation of single-layer perceptrons systematically in their 1969 book Perceptrons. In this lesson's example, 100 epochs of the rule above on XOR leave the accuracy at 0.5. The remedy is a hidden layer between input and output.
Multilayer perceptrons and activation functions
Arranging neurons in layers, each reading all outputs of the previous layer, gives a multilayer perceptron (MLP), also called a feed-forward or fully connected network. A two-layer network (one hidden layer) computes:
h = f(x · W₁ + b₁) hidden layer; W₁ has shape (input dim, hidden dim)
ŷ = h · W₂ + b₂ output layer (followed by softmax for classification)
flowchart LR
subgraph IN["Input layer"]
x1((x1)); x2((x2)); x3((x3))
end
subgraph H1["Hidden layer 1"]
h1((h)); h2((h)); h3((h)); h4((h))
end
subgraph H2["Hidden layer 2"]
g1((h)); g2((h)); g3((h))
end
subgraph OUT["Output layer"]
y(("ŷ"))
end
x1 --> h1 & h2 & h3 & h4
x2 --> h1 & h2 & h3 & h4
x3 --> h1 & h2 & h3 & h4
h1 & h2 & h3 & h4 --> g1 & g2 & g3
g1 & g2 & g3 --> yThe activation must be non-linear. If f is the identity, a two-layer network computes x·W₁·W₂, and W₁·W₂ is just another matrix, so any number of stacked layers is equivalent to one linear map. The example verifies this directly with random matrices. Common activations:
| Activation | Definition | Derivative | Typical use |
|---|---|---|---|
| sigmoid | σ(z) = 1 / (1 + e⁻ᶻ) | At most 0.25 (at z = 0); tends to 0 for large absolute z | Binary-classification outputs, gates |
| tanh | (eᶻ − e⁻ᶻ) / (eᶻ + e⁻ᶻ) | At most 1; tends to 0 for large absolute z | Early networks and RNNs |
| ReLU | max(0, z) | 1 for z > 0, 0 for z < 0 | Default for CNNs and MLPs (Nair and Hinton, 2010) |
| GELU | z · Φ(z), Φ the standard normal CDF | Smooth, slightly negative for negative z | Transformers such as BERT and the GPT series (Hendrycks and Gimpel, 2016) |
| SwiGLU | (Swish(xW) ⊙ xV) · W₂ | Gated; needs three weight matrices | Feed-forward layers of LLaMA and other models (Shazeer, 2020) |
In the AlexNet paper, Krizhevsky et al. (2012) reported that deep convolutional networks with ReLUs train several times faster than their tanh equivalents. In the example, PyTorch's GELU at x = −3, −1, 1 and 3 gives −0.0041, −0.1587, 0.8413 and 2.9959, matching x·Φ(x) computed from the definition to float32 precision (differences of at most 1×10⁻⁴).
Expressive power. The universal approximation theorems of Cybenko (1989) and Hornik, Stinchcombe and White (1989) show that a single hidden layer with enough units can approximate any continuous function on a compact set to arbitrary accuracy. The theorems only guarantee existence: they do not say how many units are needed or whether training will find the solution. Deep networks compose features layer by layer and can usually represent equally complex functions with far fewer parameters.
Forward propagation and the loss
For K-class classification, the forward pass computes in turn:
z₁ = x · W₁ + b₁
h = ReLU(z₁)
z₂ = h · W₂ + b₂ logits
p = softmax(z₂) class probabilities
L = −log p[y] cross-entropy loss (averaged over a batch)
The relation between cross-entropy and maximum likelihood is covered in Probability, Statistics and Information Theory. Intermediate results such as z₁ and h are stored during the forward pass because backpropagation needs them.
Backpropagation
Training needs the gradient of the loss L with respect to every parameter. Backpropagation starts at the output and applies the chain rule backwards through the computational graph: each node only needs the gradient of the loss with respect to its output to compute the gradients with respect to its inputs and parameters, and it passes the former on to the previous layer. For the two-layer network above (batch size n, Y the one-hot label matrix):
∂L/∂z₂ = (p − Y) / n compact form of softmax combined with cross-entropy
∂L/∂W₂ = hᵀ · ∂L/∂z₂ ∂L/∂b₂ = row-wise sum of ∂L/∂z₂
∂L/∂h = ∂L/∂z₂ · W₂ᵀ
∂L/∂z₁ = ∂L/∂h ⊙ 1[z₁ > 0] ReLU derivative: 1 where z₁ > 0, else 0
∂L/∂W₁ = xᵀ · ∂L/∂z₁ ∂L/∂b₁ = row-wise sum of ∂L/∂z₁
The pattern: weight gradient = transpose of the layer input × gradient of the layer output; gradient passed back = gradient of the layer output × transpose of the weights; an element-wise activation multiplies by its derivative.
flowchart LR I["input x"] -->|"forward"| L1["z₁ → h"] -->|"forward"| L2["z₂ → p"] --> O["loss L"] O -.->|"∂L/∂z₂"| L2 -.->|"∂L/∂h"| L1
Rumelhart, Hinton and Williams (1986) showed in Nature that networks trained this way develop hidden units that represent task-relevant features, which made backpropagation widely known in neural-network research. From the automatic-differentiation point of view it is a special case of reverse-mode automatic differentiation; the survey by Baydin et al. (2015) notes that Linnainmaa (1970) is often cited as the first published description of reverse mode. The advantage of reverse mode is that one backward pass gives the gradient of a scalar loss with respect to all parameters, however many there are, at a constant multiple of the forward cost. When Kaplan et al. (2020) estimate Transformer training compute, they count the backward pass as about twice the forward pass, giving roughly 6N floating-point operations per training token (N being the number of non-embedding parameters).
The price is memory: computing ∂L/∂W₁ needs the forward-pass input x, and the ReLU derivative needs z₁, so every layer's activations are kept until the backward pass finishes. The PyTorch Autograd mechanics notes explain how the framework records the graph during the forward pass and saves the tensors it needs.
Gradient checking
Hand-written backpropagation is error-prone, so the standard check is to compare it with numerical gradients:
Numerical gradient ∂L/∂θ ≈ (L(θ + ε) − L(θ − ε)) / (2ε) central difference, ε ≈ 1e-5
Relative error |g_num − g_analytic| / (|g_num| + |g_analytic|)
The example checks every parameter of a small 4-5-3 network in float64 and finds a maximum relative error of 1.64×10⁻⁹. For the same network, the W₁ and W₂ gradients computed by PyTorch's loss.backward() match the hand-written ones (torch.allclose returns True). The CS231n backpropagation notes illustrate in detail how to break gradients down along a computational graph.
Initialisation and vanishing gradients
During backpropagation, the gradient reaching layer l contains a product of the derivatives and weights of all later layers. If each layer scales the gradient by less than 1, it shrinks exponentially with depth (vanishing gradients); if by more than 1, it explodes. Bengio, Simard and Frasconi (1994) analysed how this makes long-term dependencies hard to learn in recurrent networks. The sigmoid's derivative is at most 0.25, so even at its maximum, ten layers multiply out to 0.25¹⁰ ≈ 9.5×10⁻⁷.
There are four main remedies:
- Activations: ReLU has derivative 1 on the positive side and does not shrink gradients through saturation.
- Initialisation: Glorot and Bengio (2010) found that with random initialisation the sigmoid drives the top hidden layer into saturation, and proposed a "normalized initialization" that keeps the variance of forward activations and backward gradients roughly constant across layers: sample from U[−√6/√(n_in + n_out), +√6/√(n_in + n_out)], giving variance 2/(n_in + n_out). He et al. (2015) derived an initialisation with variance 2/n_in for ReLU. PyTorch provides
xavier_uniform_,kaiming_normal_and related functions intorch.nn.init. - Residual connections: ResNet (He et al., 2015) has each block learn the residual F in x + F(x), so gradients can flow straight back to early layers along the identity path.
- Normalisation: batch normalisation and layer normalisation bring each layer's inputs back to a stable distribution; see the Training Tricks unit.
The example's two-layer network uses He initialisation for the hidden layer (standard deviation √(2/64)) and is trained with mini-batch SGD (batch size 32, learning rate 0.1) for 30 epochs on scikit-learn's bundled 8×8 handwritten digits (1,797 images, stratified 3:1 train/test split). Test accuracy after epochs 1, 10 and 30 is 0.520, 0.844 and 0.971, and the training loss falls from 1.3957 to 0.0703.
How this maps onto large models
- The feed-forward layer is an MLP: every Transformer layer consists of an attention sub-layer and a feed-forward sub-layer, and the latter applies "expand → activate → project back" to each token independently. BERT uses GELU; the LLaMA paper states that it replaces ReLU with SwiGLU (Touvron et al., 2023).
- Training is backpropagation: pre-training minimises next-token cross-entropy, backpropagation computes the gradients of all parameters, and an optimizer such as AdamW applies the update.
- Residuals and normalisation: every Transformer sub-layer is wrapped in a residual connection and normalisation, for exactly the training-stability reasons discussed above.
- Autoencoders: an encoder compresses the input into a low-dimensional representation and a decoder reconstructs it. Hinton and Salakhutdinov (2006) used deep autoencoders for non-linear dimensionality reduction that outperformed PCA, which can be compared with PCA in the Unsupervised Learning lesson; variational autoencoders (VAEs) turn the same structure into a generative model.
Runnable examples
The code below was run on NumPy 2.5 and scikit-learn 1.9, and its output matches the numbers above.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
# 1) Without non-linearity, two linear layers equal one
W1, W2 = rng.normal(size=(64, 32)), rng.normal(size=(32, 10)); x = rng.normal(size=(5, 64))
print("two linear layers == one:", np.allclose((x @ W1) @ W2, x @ (W1 @ W2)))
# 2) A perceptron cannot learn XOR
X4 = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], float); y4 = np.array([0, 1, 1, 0])
w, b = np.zeros(2), 0.0
for _ in range(100):
for xi, yi in zip(X4, y4):
pred = int(xi @ w + b > 0); w += (yi - pred) * xi; b += (yi - pred)
print("perceptron XOR accuracy:", (((X4 @ w + b) > 0).astype(int) == y4).mean())
# 3) Two-layer MLP: hand-written forward and backward passes
def init(n_in, n_h, n_out):
return {"W1": rng.normal(0, np.sqrt(2 / n_in), (n_in, n_h)), "b1": np.zeros(n_h), # He init
"W2": rng.normal(0, np.sqrt(1 / n_h), (n_h, n_out)), "b2": np.zeros(n_out)}
def forward(p, X):
z1 = X @ p["W1"] + p["b1"]; h = np.maximum(0, z1); z2 = h @ p["W2"] + p["b2"]
e = np.exp(z2 - z2.max(1, keepdims=True)); return z1, h, e / e.sum(1, keepdims=True)
def loss_grad(p, X, Y):
n = len(X); z1, h, prob = forward(p, X)
loss = -np.log(prob[np.arange(n), Y]).mean()
dz2 = prob.copy(); dz2[np.arange(n), Y] -= 1; dz2 /= n # (p − Y) / n
g = {"W2": h.T @ dz2, "b2": dz2.sum(0)}
dz1 = (dz2 @ p["W2"].T) * (z1 > 0) # times the ReLU derivative
g["W1"] = X.T @ dz1; g["b1"] = dz1.sum(0)
return loss, g
# 3a) Gradient check
p = init(4, 5, 3); Xs = rng.normal(size=(6, 4)); Ys = rng.integers(0, 3, 6)
_, g = loss_grad(p, Xs, Ys); eps, worst = 1e-5, 0
for k in p:
for i in np.ndindex(p[k].shape):
old = p[k][i]
p[k][i] = old + eps; lp, _ = loss_grad(p, Xs, Ys)
p[k][i] = old - eps; lm, _ = loss_grad(p, Xs, Ys); p[k][i] = old
num = (lp - lm) / (2 * eps)
worst = max(worst, abs(num - g[k][i]) / max(1e-8, abs(num) + abs(g[k][i])))
print(f"gradient check, max relative error {worst:.2e}")
# 3b) Train on 8×8 handwritten digits
X, y = load_digits(return_X_y=True); X = X / 16.0
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
p = init(64, 64, 10); lr = 0.1
for epoch in range(1, 31):
idx = rng.permutation(len(Xtr))
for s in range(0, len(Xtr), 32):
bt = idx[s:s + 32]; _, g = loss_grad(p, Xtr[bt], ytr[bt])
for k in p: p[k] -= lr * g[k]
if epoch in (1, 10, 30):
acc = (forward(p, Xte)[2].argmax(1) == yte).mean()
print(f"epoch {epoch:2d} train loss {loss_grad(p, Xtr, ytr)[0]:.4f} test accuracy {acc:.4f}")
# 4) Sigmoid derivative bound over 10 layers
print("max sigmoid derivative 0.25; product over 10 layers", 0.25 ** 10)
Key outputs: two linear layers equal one (True); perceptron XOR accuracy 0.5; maximum relative error in the gradient check 1.64e-09; test accuracy 0.5200, 0.8444 and 0.9711 after epochs 1, 10 and 30, with training loss 1.3957, 0.4170 and 0.0703; 0.25¹⁰ ≈ 9.54e-07.
Checking the hand-written gradients against PyTorch (run on PyTorch 2.15 CPU):
import torch
torch.manual_seed(0)
X = torch.randn(6, 4, dtype=torch.float64); Y = torch.randint(0, 3, (6,))
W1 = torch.randn(4, 5, dtype=torch.float64, requires_grad=True); b1 = torch.zeros(5, dtype=torch.float64, requires_grad=True)
W2 = torch.randn(5, 3, dtype=torch.float64, requires_grad=True); b2 = torch.zeros(3, dtype=torch.float64, requires_grad=True)
z1 = X @ W1 + b1; h = torch.relu(z1); z2 = h @ W2 + b2
torch.nn.functional.cross_entropy(z2, Y).backward() # autograd
with torch.no_grad(): # hand-written backprop
dz2 = torch.softmax(z2, 1); dz2[torch.arange(6), Y] -= 1; dz2 /= 6
gW2 = h.T @ dz2; gW1 = X.T @ ((dz2 @ W2.T) * (z1 > 0))
print(torch.allclose(gW1, W1.grad), torch.allclose(gW2, W2.grad)) # True True
x = torch.linspace(-3, 3, 7)
print(torch.nn.functional.gelu(x)) # matches x·Φ(x)
print(x * 0.5 * (1 + torch.erf(x / 2 ** 0.5)))
Hands-on practice
- Unit project: without a deep-learning framework, implement a two-layer MLP in NumPy that recognises MNIST with over 95% test accuracy; confirm the backward pass with a gradient check first, then compare convergence with sigmoid versus ReLU and with different initialisation scales.
- Follow micrograd to build a scalar autograd engine from scratch and compare its gradients with PyTorch.
- Complete the lecture 1 notebook of nn-zero-to-hero, a step-by-step walkthrough of backpropagation.
- In TensorFlow Playground, pick the spiral dataset and try a single hidden layer, more layers and different activations to see whether the two classes can be separated.
Suggested order
Start with the 3Blue1Brown neural networks series for geometric intuition; then read the multilayer perceptron, backpropagation and numerical stability sections of D2L chapter 5 to connect the formulas with code; practise computing gradients along computational graphs with the CS231n backpropagation notes; for a systematic treatment, read chapter 6 of Goodfellow et al.'s Deep Learning. For hands-on work, use Karpathy's Zero to Hero course. Then continue with Tokens and Embeddings and Transformers and Attention.
FAQ
Are neural networks like the brain?
Only in loose inspiration. Rosenblatt's (1958) perceptron paper was titled 'A probabilistic model for information storage and organization in the brain', but a neuron in a modern network is just a weighted sum followed by a non-linear function, trained with backpropagation and gradient descent. There is no evidence that the brain learns the same way.
Which activation function should I use?
The usual default for hidden layers is ReLU, max(0, x); Krizhevsky et al. (2012) reported that convolutional networks with ReLUs train several times faster than their tanh equivalents. Transformers commonly use GELU (Hendrycks and Gimpel, 2016); the BERT paper states that it uses GELU following OpenAI GPT, and models such as LLaMA use SwiGLU (Shazeer, 2020) in their feed-forward layers. Sigmoid and tanh are now rare in the hidden layers of deep networks but are still used in gates and binary-classification outputs.
How does backpropagation relate to automatic differentiation?
Backpropagation is reverse-mode automatic differentiation applied to neural networks. The survey by Baydin et al. (2015) notes that Linnainmaa (1970) is often cited as the first published description of reverse mode; Rumelhart, Hinton and Williams (1986) showed in Nature that it can train hidden units to learn useful internal representations, which made the method widely known in neural-network research. Frameworks such as PyTorch and JAX build the computational graph and run backpropagation automatically.
Does the universal approximation theorem mean one hidden layer is enough?
Cybenko (1989) and Hornik et al. (1989) proved that a network with a single hidden layer and enough hidden units can approximate any continuous function on a compact set to arbitrary accuracy. The theorem only guarantees that such a network exists; it says nothing about how many units are needed or whether gradient descent will find it. In practice, adding depth is usually more effective than making a layer ever wider.
Why are intermediate activations stored during training, and does this cost memory?
Yes. Computing a layer's weight gradient during the backward pass needs that layer's input from the forward pass, so training keeps every layer's activations until the backward pass finishes. This is one of the main reasons training needs far more memory than inference. PyTorch's torch.utils.checkpoint (activation checkpointing) saves memory by recomputing part of the forward pass during the backward pass.