AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·151

Deep Learning

Neural networks from the neuron up: the perceptron and its learning rule, why XOR needs hidden layers, multi-layer perceptrons as compositions of linear maps and nonlinearities, the universal approximation theorem, activation functions (sigmoid, tanh, ReLU, GELU, SiLU/SwiGLU) and their gradients, loss functions for regression, classification and beyond, backpropagation through a full MLP in matrix form implemented in NumPy, optimisers (SGD, momentum, Adam, AdamW) in practice, weight initialisation (Xavier, He) and why it matters, normalisation (batch, layer, RMSNorm), dropout, batch size and the learning rate (warm-up, cosine decay, the linear scaling rule), weight decay, gradient clipping, residual connections, and a practical training recipe with debugging checklist.

26 topics · ~19 min read · 32-question quiz
Updated Suggest a correction

Start here: a neural network in fifty lines

A neural network is a stack of simple steps: multiply the input by a matrix of weights, add a bias, apply a nonlinearity (such as ReLU, which turns negatives into zero), and repeat. The last layer turns scores into probabilities with softmax. Training is the Start Here chapter's recipe: a loss (here cross-entropy), gradients by the chain rule (backpropagation), and gradient descent.

Why hidden layers: the XOR problem

XOR outputs 1 when exactly one of two inputs is 1. No straight line separates its 1s from its 0s:

Text
no hidden layer (a linear model):   predictions [1 0 1 0] vs truth [0 1 1 0] → 50% correct
one hidden layer of 8 ReLU units:   loss 1.0125 (epoch 0) → 0.0234 (100) → 0.0017 (1,000) → 0.0005 (2,999)
                                    predictions [0 1 1 0] → 100% correct

The hidden layer learned new features (combinations of the inputs) in which the problem becomes linearly separable. That's the whole idea of deep learning: layers learn representations, and later layers build on earlier ones. (Stacking linear layers without nonlinearities wouldn't help: a product of matrices is just another matrix.)

The backward pass, written out

The full training step for one hidden layer, from the lab's code:

Python
H = np.maximum(0, X @ W1 + b1)                 # hidden layer with ReLU
P = softmax(H @ W2 + b2)                       # class probabilities
dZ = (P - Y) / len(X)                          # gradient of cross-entropy w.r.t. scores
dW2, db2 = H.T @ dZ, dZ.sum(0)
dH = dZ @ W2.T; dH[H <= 0] = 0                 # back through ReLU
dW1, db1 = X.T @ dH, dH.sum(0)
W1 -= lr * dW1;  W2 -= lr * dW2;  ...          # gradient descent

Every line of the backward pass is the chain rule applied to one line of the forward pass. Frameworks like PyTorch (chapter 152) generate this automatically, but it's the same arithmetic.

Capacity: how many hidden units?

Handwritten digits (8×8 images, 10 classes), trained with this code:

Text
no hidden layer (softmax regression):  train  98.9%  test 97.2%     650 parameters
  4 hidden units:                      train  91.1%  test 87.2%     310 parameters   (a bottleneck)
 16 hidden units:                      train 100.0%  test 96.5%   1,210 parameters
 64 hidden units:                      train 100.0%  test 97.6%   4,810 parameters
256 hidden units:                      train 100.0%  test 98.1%  19,210 parameters

These small images are almost linearly separable, so even no hidden layer did well. Squeezing everything through 4 units threw away information. Wider layers fit the training set perfectly and still generalised slightly better: large networks often generalise well despite having enough capacity to memorise, a surprise that classical bias–variance intuition doesn't predict.

How deep to go in deep learning

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain neurons, layers, activations, softmax and why depth helps
L2 Train MLPs with a framework using sensible initialisation, optimiser and regularisation
L3 Derive backpropagation for an MLP and explain capacity, regularisation and generalisation
L4 Diagnose training failures (divergence, dead units, overfitting) and fix them
L5 Choose architectures, objectives and training regimes for a problem
L6 Push deep learning methods forward or run training programmes at scale

