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.
Forward pass for a batch
One example per row of (), sigmoid hidden units, outputs:
The four steps
- Output error . For sigmoid output + MSE: .
- Output-layer gradients: , and = the column sums of .
- Propagate back: .
- 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
| Quantity | Shape | Quantity | Shape |
|---|---|---|---|
| , 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 loss | Output 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)
Output error by loss
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.