Part 02 / Topic 4 of 7
The chain rule
The chain rule says: the derivative of nested functions is the product of their derivatives. f(g(w)) has slope f′(g(w)) · g′(w).
That is exactly the structure of a neural network: layer after layer, function inside function. Backpropagation (Stage 3) is nothing more than the chain rule applied systematically from the loss back to every weight.
You can always check a derivative numerically — nudge the input and watch the output:
# examples/02_a_gradient_by_hand_matches_a.py
# f(w) = (w*x - y)^2 -> df/dw = 2*(w*x - y)*x
x, y, w = 3.0, 12.0, 2.0
f = lambda w: (w * x - y) ** 2
analytic = 2 * (w * x - y) * x
h = 1e-6
numerical = (f(w + h) - f(w - h)) / (2 * h)
print("analytic :", analytic) # analytic : -36.0
print("numerical:", round(numerical, 4)) # numerical: -36.0
The gradient is negative, so increasing w decreases the loss — the model should raise w. (It will, in Part 4.)
🧪 Quick quiz
- For f(w) = (w·x − y)², what is df/dw?
Show the answer
2(w·x − y)·x, by the chain rule. With x=3, y=12, w=2 both the formula and the numerical estimate give −36.
Done here? The practice set for Part 2 — 4 exercises with solutions — is on the part page.