Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Training a CNN

How convolutional neural networks are trained: loss, gradients, optimisation algorithms (SGD, momentum, Adam), regularisation, practical choices and the backpropagation formulas (including gradients for convolution).

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Training a convolutional neural network (CNN) turns a network’s randomly initialised filters into feature detectors that solve tasks (classification, detection, segmentation). An engineer uses these notes when choosing optimisation settings, preventing overfitting, debugging bad training, and writing the forward/backward code for convolution layers.

Key ideas

  • Gradient-based optimisation: compute gradient ∇_θ L and update θ to reduce L. The basic rule for full-batch gradient descent (assume differentiable loss): update θ ← θ − η ∇_θ L, where η is the learning rate (positive scalar). If dataset is large, use stochastic gradient descent (SGD) or mini-batch SGD which use gradients estimated from a subset (batch) of examples.

  • Epoch / iteration: one epoch = one pass over the full dataset. One iteration (or step) = one parameter update using one mini-batch.

  • Momentum: keeps an exponentially weighted average of past gradients to accelerate training and damp oscillations. Define velocity v_t and update rules below.

  • Adaptive optimisers: Adam, RMSProp, AdaGrad change per-parameter step sizes based on gradient magnitudes and moments. They combine ideas of momentum and per-parameter scaling. For Adam (β1, β2), with g_t = ∇θ L_t: m_t = β1 m{t−1} + (1−β1) g_t, v_t = β2 v_{t−1} + (1−β2) g_t^2; bias-correct m̂_t = m_t/(1−β1^t), v̂_t = v_t/(1−β2^t), then update θ ← θ − η m̂_t/(sqrt(v̂_t)+ε). Note: for adaptive methods, decoupled weight decay (AdamW) is preferred over adding λ‖θ‖^2 to the loss, updating as θ ← θ − η ( m̂_t/(sqrt(v̂_t)+ε) + λ θ ).

  • Regularisation: methods to reduce overfitting: L2 weight decay (adds λ/2 ‖θ‖^2 to loss), dropout (randomly zero activations during training), data augmentation (generate transformed inputs), early stopping (stop when validation loss stops improving).

  • Weight initialisation: choose initial weights to avoid vanishing/exploding gradients. Common schemes: Xavier/Glorot (for tanh) and He/Kaiming (for ReLU). State assumptions: these derive from preserving variance of signals forward/backward under independence assumptions. Typical choices: He normal with Var(w) = 2/fan_in for ReLU/LeakyReLU; Glorot (Xavier) with Var(w) = 2/(fan_in+fan_out) (normal) or uniform bounds ±sqrt(6/(fan_in+fan_out)) for tanh/linear.

  • Batch normalisation (BatchNorm): normalises layer activations across the mini-batch to zero mean and unit variance, then scales/shifts with learned γ, β. Helps with training stability and allows higher learning rates. In CNNs, BN is computed per-channel over the batch and spatial locations; at inference, use running (exponential moving average) estimates of mean and variance.

  • Vanishing and exploding gradients: gradients may shrink or grow exponentially through many layers. Mitigations: good initialisation, BatchNorm, residual connections (ResNet), careful learning rates.

  • Convolution backpropagation (key derivation frequently asked in exams). Use the common deep-learning convention: convolution layers implement cross-correlation: for one input channel and one output channel, with no stride/padding, the forward output is y[i,j] = Σ_{u=0}^{K-1} Σ_{v=0}^{K-1} x[i+u, j+v] · w[u,v] + b. Let δ[i,j] = ∂L/∂y[i,j] (gradient of loss wrt output). Then:

    • Gradient wrt kernel w: ∂L/∂w[u,v] = Σ_{i,j} x[i+u, j+v] · δ[i,j].
    • Gradient wrt input x: ∂L/∂x[a,b] = Σ_{i,j} δ[i,j] · w[a−i, b−j], summing only where indices valid. In practice, ∂L/∂x equals (full) convolution of δ with the kernel flipped both axes. Gradient wrt bias: ∂L/∂b = Σ_{i,j} δ[i,j].

    What to draw for an exam diagram: draw a 3×3 input grid, a 2×2 kernel overlay at the top-left producing y₀₀, then slide kernel one step to the right to get y₀₁, etc. Label each input pixel with coordinates and show which kernel weight multiplies which input for a chosen output. Then write the sum formula for that output and show how summing δ-weighted patches produces ∂L/∂w.

Notes where unsure: the sign-convention for cross-correlation vs mathematical convolution — I use the deep-learning cross-correlation convention (no flip) for forward; flipped kernel appears in input gradient. Verify for your framework.

Formulas

y[i,j] = Σ_{u,v} x[i+u, j+v] · w[u,v] + b — y: output activation at (i,j), unitless; x: input activation, unitless; w: kernel weight, unitless; b: bias, unitless. Applies for cross-correlation conv layer without stride/padding.

L(θ) = (1/N) Σ_{n=1..N} ℓ(f(x_n; θ), y_n) — average loss over N examples. Units: unitless. Applies to supervised training.

θ ← θ − η ∇_θ L — gradient descent update. η: learning rate (unitless), ∇_θ L: gradient vector (same units as θ inverse).

v_t = μ v_{t−1} + (1−μ) ∇_θ L(t) and θ ← θ − η v_t — momentum (one common variant). μ: momentum coefficient (unitless, e.g. 0.9).