From linear models to neural networks

A linear model ŷ = Wx + b can only draw straight decision boundaries. Stacking linear layers doesn't help: W₂(W₁x) = (W₂W₁)x is still linear. The key ingredient is a nonlinearity between layers: h = φ(W₁x + b₁), ŷ = W₂h + b₂. With enough hidden units, such networks can represent extremely rich functions, and gradient descent with backpropagation (chapter 146) can fit them.

Deep learning = neural networks with many layers, trained end-to-end on large data, learning their own representations (features) instead of relying on hand-engineered ones.

The perceptron

Frank Rosenblatt's perceptron (1958): ŷ = step(w · x + b). Learning rule: for each misclassified example, w ← w + η·y·x (labels ±1). It converges if the data is linearly separable.

Minsky and Papert (1969) highlighted its limits: a single perceptron can't learn XOR, because no line separates {(0,1), (1,0)} from {(0,0), (1,1)}. One hidden layer solves it: hidden units compute OR and NAND, and the output computes their AND.

(0,0)(1,0)1 no single line hiddenlayer h₁ = OR(x)h₂ = AND(x) ×2 separable now
XOR is not linearly separable. In input space no single line separates the two classes. A hidden layer maps the four points into a new representation, here the outputs of an OR unit and an AND unit, in which a single line does separate them. Learning such representations is the essence of deep learning.

Multi-layer perceptrons

An MLP (fully connected / dense network) alternates affine layers and elementwise nonlinearities:

h⁽¹⁾ = φ(W⁽¹⁾x + b⁽¹⁾), h⁽²⁾ = φ(W⁽²⁾h⁽¹⁾ + b⁽²⁾), …, ŷ = W⁽ᴸ⁾h⁽ᴸ⁻¹⁾ + b⁽ᴸ⁾

  • Width: units per layer; depth: number of layers.
  • With a mini-batch, x becomes a matrix X (batch × features) and each layer is one matrix multiply: H = φ(XWᵀ + b): why GPUs (matmul machines) dominate.
  • Parameters per dense layer: in × out + out. A 4096 → 16384 layer has about 67M parameters.
  • Universal approximation theorem: a network with one hidden layer and enough units can approximate any continuous function on a compact domain to arbitrary accuracy. It says nothing about how many units, or whether training finds them; depth makes many functions exponentially more efficient to represent (compositional structure), which is why deep networks work better in practice.
softmax x ∈ ℝ⁴ReLU(W₁x+b₁)ReLU(W₂h₁+b₂)logitsp
A multi-layer perceptron. Each layer multiplies its input by a weight matrix, adds a bias, and applies a nonlinearity; the final layer produces logits that softmax turns into class probabilities. In a batch, each arrow bundle is one matrix multiplication.

Activation functions

Activation Formula Gradient Notes
Sigmoid 1/(1 + e⁻ˣ) σ(1 − σ) ≤ 0.25 Output gates and binary outputs; saturates → vanishing gradients in deep stacks
tanh (eˣ − e⁻ˣ)/(eˣ + e⁻ˣ) 1 − tanh² Zero-centred; RNNs; still saturates
ReLU max(0, x) 0 or 1 Cheap, non-saturating for x > 0; "dying ReLU" when a unit's input is always negative
Leaky ReLU / PReLU max(αx, x) α or 1 Keeps a small gradient for x < 0
ELU / SELU smooth negative part — SELU self-normalises under specific conditions
GELU x·Φ(x) (Φ = normal CDF) smooth BERT, GPT-2/3; smooth gating by input magnitude
SiLU / Swish x·σ(x) smooth Vision and LLM MLPs
SwiGLU / GeGLU (xW ⊙ SiLU(xV))W₂ — Gated linear units in the MLP blocks of most modern LLMs (Llama-family, Qwen, Mistral, Gemma variants)
Softmax exp(zᵢ)/Σexp(zⱼ) Jacobian diag(p) − ppᵀ Output distribution over classes or tokens
sigmoid tanh ReLU GELU / SiLU
Common activation functions. Sigmoid and tanh flatten out for large inputs, so their gradients vanish there. ReLU is zero for negative inputs and the identity for positive ones. GELU and SiLU are smooth variants that let small negative values through, and are the defaults in Transformer feed-forward blocks.

