Computer Engineering 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.

Backpropagation training

Backpropagation is the algorithm to compute gradients for training feedforward neural networks (multilayer perceptrons) using the chain rule so weights and biases are updated by gradient descent.

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

Backpropagation is the standard method an engineer uses to compute how to change neural-network weights so the network learns from data. You will use it when training multilayer perceptrons (MLPs) in pattern recognition, control, or any application where a differentiable neural model is fitted to examples.

Key ideas

Start from first principles and definitions.

  • Artificial neuron: a unit that computes a weighted sum plus a bias, then applies an activation function to produce an output. If the pre-activation is z and activation function is σ, the neuron output is a = σ(z).
  • Layer: a collection of neurons that take the same input vector and produce an output vector. Layers are stacked to form a feedforward network (no cycles).
  • Weights and biases: parameters of the network; weights multiply inputs, biases shift the pre-activation.
  • Loss (cost) function: a scalar measure of error over network output(s) and target(s). Common choice: mean squared error (MSE) for regression and simple theory examples.
  • Gradient: vector of partial derivatives of the loss with respect to parameters; it points in the direction of steepest increase. To reduce loss we move parameters opposite to the gradient.
  • Gradient descent: update rule for parameters w ← w − η·∇C, where η is the learning rate (step size).
  • Epoch, batch, minibatch, stochastic: one epoch = one full pass over the training set; batch = full dataset used to compute gradient; minibatch = subset; stochastic (SGD) uses batch size 1. In practice, the term “SGD” is often used to mean minibatch gradient descent.
  • Backpropagation: efficient algorithm to compute gradients for all weights and biases by applying the chain rule layer-by-layer from output to input. It avoids repeated work by reusing intermediate derivatives.

Precise statements and derivation (standard MLP with L layers): Label layers 1..L, with layer L being output. Let a^0 = x (input column vector). For layer l (1 ≤ l ≤ L):

  • Pre-activation: z^l = W^l a^{l-1} + b^l (column vector), where W^l is the weight matrix of layer l and b^l is the bias column vector.
  • Activation: a^l = σ^l(z^l) applied elementwise (σ^l may differ between layers).

Define scalar cost C(a^L, y) for a given target y. We need ∂C/∂W^l and ∂C/∂b^l. Using the chain rule, derive the error term δ^l defined by

  • Output-layer error: δ^L = ∂C/∂a^L ⊙ σ'^L(z^L) (here ⊙ is elementwise product).
  • Backpropagation recurrence: for l = L-1, L-2, ..., 1, δ^l = ( (W^{l+1})^T δ^{l+1} ) ⊙ σ'^l(z^l).

Then the exact gradients are

  • ∂C/∂b^l = δ^l (vector of same size as b^l),
  • ∂C/∂W^l = δ^l (a^{l-1})^T (matrix outer product: each element (i,j) = δ^l_i · a^{l-1}_j).

Assumptions behind the above: activations σ are differentiable; cost is differentiable in a^L. This derivation is the vectorised chain rule; draw the computational graph and propagate sensitivities backward. For piecewise-linear activations like ReLU, use a subgradient at z=0 (commonly take σ'(0)=0) and backprop still applies.

What to draw (diagram guidance for an exam):

  • Draw a 3-layer MLP: input layer with labeled inputs x1, x2; hidden layer with two neurons (draw circles), label their pre-activations z^1_1, z^1_2 and activations a^1_1, a^1_2; output layer single neuron with z^2_1, a^2_1. Draw arrows for weights W^1 and W^2 and biases b^1 and b^2. Annotate dimensions: W^1 is 2×2, W^2 is 1×2. Show forward pass equations next to arrows and then on the right show backward pass: δ^2 computed from ∂C/∂a^2, then δ^1 = (W^2)^T δ^2 ⊙ σ'(z^1).

Why vectorised form helps: it computes gradients for all neurons in a layer in one matrix multiply; complexity grows linearly in number of edges.

Practical considerations (short definitions):

  • Vanishing gradient: gradients get very small when σ' is small (e.g., sigmoid/tanh for large |z|). Causes slow learning for deep layers.
  • Exploding gradient: gradients grow very large; numerical instability.
  • Weight initialization: choose initial weights (e.g., Xavier/He) to keep activations and gradients in stable ranges.
  • Momentum, RMSProp, Adam: algorithmic variants that modify pure gradient descent to speed convergence or stabilise updates.
  • Regularization (weight decay): add an L2 penalty λ/2 ∑_l ||W^l||_F^2 so gradients become ∂C/∂W^l ← ∂C/∂W^l + λ W^l (biases often not regularized). L1 regularization adds λ · sign(W^l).

Formulas

z^l = W^l a^{l-1} + b^l where z^l is pre-activation vector (unitless), W^l is weight matrix (unitless), a^{l-1} is previous layer activation vector (unitless), b^l bias vector (unitless). Applies to forward pass.

a^l = σ^l(z^l) where σ^l is the activation function (elementwise). Unitless. Applies after each layer.

C = 1/2 ||y - a^L||^2 (squared error for one sample). C is unitless. For vector output of size n, the per-sample MSE is (1/n) ||y - a^L||^2. Use this C for derivations if using SSE; its derivative is ∂C/∂a^L = a^L − y.

δ^L = ∂C/∂a^L ⊙ σ'^L(z^L) output-layer error vector. Unitless. Applies for differentiable cost and activation. For sigmoid with binary cross-entropy, or softmax with cross-entropy, this simplifies to δ^L = a^L − y (no σ' factor), which is standard for classification.

