Lesson 7.4 · 9 min read · about 55 min to master at a very slow pace

Backpropagation in Matrix Form

The same algorithm for a whole batch at once: four steps, the shape of every matrix, the element-wise product, how the output error changes with the loss, and a complete NumPy implementation.

Not startedJump to quiz

Forward pass for a batch

One example per row of (), sigmoid hidden units, outputs:

The four steps

  1. Output error . For sigmoid output + MSE: .
  2. Output-layer gradients: , and = the column sums of .
  3. Propagate back: .
  4. Hidden-layer gradients: , and = the column sums of .

is element-wise multiplication. The general rule: weight gradient = (layer input)ᵀ × (error at the layer's output), and the error travels backwards through the transposed weights and the activation derivative.

Check the shapes

QuantityShapeQuantityShape
, matches ✓
, matches ✓
, matches ✓

A gradient always has the same shape as the thing it's the gradient of. If a product doesn't fit, a transpose is missing.

Changing the loss changes only step 1

Output and lossOutput error
Sigmoid + MSE
Linear + MSE
Softmax + cross-entropy
Linear + MAE

In NumPy

def forward(X, p):
    H = sigmoid(X @ p["W1"] + p["b1"])
    y_hat = sigmoid(H @ p["W2"] + p["b2"])
    return y_hat, H

def backward(X, y, p):          # MSE, sigmoid hidden and output
    y_hat, H = forward(X, p)
    N = len(y)
    d2 = 2.0 / N * (y_hat - y) * y_hat * (1 - y_hat)
    d1 = (d2 @ p["W2"].T) * H * (1 - H)
    return {"W2": H.T @ d2, "b2": d2.sum(0),
            "W1": X.T @ d1, "b1": d1.sum(0)}

Stuck? Common doubts

Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.

First passWhy do the biases use a sum over rows?

Every example uses the same bias, and for each one, so the bias gradient is each column of added up over the examples. In code that's d.sum(0).

Cheatsheet

Matrix backprop (4 steps)

from the loss; ; ; . Biases: column sums.

Output error by loss

Sigmoid+MSE: . Linear+MSE: . Softmax+CE: .

See every cheatsheet by category →

Check your understanding

Score 75% or more to master this lesson and earn XP. Answer first, then check.

Q1concept is and is . What is , and its shape?
Q2conceptWhat does mean in ?
Q3applyYou switch the output from sigmoid + MSE to softmax + cross-entropy. Which of the four backprop steps changes?
Q4calculate is and is . What is the shape of ?
Q5conceptHow is the bias gradient computed from ?