Loss functions

Task Output Loss
Regression Linear unit MSE (Gaussian), MAE / Huber (robust), quantile (intervals)
Binary classification 1 logit Binary cross-entropy with logits (sigmoid fused)
Multi-class K logits Categorical cross-entropy with logits (softmax fused); label smoothing
Multi-label K logits Independent BCE per label
Imbalanced — Class weights, focal loss (down-weights easy examples)
Similarity / embeddings Vectors Contrastive (InfoNCE), triplet, cosine embedding loss (chapter 159)
Sequence generation Token logits Next-token cross-entropy (chapter 156)
Generative — Reconstruction + KL (VAE), adversarial (GAN), denoising MSE (diffusion)
Preference Pairs Bradley–Terry / DPO losses (chapter 164)

Label smoothing replaces one-hot targets with (1 − ε) on the true class and ε/K elsewhere: discourages over-confidence, improving calibration and generalisation.

Backpropagation through an MLP

For a dense layer Z = XWᵀ + b followed by A = φ(Z), with upstream gradient G = ∂L/∂A (batch × out):

  • ∂L/∂Z = G ⊙ φ′(Z) (elementwise)
  • ∂L/∂W = (∂L/∂Z)ᵀ X (out × in)
  • ∂L/∂b = column sums of ∂L/∂Z
  • ∂L/∂X = (∂L/∂Z) W (passed to the previous layer)

For softmax + cross-entropy averaged over a batch of n: ∂L/∂logits = (P − Y)/n (chapter 147).

A complete two-layer network trained on a nonlinear problem, in NumPy:

Python
import numpy as np
rng = np.random.default_rng(0)

# Two interleaved spirals: not linearly separable
def spirals(n=300, noise=0.2):
    t = np.sqrt(rng.random(n)) * 3 * np.pi
    a = np.c_[t * np.cos(t), t * np.sin(t)] + rng.normal(scale=noise, size=(n, 2))
    b = np.c_[-t * np.cos(t), -t * np.sin(t)] + rng.normal(scale=noise, size=(n, 2))
    X = np.vstack([a, b]) / 10; y = np.r_[np.zeros(n), np.ones(n)].astype(int)
    return X, y

X, y = spirals()
Y = np.eye(2)[y]
d_in, d_h, d_out = 2, 64, 2
W1 = rng.normal(0, np.sqrt(2 / d_in), (d_h, d_in)); b1 = np.zeros(d_h)       # He initialisation
W2 = rng.normal(0, np.sqrt(2 / d_h), (d_h, d_h));  b2 = np.zeros(d_h)
W3 = rng.normal(0, np.sqrt(1 / d_h), (d_out, d_h)); b3 = np.zeros(d_out)
params = [W1, b1, W2, b2, W3, b3]
m = [np.zeros_like(p) for p in params]; v = [np.zeros_like(p) for p in params]

def forward(X):
    Z1 = X @ W1.T + b1; A1 = np.maximum(Z1, 0)
    Z2 = A1 @ W2.T + b2; A2 = np.maximum(Z2, 0)
    logits = A2 @ W3.T + b3
    return Z1, A1, Z2, A2, logits