δ^l = (W^{l+1})^T δ^{l+1} ⊙ σ'^l(z^l) backprop recurrence for hidden layers. Unitless.

∂C/∂b^l = δ^l gradient w.r.t biases; same shape as b^l.

∂C/∂W^l = δ^l (a^{l-1})^T gradient w.r.t weights; matrix outer product; element (i,j) = δ^l_i · a^{l-1}_j.

w ← w - η · ∂C/∂w weight update in gradient descent. η (learning rate) is unitless.

Notes: In minibatch training, compute gradients for each sample then average over the minibatch before applying update.

Worked examples

Example 1 — manual numerical backprop (one sample) Network: 2 inputs → 2 hidden → 1 output. Activation: sigmoid σ(z)=1/(1+e^{-z}). Use MSE cost C = 1/2 (y − a^L)^2. Given:

  • Input x = [1.0, 0.5]^T.
  • Weights W^1 = [[0.1, -0.2], [0.4, 0.2]] (rows are hidden neurons), b^1 = [0.0, 0.0]^T.
  • W^2 = [0.3, -0.3] (row vector for single output), b^2 = 0.0.
  • Target y = 0.6. Step 1: forward pass
  • z^1 = W^1 x + b^1 = [0.0, 0.5]^T.
  • a^1 = σ(z^1) = [0.5, 0.6224593312]^T.
  • z^2 = W^2 · a^1 + b^2 = 0.3·0.5 + (−0.3)·0.6224593312 = −0.0367377994.
  • a^2 = σ(z^2) ≈ 0.490817 (approx).
  • Cost C = 1/2 (0.6 − 0.490817)^2 ≈ 0.005958 (approx). Step 2: backward pass
  • δ^2 = (a^2 − y) · σ'(z^2) with σ'(z)=a(1−a). Compute a^2 − y ≈ −0.109183, σ'(z^2) ≈ 0.249999 ⇒ δ^2 ≈ −0.0272955.
  • Gradients for W^2: ∂C/∂w2_1 = a^1_1·δ^2 ≈ 0.5·(−0.0272955) = −0.0136478; ∂C/∂w2_2 ≈ 0.6224593·(−0.0272955) ≈ −0.0169890.
  • ∂C/∂b^2 = δ^2 ≈ −0.0272955.
  • Backprop to hidden: for each hidden neuron j, δ^1_j = (sum_k w^2_k · δ^2_k)·σ'(z^1_j). Here W^2 has elements [0.3, −0.3], so δ^1 ≈ [0.3·δ^2, (−0.3)·δ^2] ⊙ [0.25, 0.2350037] ≈ [−0.00204716, 0.00192263].
  • Gradients for W^1: ∂C/∂w1_11 = δ^1_1·x_1 ≈ −0.00204716; ∂C/∂w1_12 = δ^1_1·x_2 ≈ −0.00102358; ∂C/∂w1_21 ≈ 0.00192263; ∂C/∂w1_22 ≈ 0.00096131. Step 3: one gradient-descent update with η = 0.5
  • Updated W^2 ≈ [0.30682388, −0.2915055], b^2 ≈ 0.01364776.
  • Updated W^1 ≈ [[0.10102358, −0.19948821], [0.39903869, 0.19951934]], b^1 ≈ [0.00102358, −0.00096131]. (Each numerical value above is approximate; verify with a calculator or the Python program.)

Example 2 — Python program that computes the forward pass, gradients and one update for the same network (complete code). Run this program to confirm the numbers above.

# backprop_step.py  -- computes gradients for one sample and updates weights
import math

def sigmoid(x):
    return 1.0 / (1.0 + math.exp(-x))

def sigmoid_prime(x):
    s = sigmoid(x)
    return s * (1.0 - s)

# given data
x = [1.0, 0.5]
y = 0.6

# weights and biases (same as manual example)
W1 = [[0.1, -0.2], [0.4, 0.2]]  # 2x2
b1 = [0.0, 0.0]
W2 = [0.3, -0.3]                # 1x2
b2 = 0.0

