Backpropagation

Updated · 8 min read
hardPython 3.13aideep-learningbackpropagationchain-rulegradients

Backpropagation is the method that computes the gradient of the loss for every weight in a neural network. It runs the network forward to get a prediction and a loss, then works backward from the loss, layer by layer, using the chain rule from "Derivatives and Gradients" to find how much each weight contributed to the error. Gradient descent then uses those gradients to update the weights.

Without backpropagation, training a network with millions of weights would be hopelessly slow. With it, all the gradients cost about as much as one extra forward pass.

Forward and Backward Passes

PassDirectionWhat it computes
Forward passInput to outputEach layer's outputs, the prediction and the loss; it keeps the intermediate values
Backward passLoss to inputThe gradient of the loss for each layer's outputs, then for its weights, using the saved values

The chain rule links them: if the loss depends on y, and y depends on h, then dLoss/dh = dLoss/dy × dy/dh. Each layer multiplies the gradient flowing back into it by its own local slope and passes it on.

Example: Backpropagation by Hand

Forward to the loss, then backward through the chain rule

This program runs one forward and one backward pass through a tiny network for one training example, then checks one gradient numerically.

Python
import numpy as np
 
# A tiny network: 2 inputs -> 2 hidden neurons (sigmoid) -> 1 output. One training example.
x, target = np.array([1.0, 2.0]), 1.0
W1 = np.array([[0.1, 0.4], [-0.3, 0.2]])   # W1[i, j]: input i -> hidden neuron j
b1 = np.array([0.0, 0.1])
W2 = np.array([0.5, -0.6])
b2 = 0.2
 
def sigmoid(z):
    return 1 / (1 + np.exp(-z))
 
def loss_of(W1, b1, W2, b2):
    h = sigmoid(x @ W1 + b1)
    return (h @ W2 + b2 - target) ** 2
 
# Forward pass: keep every intermediate value
z1 = x @ W1 + b1
h = sigmoid(z1)
y = h @ W2 + b2
loss = (y - target) ** 2
print(f"Forward: hidden {h.round(4)}  output {y:.4f}  loss {loss:.4f}")
 
# Backward pass: the chain rule, from the loss back to every weight
d_y = 2 * (y - target)                  # dLoss/dy
d_W2 = d_y * h                          # y = h @ W2 + b2
d_b2 = d_y
d_h = d_y * W2                          # how the loss changes with each hidden output
d_z1 = d_h * h * (1 - h)                # sigmoid's slope is h * (1 - h)
d_W1 = np.outer(x, d_z1)                # z1 = x @ W1 + b1
d_b1 = d_z1
print("Gradient for W2:", d_W2.round(4))
print("Gradient for W1:", d_W1.round(4).tolist())
 
# Check one gradient numerically: nudge W1[1, 0] a tiny bit and watch the loss
eps = 1e-6
W1_up = W1.copy()
W1_up[1, 0] += eps
numeric = (loss_of(W1_up, b1, W2, b2) - loss) / eps
print(f"W1[1, 0]: backpropagation {d_W1[1, 0]:.6f}  numerical {numeric:.6f}")
Output
Forward: hidden [0.3775 0.7109]  output -0.0378  loss 1.0770
Gradient for W2: [-0.7836 -1.4756]
Gradient for W1: [[-0.2439, 0.2559], [-0.4878, 0.5118]]
W1[1, 0]: backpropagation -0.487773  numerical -0.487773

Explanation: Follow the backward pass line by line:

  1. d_y = 2 × (y - target): the loss is (y - target)², so its slope is 2 × (y - target) = 2 × (-0.0378 - 1) ≈ -2.08. Negative means a bigger y would lower the loss.
  2. d_W2 = d_y × h: each output weight's gradient is the error signal times the hidden value it multiplies.
  3. d_h = d_y × W2: the error flows back to each hidden neuron through its weight.
  4. d_z1 = d_h × h × (1 - h): it passes back through sigmoid, whose slope is h × (1 - h).
  5. d_W1 = np.outer(x, d_z1): each first-layer weight's gradient is its input times the error signal of the neuron it feeds.

The numerical check nudges one weight by 0.000001 and measures how the loss changes. Both methods give −0.487773: the chain rule is right. Notice the second row of d_W1 is exactly twice the first, because the second input (2) is twice the first (1).

Example: Training XOR with Backpropagation