for step in range(1, 3001):
    Z1, A1, Z2, A2, logits = forward(X)
    logits -= logits.max(1, keepdims=True)
    P = np.exp(logits); P /= P.sum(1, keepdims=True)
    loss = -np.mean(np.log(P[np.arange(len(y)), y]))

    dlogits = (P - Y) / len(y)                                   # softmax + CE gradient
    dW3 = dlogits.T @ A2; db3 = dlogits.sum(0); dA2 = dlogits @ W3
    dZ2 = dA2 * (Z2 > 0)                                         # ReLU derivative
    dW2 = dZ2.T @ A1; db2 = dZ2.sum(0); dA1 = dZ2 @ W2
    dZ1 = dA1 * (Z1 > 0)
    dW1 = dZ1.T @ X;  db1 = dZ1.sum(0)
    grads = [dW1, db1, dW2, db2, dW3, db3]

    for i, (p, g) in enumerate(zip(params, grads)):             # Adam, in place
        m[i] = 0.9 * m[i] + 0.1 * g; v[i] = 0.999 * v[i] + 0.001 * g * g
        p -= 0.01 * (m[i] / (1 - 0.9 ** step)) / (np.sqrt(v[i] / (1 - 0.999 ** step)) + 1e-8)

acc = (forward(X)[-1].argmax(1) == y).mean()
round(loss, 3), acc                       # loss → ≈0, training accuracy 1.0: it fits perfectly (judge it on held-out data!)

Every deep learning framework automates exactly this: forward pass, gradient bookkeeping, parameter update. Chapter 152 rewrites it in PyTorch in a dozen lines.

Optimisers in practice

Chapter 146 derived SGD, momentum and Adam. Practical guidance:

Optimiser Typical use Typical learning rate
SGD + momentum (0.9), Nesterov CNNs for vision, when well-tuned schedules exist; can generalise slightly better 0.01–0.1 (with batch-size scaling)
Adam Default for quick experiments 1e-3
AdamW Transformers, fine-tuning, LLM pre-training; decoupled weight decay 1e-4 to 6e-4 pre-training; 1e-5 to 2e-4 fine-tuning (much higher for LoRA adapters)
Adafactor, 8-bit Adam, paged optimisers Memory-constrained large models —
Lion, Sophia, Shampoo/SOAP, Muon Research and some large-scale training; Muon orthogonalises updates for matrix parameters —

Adam stores two extra values per parameter (m, v): optimiser state is often 2× the model's weights in memory, which matters for large models (chapter 152, 165).

Initialisation

Weights must start random (identical weights would compute identical gradients: symmetry), and at the right scale: if each layer multiplies the signal's variance by more than 1, activations and gradients explode with depth; less than 1, they vanish.

  • For a layer with fan_in inputs, the output variance ≈ fan_in · Var(w) · Var(input). Keeping it constant needs Var(w) ≈ 1/fan_in.
  • Xavier/Glorot (tanh, sigmoid): Var(w) = 2/(fan_in + fan_out).
  • He/Kaiming (ReLU): Var(w) = 2/fan_in (ReLU zeroes half the inputs, halving variance).
  • Biases: usually zero. Output layers sometimes initialised small or zero; residual branches often scaled by 1/√(2·layers) in Transformers.
  • Frameworks choose sensible defaults per layer type, but custom architectures need attention.
Python
def activation_stats(init_std, depth=20, width=512):
    h = rng.normal(size=(256, width))
    for _ in range(depth):
        W = rng.normal(0, init_std, (width, width))
        h = np.maximum(h @ W, 0)
    return h.std()

activation_stats(0.01)                     # → ~0: signal vanished
activation_stats(np.sqrt(2 / 512))         # → order 1: He init keeps the scale
activation_stats(0.1)                      # → ≈ 10⁴ and growing ≈1.6× per layer: exploding

Normalisation

Normalisation layers rescale activations to stable statistics, smoothing the loss landscape and allowing higher learning rates.

Layer Normalises over Use
BatchNorm Each feature across the batch (and spatial positions) CNNs; needs reasonable batch sizes; behaves differently in training (batch stats) and inference (running averages): a classic bug source
LayerNorm All features of each example Transformers, RNNs; independent of batch size
RMSNorm Like LayerNorm without mean-centering: x / RMS(x) · γ Most modern LLMs; cheaper
GroupNorm / InstanceNorm Groups of channels per example Small-batch vision, style transfer

Each has learnable scale (γ) and usually shift (β) so the network can undo normalisation if useful. Placement in Transformers: pre-norm (normalise the input of each sub-block) trains more stably than the original post-norm.

Residual connections