# forward pass
z1 = [W1[0][0]*x[0] + W1[0][1]*x[1] + b1[0],
      W1[1][0]*x[0] + W1[1][1]*x[1] + b1[1]]
a1 = [sigmoid(z1[0]), sigmoid(z1[1])]
z2 = W2[0]*a1[0] + W2[1]*a1[1] + b2
a2 = sigmoid(z2)

# cost derivative (MSE)
dC_da2 = a2 - y
# backprop
delta2 = dC_da2 * sigmoid_prime(z2)

grad_W2 = [delta2 * a1[0], delta2 * a1[1]]
grad_b2 = delta2

# hidden deltas
# W2 is a row [w21, w22], so W2^T * delta2 = [w21*delta2, w22*delta2]
delta1 = [W2[0] * delta2 * sigmoid_prime(z1[0]),
          W2[1] * delta2 * sigmoid_prime(z1[1])]

grad_W1 = [[delta1[0] * x[0], delta1[0] * x[1]],
           [delta1[1] * x[0], delta1[1] * x[1]]]
grad_b1 = delta1

# update with learning rate
eta = 0.5
W2 = [W2[i] - eta * grad_W2[i] for i in range(2)]
b2 = b2 - eta * grad_b2
for i in range(2):
    for j in range(2):
        W1[i][j] = W1[i][j] - eta * grad_W1[i][j]
    b1[i] = b1[i] - eta * grad_b1[i]

# print results
print('a1 =', a1)
print('z2 =', z2, 'a2 =', a2)
print('delta2 =', delta2)
print('grad_W2 =', grad_W2)
print('grad_b2 =', grad_b2)
print('delta1 =', delta1)
print('grad_W1 =', grad_W1)
print('Updated W2 =', W2)
print('Updated b2 =', b2)
print('Updated W1 =', W1)
print('Updated b1 =', b1)

Sample output (approximate; run to get exact floats):

a1 = [0.5, 0.6224593312018546] z2 = -0.03673779936055638 a2 = 0.4908169... delta2 = -0.0272955... grad_W2 = [-0.0136478..., -0.0169890...] grad_b2 = -0.0272955... delta1 = [-0.00204716..., 0.00192263...] grad_W1 = [[-0.00204716..., -0.00102358...], [0.00192263..., 0.00096131...]] Updated W2 = [0.30682388..., -0.2915055...] Updated b2 = 0.01364776... Updated W1 = [[0.10102358..., -0.19948821...], [0.39903869..., 0.19951934...]] Updated b1 = [0.00102358..., -0.00096131...]

(Exact decimal digits depend on your Python float print formatting; values above match the manual worked example to the shown precision.)

Example 2 is intentionally a single-step example so you can check every derivative and update by hand or by running the program.

Common mistakes

  • Using ∂C/∂a instead of ∂C/∂z at the output when computing δ^L; remember δ^L = (∂C/∂a^L) ⊙ σ'(z^L).
  • Forgetting to average gradients over minibatch (or forgetting factor 1/N) when using batch-based losses.
  • Confusing elementwise product (⊙) with matrix multiplication.
  • Omitting bias gradients (they are simply δ^l summed over examples).

For your exam

Common question types and what full answers include:

  • Definitions: define backpropagation, δ (error term), and gradient descent. Include shapes and assumptions (differentiability).
  • Short notes: explain vanishing/exploding gradients and remedies (ReLU, proper init, batch norm, residual connections — refer to Deep Learning topics).
  • Derivation: derive the backprop recurrence δ^l = (W^{l+1})^T δ^{l+1} ⊙ σ'(z^l). Show chain rule steps and where matrix multiplication appears. Provide vectorised and scalar forms.
  • Numerical: perform forward pass, compute cost, compute δ for each neuron, gradients, and one update (show each arithmetic step and units if any). Draw the network and label z and a values.
  • Programming: write a short function that computes forward and backward passes for one minibatch and updates parameters. Show test run outputs.

A full-marks derivation must show: (i) expression for z^l and a^l, (ii) ∂C/∂W^l in terms of δ^l and a^{l-1}, (iii) explicit chain-rule step to reach δ recurrence, and (iv) a worked small numeric example or a clear diagram.

Quick check

  1. What is the definition of δ^l (error term) for an output layer?
  2. Write the formula for ∂C/∂W^l in vector form.
  3. Name two practical problems in deep networks caused by repeated multiplication of small or large derivatives.

Answers: 1) δ^L = ∂C/∂a^L ⊙ σ'^L(z^L). 2) ∂C/∂W^l = δ^l (a^{l-1})^T. 3) Vanishing gradient and exploding gradient.

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

Stuck on something here?