The previous lesson's XOR network had hand-picked weights. This program starts from random weights and lets backpropagation and gradient descent find them.

Python
import numpy as np
 
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
t = np.array([0, 1, 1, 0], dtype=float)                 # XOR
 
rng = np.random.default_rng(1)
W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros(4)          # 2 inputs -> 4 hidden neurons
W2, b2 = rng.normal(0, 1, 4), 0.0                       # 4 hidden -> 1 output
 
def sigmoid(z):
    return 1 / (1 + np.exp(-z))
 
learning_rate = 1.0
for step in range(1, 3001):
    h = sigmoid(X @ W1 + b1)                            # forward
    y = sigmoid(h @ W2 + b2)
    loss = -np.mean(t * np.log(y) + (1 - t) * np.log(1 - y))   # cross-entropy
 
    d_z2 = (y - t) / len(X)                             # backward (sigmoid + cross-entropy simplify to this)
    d_W2, d_b2 = h.T @ d_z2, d_z2.sum()
    d_z1 = np.outer(d_z2, W2) * h * (1 - h)
    d_W1, d_b1 = X.T @ d_z1, d_z1.sum(axis=0)
 
    W1 -= learning_rate * d_W1                          # gradient descent on every weight
    b1 -= learning_rate * d_b1
    W2 -= learning_rate * d_W2
    b2 -= learning_rate * d_b2
    if step in (1, 100, 1000, 3000):
        print(f"step {step:4}: loss {loss:.4f}  outputs {y.round(2)}")
Output
step    1: loss 0.7452  outputs [0.65 0.69 0.63 0.67]
step  100: loss 0.6836  outputs [0.49 0.55 0.47 0.51]
step 1000: loss 0.0141  outputs [0.01 0.99 0.99 0.02]
step 3000: loss 0.0029  outputs [0. 1. 1. 0.]

Explanation: Every step runs a forward pass on all four examples, a backward pass to get all the gradients, and a gradient descent update. The loss is cross-entropy, the standard loss for yes/no outputs; combined with a sigmoid output, its gradient simplifies to y - t. At step 1 the random network outputs about 0.65 for everything. At step 100 it's still unsure, then it finds the pattern: by step 3,000 the outputs are 0, 1, 1, 0, exactly XOR, and the loss is 0.0029. The network learned its own hidden features.

Problems Backpropagation Can Hit

ProblemDescriptionCommon fix
Vanishing gradientsGradients shrink as they pass back through many layers, so early layers barely learnReLU activations, careful starting weights, residual connections
Exploding gradientsGradients grow huge and training blows upGradient clipping, lower learning rate
Dead ReLUsNeurons stuck outputting 0 get no gradientLower learning rate, variants like Leaky ReLU
Local minima and plateausThe loss stops falling for a while, like steps 1 to 100 aboveRandom starts, momentum, optimizers like Adam

Common Mistakes

Confusing backpropagation with gradient descent. Backpropagation computes the gradients; gradient descent uses them to update the weights.

Forgetting the activation's slope. Each layer's gradient must pass through its activation's derivative, like h × (1 - h) for sigmoid.

Not checking gradients. When writing a backward pass by hand, compare with a numerical gradient, as above.

Interview Corner

What is backpropagation?

An efficient way to compute the gradient of the loss for every parameter, by applying the chain rule backward from the loss through each layer, reusing values saved during the forward pass.

What is the vanishing gradient problem?

Gradients get smaller as they are multiplied back through many layers, so early layers learn very slowly. Sigmoid's small slopes make it worse; ReLU, good initialization and residual connections help.

Practice

Exercise: check every gradient. Extend the numerical check in the first program to all four entries of W1 and both entries of W2. Do they all match backpropagation to six decimal places?

Check your understanding:

  1. What does the forward pass save, and why?
  2. Why is the second row of d_W1 twice the first?
  3. What is the difference between backpropagation and gradient descent?

Quick check: backpropagation

4 questions
1Which rule does backpropagation apply?
2What did the numerical check show?
3What did the XOR network output after 3,000 steps?
4What does backpropagation produce?

Key Takeaways

Quick reference

StepCode (sigmoid layer)
Output error (squared loss)d_y = 2 * (y - target)
Output weightsd_W2 = d_y * h
Back through sigmoidd_z1 = (d_y * W2) * h * (1 - h)
First-layer weightsd_W1 = np.outer(x, d_z1)

Was this tutorial helpful?

Lesson 136 of 186