A residual block computes x + F(x) instead of F(x) (ResNet, 2015). The identity path gives gradients a direct route backward: ∂(x + F(x))/∂x = I + ∂F/∂x, so gradients don't have to pass through every nonlinearity. This made very deep networks (100+ layers) trainable and is present in every Transformer block (chapter 154).

Regularisation in deep learning

  • Dropout: during training, zero each activation with probability p and scale survivors by 1/(1 − p) ("inverted dropout"); at inference, do nothing. Prevents co-adaptation; acts like an ensemble of sub-networks. Common p: 0.1–0.5; many large LLMs use little or none during pre-training because data is abundant.
  • Weight decay: shrink weights each step (L2-like). With Adam, use AdamW so decay isn't distorted by adaptive scaling. Typically 0.01–0.1; usually not applied to biases and normalisation parameters.
  • Data augmentation: random crops, flips, colour jitter, mixup/cutmix (vision); SpecAugment (audio); back-translation, paraphrasing (text).
  • Early stopping: stop when validation loss stops improving; keep the best checkpoint.
  • Label smoothing, stochastic depth (drop whole residual blocks).
Python
def dropout(x, p, training, rng):
    if not training or p == 0: return x
    mask = (rng.random(x.shape) >= p) / (1 - p)     # inverted dropout: expected value unchanged
    return x * mask

