Week 07 · Gradients, Jacobians, and the chain rule

Differentiate a two-input loss and use a numerical derivative to catch a wrong sign or a transposed Jacobian.

Watch on YouTube

Subject contents · Week 6 · Week 8

Differentiate a two-input loss and use a numerical derivative to catch a wrong sign or a transposed Jacobian.

Track how an input changes a model’s error

A model may first convert two measurements into intermediate scores and then combine those scores into one loss. A small change in an input can affect several scores at once. To know how the loss moves, add the effect along each path.

This lesson works that out with two inputs and two intermediate values. You will distinguish a gradient from a Jacobian, calculate the chain rule with actual numbers, and check the answer by perturbing the original inputs. The same reasoning explains how training sends a loss signal back through a sequence of layers.

The idea

A partial derivative changes one input while holding the others fixed. The gradient collects those partial derivatives for a scalar-valued function. For a small step δ, the change in the function is approximately ∇f · δ. The approximation is local, so a large step can behave differently.

For a vector-valued function g, its Jacobian J has one row per output and one column per input. The entry in row i and column j is the derivative of output i with respect to input j. If f(x) = h(g(x)) and h returns a scalar, the column-gradient form of the chain rule is ∇f = Jᵀ∇h. The transpose maps derivatives with respect to the intermediate outputs back to derivatives with respect to the original inputs.

A central finite difference checks the derivative by evaluating the function at x + εeⱼ and x − εeⱼ, where eⱼ is the jth unit vector. Divide the difference by 2ε. For a smooth function, the approximation improves as ε shrinks until rounding starts to dominate.

Trace one column of the chain rule

Here g maps (x, y) to two outputs (a, b), and h turns (a, b) into a scalar loss. The Jacobian entry Jᵢⱼ tells you how much output i changes per small change in input j while the other input is held fixed. Column 1 of J therefore records both paths out of x.

∂f/∂x = (∂h/∂a)(∂a/∂x) + (∂h/∂b)(∂b/∂x).

The symbol ∂ means a partial derivative. In this example, increasing x by a tiny amount increases a twice as much and increases b by the same amount. At a = 4 and b = −1, the loss increases at rate 8 with respect to a and decreases at rate 2 with respect to b. The two contributions are 8 × 2 and (−2) × 1. Add them to get 14.

Writing both input derivatives together gives Jᵀ∇h. If a layer had two inputs and three outputs, J would be 3-by-2. Multiplying its transpose by the three intermediate loss derivatives gives two original input derivatives. This shape check explains the transpose even when the numerical example happens to use a symmetric Jacobian.

Work it out

Let g(x, y) = (2x + y, x − y) and let h(a, b) = a² + b². At (1, 2), g gives (4, −1), so ∇h = (8, −2).

The rows of J are (2, 1) and (1, −1). The first input contributes 2 × 8 + 1 × (−2) = 14. The second contributes 1 × 8 + (−1) × (−2) = 10. The gradient is (14, 10). If x alone increases by 0.01, the linear estimate of the change is 0.14. Direct substitution gives 0.1405. The difference comes from the quadratic term.

A cross-section of the loss at y=2 shows a tangent at x=1 and two nearby evaluations on either side used by the central difference.

At y = 2, the tangent has slope 14 at x = 1. The two marked function values estimate that slope.

Run the Python lab

import numpy as np

J = np.array([[2., 1.], [1., -1.]])
point = np.array([1., 2.])

def loss(matrix, x):
    g = matrix @ x
    return g @ g

def numerical_gradient(matrix, x, eps=1e-5):
    return np.array([
        (loss(matrix, x + eps * e) - loss(matrix, x - eps * e)) / (2 * eps)
        for e in np.eye(len(x))
    ])

analytic = J.T @ (2 * (J @ point))
numeric = numerical_gradient(J, point)
print("analytic gradient:", analytic.tolist())
print("central difference:", np.round(numeric, 6).tolist())
np.testing.assert_allclose(analytic, numeric, atol=1e-8)

# A nonsymmetric Jacobian exposes a missing transpose.
J_asymmetric = np.array([[2., 3.], [1., -1.]])
upstream = 2 * (J_asymmetric @ point)
correct = J_asymmetric.T @ upstream
wrong = J_asymmetric @ upstream
np.testing.assert_allclose(correct, numerical_gradient(J_asymmetric, point))
assert not np.allclose(correct, wrong)
print("nonsymmetric check:", correct.tolist())

Expected output

analytic gradient: [14.0, 10.0]
central difference: [14.0, 10.0]
nonsymmetric check: [30.0, 50.0]

Use finite differences to debug the derivative

The lab changes one coordinate at a time. It evaluates the same loss on either side of the original value and divides the difference by the total step. For the x coordinate, that compares f(1 + ε, 2) with f(1 − ε, 2). It checks the whole composite loss, so it can expose mistakes made in either derivative.

In this example a central difference gives the exact derivative in real arithmetic because the quadratic terms cancel. In floating point, subtracting nearly equal losses loses precision when ε is too small. Compare several step sizes when debugging a derivative. The last part of the lab uses a nonsymmetric Jacobian and checks that replacing Jᵀ with J produces a different result. The original example alone would miss that bug.

Try it yourself

  1. At the same point, approximate the loss change for δ = (0.01, −0.02). Compare with direct substitution.
  2. Replace g’s first output by 2x + 3y. Write the new Jacobian and verify your new gradient.

Check your work. The first-order change is −0.06. Direct substitution gives −0.0591. In the second exercise g gives (8, −1), and the gradient becomes (30, 50).

Further reading

Mathematics for Machine Learning

Subject contents · Week 6 · Week 8