θ ← θ − η (∇_θ L + λ θ) — SGD with L2 weight decay (λ has units 1/(parameter units)^2; if θ is dimensionless, λ is dimensionless). Equivalent to adding λ/2 ‖θ‖^2 to loss.

softmax(z)_k = exp(z_k) / Σ_j exp(z_j) — output probabilities.

cross-entropy (multi-class) ℓ = − Σ_k y_k log(p_k) — y_k: one-hot or true distribution, p_k: softmax probability. Units: nats (if natural log), unitless for exams.

BatchNorm: x̂ = (x − μ_B) / sqrt(σ_B^2 + ε); y = γ x̂ + β — μ_B, σ_B^2 are batch mean and variance, ε small positive constant.

Worked examples

Example 1 — numerical convolution forward + backward + weight update (exam standard). Given: one input channel x (3×3), one kernel w (2×2), stride 1, no padding. Use cross-correlation forward. Learning rate η = 0.1. Define loss L = Σ_{i,j} y[i,j] (i.e. sum of outputs). Compute forward, gradients and updated w.

  1. Input x = [[1,2,3],[4,5,6],[7,8,9]] (unitless). Kernel w = [[1,0],[0,−1]].
  2. Forward: compute 2×2 output y: y[0,0] = 1·1 + 2·0 + 4·0 + 5·(−1) = 1 − 5 = −4 y[0,1] = 2·1 + 3·0 + 5·0 + 6·(−1) = 2 − 6 = −4 y[1,0] = 4·1 + 5·0 + 7·0 + 8·(−1) = 4 − 8 = −4 y[1,1] = 5·1 + 6·0 + 8·0 + 9·(−1) = 5 − 9 = −4 So L = Σ y = −16.
  3. dL/dy is ones (since ℓ = sum of outputs). Gradient wrt kernel: ∂L/∂w[u,v] = Σ_{i,j} x[i+u, j+v]·δ[i,j]. Sum patches: Sum of top-left positions = 1+2+4+5 = 12 top-right = 2+3+5+6 = 16 bottom-left = 4+5+7+8 = 24 bottom-right = 5+6+8+9 = 28 So ∂L/∂w = [[12,16],[24,28]].
  4. Weight update (SGD): w_new = w − η ∂L/∂w = [[1,0],[0,−1]] − 0.1·[[12,16],[24,28]] = [[1−1.2, 0−1.6], [0−2.4, −1−2.8]] = [[−0.2, −1.6], [−2.4, −3.8]]. Final answer: new kernel [[-0.2, -1.6], [-2.4, -3.8]] (unitless).

Example 2 — minimal NumPy code to compute forward and backward (single-channel) for the above and print values.

import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
w = np.array([[1,0],[0,-1]])
# forward cross-correlation
y = np.empty((2,2), dtype=float)
for i in range(2):
    for j in range(2):
        patch = x[i:i+2, j:j+2]
        y[i,j] = np.sum(patch * w)
print('y =')
print(y)
# backward: dL/dy = ones
dY = np.ones_like(y)
# grad wrt w: sum of patches
dW = np.zeros_like(w, dtype=float)
for u in range(2):
    for v in range(2):
        s = 0.0
        for i in range(2):
            for j in range(2):
                s += x[i+u, j+v] * dY[i,j]
        dW[u,v] = s
print('dW =')
print(dW)
# update
w_new = w - 0.1 * dW
print('w_new =')
print(w_new)

Sample output exactly:

y =
[[-4. -4.]
 [-4. -4.]]
dW =
[[12. 16.]
 [24. 28.]]
w_new =
[[-0.2 -1.6]
 [-2.4 -3.8]]

(You can run this in a Python REPL. All numbers checked.)

Common mistakes

  • Wrong sign in the update (adding instead of subtracting gradient).
  • Using too large learning rate → divergence, or too small → no learning; not trying learning-rate schedules.
  • Not shuffling training data before creating mini-batches → correlated batches can slow convergence.
  • Forgetting dropout/batchnorm behaviour difference between training and evaluation modes (model.train() vs model.eval()).
  • Initialising all weights to zero (breaks symmetry) or using inappropriate variance leading to vanishing/exploding gradients.

For your exam

Types of questions: short definitions, short notes, derivations, diagram-based proofs, numerical updates, small programs (NumPy/PyTorch), and debugging scenarios. What a full-marks answer includes:

  • Definitions of terms (learning rate, epoch, batch, momentum, overfitting). Bold or clearly state symbols.
  • For derivations: show forward equation, explicitly define δ = ∂L/∂y, then derive ∂L/∂w and ∂L/∂x step by step; draw the sliding-kernel diagram and label indices.
  • For numerical problems: write formulas, substitute numbers stepwise, carry units (unitless in most cases), and give final numeric answer bolded.
  • For code questions: provide runnable code, sample input and exact output lines.

Quick check

  1. What does one SGD iteration do?
  2. Give the formula for cross-entropy loss with softmax probabilities.
  3. For a 3×3 input and 2×2 kernel with stride 1, how many output positions are there? Answers: 1) Compute gradient on one mini-batch and update θ ← θ − η ∇_θ L_batch. 2) ℓ = − Σ_k y_k log( exp(z_k)/Σ_j exp(z_j) ). 3) (3−2+1)×(3−2+1) = 2×2 = 4 output positions.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?