Batch size and learning rate

  • Batch size trades gradient noise against throughput. Larger batches use hardware better and give smoother gradients but fewer updates per epoch; beyond a critical batch size, more data per step stops speeding up training.
  • Linear scaling rule (for SGD, moderate batch sizes): multiply batch size by k → multiply learning rate by k, with warm-up. Adam tends to follow closer to square-root scaling. Always re-validate.
  • Gradient accumulation simulates a large batch on limited memory: sum gradients over several micro-batches before stepping.
  • The learning rate is the most important hyperparameter. Use a schedule:
  • Warm-up: increase linearly from ~0 over the first few hundred or thousand steps (Adam's moment estimates and the early loss landscape are unstable).
  • Decay: cosine to ~10% of peak, linear, step, or warmup-stable-decay (WSD), which keeps a constant rate then decays at the end (handy for continued training).
  • LR range test: increase the learning rate exponentially over a short run; pick a value somewhat below where loss starts to blow up.
training steps →learning rate peakwarm-up cosine decayWSD plateau
A typical learning-rate schedule for Transformer training. The rate rises linearly during warm-up, then follows a cosine decay toward a small final value. A warmup-stable-decay schedule instead holds a constant plateau and decays only at the end.

Gradient clipping

Rare large gradients (from outliers, unstable attention logits, or bad batches) can wreck training. Clipping by global norm rescales all gradients when their combined norm exceeds a threshold (commonly 1.0 for Transformers):

if ‖g‖ > c: g ← g · c/‖g‖

Monitor the gradient norm during training: spikes often precede loss spikes and divergence.

Python
def clip_by_global_norm(grads, max_norm=1.0):
    total = np.sqrt(sum(np.sum(g * g) for g in grads))
    scale = min(1.0, max_norm / (total + 1e-6))
    return [g * scale for g in grads], total

A practical training recipe

  1. Start simple: a small, known-good architecture and a baseline. Get the pipeline working end-to-end.
  2. Overfit one batch first: if a model can't drive loss near zero on 32 examples, there's a bug (labels, loss, gradient flow, learning rate).
  3. Check the initial loss: for K balanced classes, cross-entropy should start near ln K (2.30 for 10 classes). Much higher means bad initialisation or label issues.
  4. Find a learning rate (range test), use AdamW with warm-up and cosine decay, weight decay 0.01–0.1, gradient clipping at 1.0.
  5. Monitor: training and validation loss, gradient norm, learning rate, activation statistics, throughput, sample predictions.
  6. Scale up data and model gradually; regularise only once overfitting appears.
  7. Ablate one change at a time; fix random seeds; log everything (chapter 178).

Lab: an MLP from scratch in NumPy

NumPy 2.5 on the lab machine; full-batch gradient descent, He initialisation (N(0, 2/fan_in)), ReLU hidden units, softmax + cross-entropy output. Digits are scikit-learn's bundled 8×8 images scaled to [0, 1], 60/40 stratified split.

Experiment 1: XOR

Model Loss trajectory Predictions Accuracy
softmax regression (no hidden layer), 5,000 epochs — [1 0 1 0] 50%
8 ReLU hidden units, 3,000 epochs, lr 0.5 1.0125 → 0.0234 (ep 100) → 0.0017 (ep 1,000) → 0.0005 [0 1 1 0] 100%

All ten seeds tried (0–9) reached 100%. With fewer units (try 2) some initialisations leave too few ReLUs active on the four points and training stalls, the "dying ReLU" problem at tiny scale; wide layers make it rare.

Experiment 2: width on digits

Hidden units Train Test Parameters Time (2,000 epochs)
0 98.9% 97.2% 650 1.1 s
4 91.1% 87.2% 310 1.0 s
16 100.0% 96.5% 1,210 1.5 s
64 100.0% 97.6% 4,810 3.2 s
256 100.0% 98.1% 19,210 14.2 s

On 719 test images, one image is 0.14 points, so 97.6% vs 98.1% is about 4 images: suggestive, not conclusive (chapter 147). The widest network memorised the training set yet tested best. This benign overfitting is common in over-parameterised networks trained by gradient descent and is part of why "bigger models generalise better" held up in practice (the "double descent" picture extends the classical U-curve).

Experiment 3: verifying the hand-written backward pass

Before trusting hand-written gradients, compare them with finite differences on a few weights (chapter 146): perturb one entry of W1 by ±1e-5, recompute the loss, and check (L+ − L−)/2e-5 matches dW1 to about 1e-7 relative error. Every framework's own test suite does this for each operation (torch.autograd.gradcheck).

Try it yourself

  1. Add L2 weight decay (dW += λ W) to the 256-unit network and find the λ that maximises validation accuracy.
  2. Replace full-batch descent with mini-batches of 32 and compare epochs needed and final accuracy.
  3. Add a second hidden layer and compare 64-64 with a single 256 layer at similar parameter counts.
  4. Implement the gradient check above for W1 and b1 and report the maximum relative error.

Revision sheet: deep learning

Key ideas

  • Perceptron → MLP: linear map + nonlinearity, stacked; universal approximation (wide enough nets approximate any continuous function, depth makes it efficient).
  • Activations: ReLU, GELU/SiLU (modern), sigmoid/tanh (gates, outputs); softmax for class probabilities.
  • Losses: cross-entropy (classification), MSE/MAE/Huber (regression).
  • Backpropagation: chain rule in reverse; cost ≈ 2× the forward pass.
  • Optimisation: SGD with momentum, Adam/AdamW; mini-batches; learning-rate schedules.
  • Initialisation and normalisation: He/Xavier; batch norm, layer norm; residual connections.
  • Regularisation: weight decay, dropout, data augmentation, early stopping.
  • Generalisation in over-parameterised nets: benign overfitting, double descent, implicit regularisation of SGD.

Numbers to remember

  • Lab: XOR 50% linear → 100% with 8 hidden ReLUs.
  • Lab: digits 97.2% with no hidden layer, 87.2% with a 4-unit bottleneck, 98.1% with 256 units.
  • An MLP layer d → h has d·h + h parameters.

Pitfalls

  • No nonlinearity between layers.
  • Bottleneck layers too narrow for the information needed.
  • Bad initialisation (vanishing or exploding signals, dead ReLUs).
  • Judging tiny accuracy differences on small test sets.
  • Training without a validation set for early stopping and tuning.

Glossary

  • Representation learning: learning features rather than hand-crafting them.
  • Logits: pre-softmax scores.
  • Epoch: one pass over the training data.
  • Dropout: randomly zeroing activations during training.
  • Double descent: test error falling again as models grow past the interpolation point.