Three gears are linked together. Gear A turns gear B twice as fast, and gear B turns gear C three times as fast. How fast does C turn compared with A? You don't need a formula: 2 × 3 = 6 times as fast. When changes pass along a chain, the rates multiply. That one idea is the chain rule, and it's the most important derivative rule in machine learning: backpropagation, the algorithm that trains every neural network, is the chain rule applied over and over.
So far you've differentiated functions of x directly. But most real functions are functions of functions: e^(−x²) puts x² inside an exponential, and a model's loss puts the weight inside a prediction, which sits inside an error. This lesson explains the chain rule step by step: spotting the inside and outside functions, multiplying their rates, many worked examples checked in Python, and a chain of three steps that previews backpropagation.
What you need first: derivative rules, derivatives of exponentials and logarithms and what is a function? (especially functions inside functions).
Key terms
- Composite function: a function inside another function, such as (3x + 1)², where 3x + 1 is put inside "square it".
- Inner function: the part applied first (3x + 1).
- Outer function: the part applied to the result (squaring).
- Chain rule: the derivative of a composite is the outer function's slope (at the inner value) times the inner function's slope.
A weather balloon
A weather balloon rises at 2 metres per second. The air gets colder as you go up: about 0.0065 °C colder per metre. How fast is the temperature at the balloon changing, per second?
- Height changes with time: dh/dt = 2 m/s.
- Temperature changes with height: dT/dh = −0.0065 °C per m.
- Temperature changes with time: dT/dt = dT/dh × dh/dt = −0.0065 × 2 = −0.013 °C per second.
The units show why multiplying is right: (°C per metre) × (metres per second) = °C per second. The metres cancel, just like the dh's look as though they cancel in the notation:
dT/dt = dT/dh × dh/dt
The fraction-like notation isn't a coincidence. Each derivative is a rate, and a rate of a rate multiplies through.
The chain rule
For y = f(g(x)), call the inside u = g(x). Then:
dy/dx = dy/du × du/dx, or in the other notation, (f(g(x)))′ = f′(g(x)) × g′(x)
Read it as "the slope of the outside, evaluated at the inside, times the slope of the inside". Recipe:
- Spot the inside: what's calculated first? Call it u.
- Differentiate the outside as if u were just a variable.
- Differentiate the inside with respect to x.
- Multiply, and put u back in terms of x.
Worked examples
Example 1: y = (3x + 1)²
- Inside: u = 3x + 1. Outside: y = u².
- dy/du = 2u.
- du/dx = 3.
- dy/dx = 2u × 3 = 6u = 6(3x + 1).
Check by expanding: (3x + 1)² = 9x² + 6x + 1, whose derivative is 18x + 6 = 6(3x + 1). The same.
Example 2: y = e^(−x²), the bell-shaped curve behind the normal distribution.
- Inside: u = −x². Outside: y = eᵘ.
- dy/du = eᵘ.
- du/dx = −2x.
- dy/dx = eᵘ × (−2x) = −2x e^(−x²).
Example 3: y = ln(1 + x²)
- Inside: u = 1 + x². Outside: y = ln u.
- dy/du = 1/u.
- du/dx = 2x.
- dy/dx = 2x ÷ (1 + x²).
Example 4: y = √(x² + 9)
- Inside: u = x² + 9. Outside: y = u^(1/2).
- dy/du = ½u^(−1/2).
- du/dx = 2x.
- dy/dx = ½(x² + 9)^(−1/2) × 2x = x ÷ √(x² + 9).
Check all four numerically:
import numpy as np
import matplotlib.pyplot as plt
def slope_at(f, x, h=1e-6):
return (f(x + h) - f(x - h)) / (2 * h)
examples = [
("(3x + 1)²", lambda x: (3 * x + 1) ** 2, lambda x: 6 * (3 * x + 1)),
("e^(−x²)", lambda x: np.exp(-x ** 2), lambda x: -2 * x * np.exp(-x ** 2)),
("ln(1 + x²)", lambda x: np.log(1 + x ** 2), lambda x: 2 * x / (1 + x ** 2)),
("√(x² + 9)", lambda x: np.sqrt(x ** 2 + 9), lambda x: x / np.sqrt(x ** 2 + 9)),
]
for name, f, rule in examples:
x = 1.5
print(f"{name:12} at x = {x}: numeric {slope_at(f, x):9.5f}, chain rule {rule(x):9.5f}")
(3x + 1)² at x = 1.5: numeric 33.00000, chain rule 33.00000
e^(−x²) at x = 1.5: numeric -0.31620, chain rule -0.31620
ln(1 + x²) at x = 1.5: numeric 0.92308, chain rule 0.92308
√(x² + 9) at x = 1.5: numeric 0.44721, chain rule 0.44721
See what the derivative of the bell curve says:
x = np.linspace(-3, 3, 300)
fig, ax = plt.subplots(figsize=(7.5, 4.5))
ax.plot(x, np.exp(-x ** 2), color="black", linewidth=2.5, label="y = e^(−x²)")
ax.plot(x, -2 * x * np.exp(-x ** 2), color="#c2410c", linewidth=2.5, label="dy/dx = −2x e^(−x²)")
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xlabel("x")
ax.set_title("The bell curve and its slope")
ax.legend(loc="upper left")
plt.show()
The slope is positive where the bell rises, zero at the top, and negative where it falls, and it's steepest about 0.7 either side of the middle.
The chain rule and a model's error
A model with one weight predicts wx for an input x, and its squared error for a true value y is:
L = (wx − y)²
Here the weight is buried two layers deep: inside the prediction, which is inside the error. Chain it:
- Inside: u = wx − y (the prediction error). Outside: L = u².
- dL/du = 2u.
- du/dw = x (y and x are fixed numbers from the data; only w changes).
- dL/dw = 2(wx − y) × x.
Read the answer as a story: "twice the error, times the input". A big error gives a big push; a big input gives the weight a lot of influence, so it gets a big push too. This is exactly the gradient used in linear regression from scratch and in gradient descent.
x_in, y_true = 3.0, 7.0
loss = lambda w: (w * x_in - y_true) ** 2
for w in [1.0, 2.0, 2.5]:
print(f"w = {w}: error {w * x_in - y_true:+.1f}, chain rule 2(wx − y)x = {2 * (w * x_in - y_true) * x_in:+.2f}, numeric {slope_at(loss, w):+.2f}")
w = 1.0: error -4.0, chain rule 2(wx − y)x = -24.00, numeric -24.00
w = 2.0: error -1.0, chain rule 2(wx − y)x = -6.00, numeric -6.00
w = 2.5: error +0.5, chain rule 2(wx − y)x = +3.00, numeric +3.00
Longer chains: a preview of backpropagation
The chain rule works for any number of links: multiply all the rates along the chain. Here's a tiny "neural network" with one weight, a sigmoid and a squared error:
z = w × x → p = σ(z) → L = (p − y)²
Each link has a simple slope:
| Link | Slope |
|---|---|
| z = w × x | dz/dw = x |
| p = σ(z) | dp/dz = p(1 − p) (see the next lesson) |
| L = (p − y)² | dL/dp = 2(p − y) |
dL/dw = dL/dp × dp/dz × dz/dw = 2(p − y) × p(1 − p) × x
import matplotlib.patches as patches
fig, ax = plt.subplots(figsize=(10, 2.8))
boxes = [("w", 0.5), ("z = w·x", 3.0), ("p = σ(z)", 5.5), ("L = (p − y)²", 8.0)]
for label, cx in boxes:
ax.add_patch(patches.FancyBboxPatch((cx - 0.9, 0.9), 1.8, 0.8, boxstyle="round,pad=0.05", facecolor="#dbeafe", edgecolor="#1f5fbf"))
ax.text(cx, 1.3, label, ha="center", va="center", fontsize=12)
mids = [(0.5, 3.0, "dz/dw = x"), (3.0, 5.5, "dp/dz = p(1 − p)"), (5.5, 8.0, "dL/dp = 2(p − y)")]
for x0, x1, slope in mids:
ax.annotate("", xy=(x1 - 0.95, 1.45), xytext=(x0 + 0.95, 1.45), arrowprops=dict(arrowstyle="->", color="black"))
ax.annotate("", xy=(x0 + 0.95, 1.1), xytext=(x1 - 0.95, 1.1), arrowprops=dict(arrowstyle="->", color="#c2410c"))
ax.text((x0 + x1) / 2, 0.55, slope, ha="center", color="#c2410c", fontsize=11)
ax.text(4.25, 2.05, "forward: calculate values →", ha="center", fontsize=11)
ax.text(4.25, 0.1, "← backward: multiply the slopes", ha="center", fontsize=11, color="#c2410c")
ax.set_xlim(-0.6, 9.2)
ax.set_ylim(0, 2.3)
ax.axis("off")
plt.show()
The forward pass calculates z, p and L. The backward pass multiplies the slopes from the loss back to the weight. Compute it with real numbers and check:
def sigmoid(z):
return 1 / (1 + np.exp(-z))
x_in, y_true, w = 2.0, 1.0, 0.3
z = w * x_in # forward pass
p = sigmoid(z)
L = (p - y_true) ** 2
print(f"forward: z = {z:.3f}, p = {p:.4f}, L = {L:.4f}")
dL_dp = 2 * (p - y_true) # backward pass: one slope per link
dp_dz = p * (1 - p)
dz_dw = x_in
dL_dw = dL_dp * dp_dz * dz_dw
print(f"backward: dL/dp = {dL_dp:.4f}, dp/dz = {dp_dz:.4f}, dz/dw = {dz_dw:.1f}")
print(f"chain rule dL/dw = {dL_dw:.5f}")
full = lambda w: (sigmoid(w * x_in) - y_true) ** 2
print(f"numeric dL/dw = {slope_at(full, w):.5f}")
forward: z = 0.600, p = 0.6457, L = 0.1256
backward: dL/dp = -0.7087, dp/dz = 0.2288, dz/dw = 2.0
chain rule dL/dw = -0.32427
numeric dL/dw = -0.32427
The chain rule and the numerical slope agree to five decimal places: −0.32427. The gradient is negative, so increasing w would lower the loss, which makes sense because the prediction 0.6457 is below the true label 1. A real network does exactly this, with millions of weights: one forward pass, then one backward pass that multiplies local slopes and reuses them, so every weight gets its gradient at about the cost of two passes.
Common mistakes
- Forgetting the inside's slope. d/dx (e^(3x)) is 3e^(3x), not e^(3x). The "× inner slope" is the step most often missed.
- Changing the inside when differentiating the outside. In d/dx (x² + 1)⁵, the outside's slope is 5(x² + 1)⁴: keep the inside as it is.
- Picking the wrong inside. Ask "what would I calculate first with a calculator?" That's the inside.
- Stopping one link early. In a chain of three, multiply all three slopes.
Practice
- Differentiate y = (2x − 5)⁴.
Show the answer
Inside u = 2x − 5 (slope 2), outside u⁴ (slope 4u³). dy/dx = 4(2x − 5)³ × 2 = 8(2x − 5)³.
- Differentiate y = e^(5x) and y = ln(3x). What's surprising about the second?
Show the answer
d/dx e^(5x) = 5e^(5x). d/dx ln(3x) = (1/(3x)) × 3 = 1/x. The 3 cancels: ln(3x) = ln 3 + ln x, and ln 3 is a constant, so it has the same slope as ln x.
- Differentiate y = 1 ÷ (1 + x²), writing it as (1 + x²)⁻¹, and check at x = 1 in Python.
Show the answer
Outside u⁻¹ (slope −u⁻²), inside 1 + x² (slope 2x). dy/dx = −2x ÷ (1 + x²)². At x = 1: −2 ÷ 4 = −0.5.
print(round(slope_at(lambda x: 1 / (1 + x ** 2), 1), 5))
-0.5
- For L = (wx − y)² with x = 2, y = 10 and w = 3, find dL/dw. Should gradient descent increase or decrease w?
Show the answer
dL/dw = 2(wx − y)x = 2(6 − 10)(2) = −16. It's negative, so increasing w lowers the loss: gradient descent increases w (w − lr × (−16)). That makes sense: the prediction 6 is below the true 10.
Interview questions
What is the chain rule, and why does it matter for deep learning?
For y = f(g(x)), dy/dx = f′(g(x)) × g′(x): multiply the rates of change along the chain. A neural network is a long chain of functions, so the gradient of the loss with respect to any weight is a product of the local slopes along the path from that weight to the loss. Backpropagation computes those products efficiently, starting from the loss and working backwards.
Why can multiplying many slopes cause vanishing or exploding gradients?
The gradient for an early layer is a product of many local slopes. If they're mostly below 1 (the sigmoid's slope is at most 0.25), the product shrinks towards zero and early layers barely learn; if they're mostly above 1, it grows huge. ReLU activations, careful initialisation, normalisation and residual connections all help keep the product stable.
Key takeaways
- When changes pass along a chain, the rates multiply: dy/dx = dy/du × du/dx.
- Recipe: spot the inside, differentiate the outside (keeping the inside), times the inside's slope.
- e^(−x²) → −2x e^(−x²); ln(1 + x²) → 2x ÷ (1 + x²); (3x + 1)² → 6(3x + 1).
- For a squared error, dL/dw = 2 × error × input.
- Backpropagation is the chain rule: forward pass for values, backward pass multiplying slopes.
Frequently asked questions
How do I know when to use the chain rule?
Whenever there's something other than plain x inside a function: (3x + 1)², e^(2x), ln(x² + 1), sin(5x). If you'd need two or more calculator steps in order, it's a chain.
Is dy/du × du/dx really cancelling fractions?
Not literally, because derivatives aren't fractions. But they are limits of fractions (tiny changes divided by tiny changes), which is why the cancelling picture gives the right answer and is a reliable way to remember the rule.
Does the chain rule work with many inputs?
Yes. With many inputs, each path from a weight to the loss contributes a product of slopes, and the contributions from different paths add up. That's the multivariable chain rule, which builds on partial derivatives later in this course.
What to learn next
- Find the slope of the sigmoid in derivative of the sigmoid function, the next lesson.
- See the error gradient at work in linear regression from scratch.
- Review the rules for each link in derivatives of exponentials and logarithms.