Gradients of Vector-Valued Functions
The previous page ended with a row. This page stacks of them.
That is genuinely all the new content — and the fact that it is so little is the payoff for §5.2’s row convention. Under the column convention this page would need transposes; under the row convention the gradient of a function with outputs is just gradients written one above the other, and the shape rule stays (rows are outputs, columns are inputs) all the way up.
What is new is what the resulting matrix means. Its determinant is a volume magnifier, which is where Chapter 6’s change-of-variables formula comes from. And the chain rule becomes an honest matrix product, which is where backpropagation comes from.
What you’ll learn
Section titled “What you’ll learn”- Definition 5.6: the Jacobian of as an matrix.
- The numerator layout the book uses, its transpose the denominator layout, and how to tell which one a source is using.
- Example 5.9: , exactly — the identity every linear layer’s backward pass is.
- The Jacobian determinant as the factor by which areas and volumes scale, verified by counting rather than quoting §4.1.
- Why that is only a local statement for a nonlinear map, measured — and what happens where the determinant vanishes.
- Example 5.10 and 5.11: the chain rule as a matrix product, and the least-squares gradient that Chapter 9 is built on.
Intuition: one row per output
Section titled “Intuition: one row per output”A function with one output has one thing to say about how it changes: a single gradient row. A function with outputs has things to say, one per output coordinate, and each is a row.
Stack them and you have a matrix. Row is “how output responds to each input”; column is “how input affects each output”. Both readings are useful, and they are the two ways to slice the same object.
The determinant then answers a question neither row nor column does: how much does the map stretch space? A unit square in the domain lands on a parallelogram in the codomain, and is the ratio of their areas.
flowchart TD F["f: ℝⁿ → ℝᵐ
m outputs, n inputs"] F --> ROWS["one gradient ROW per output:
∂fᵢ/∂x = [∂fᵢ/∂x₁ … ∂fᵢ/∂xₙ]"] ROWS --> J["Jacobian J ∈ ℝᵐˣⁿ
Def 5.6, Eq 5.58
rows = outputs, cols = inputs"] J --> NUM["numerator layout
(the book's choice)"] NUM -->|"transpose"| DEN["denominator layout
(also common — check which)"] J --> SPECIAL["special cases:
m = 1 → the row of §5.2
n = 1 → a column
f(x) = Ax → J = A exactly"] J --> DET["det J: the volume magnifier
Eq 5.58-5.61, Figure 5.5"] DET --> CV["Ch 6 §6.7
change of variables"] DET --> ZERO["det J = 0: the map folds
— locally not invertible"] J --> CHAIN["chain rule as a matrix product
d(f∘g)/dt = (∂f/∂x)(∂x/∂t)"] CHAIN --> LS["Example 5.11: ∂L/∂θ = −2eᵀΦ
the gradient Ch 9 runs on"] CHAIN --> BP["§5.6 backpropagation"]
The math
Section titled “The math”The Jacobian
Section titled “The Jacobian”As a special case, a function has a Jacobian that is a row vector of dimension — which is exactly Equation 5.40. §5.2 was not a different construction; it was this one with .
The two differ unless the Jacobian happens to be square, so this is not a convention you can leave unresolved. A quick test on any source: find a Jacobian of a map with different input and output dimensions and read its shape. gives in numerator layout and in denominator layout.
The Jacobian determinant
Section titled “The Jacobian determinant”§4.1 showed the determinant computes the area of a parallelogram. Given , as the sides of a unit square,
and for a parallelogram with sides , ,
so that parallelogram has three times the area of the unit square. The mapping that takes one to the other is linear, with transformation matrix
satisfying and .
And if the same map is written out in coordinates,
then its Jacobian, computed from Definition 5.6, is
— the same matrix. So the Jacobian is the coordinate transformation, and:
That word “approximates” carries the whole caveat, and the second figure below measures exactly how much of one.
Worked example by hand
Section titled “Worked example by hand”Example 5.9 — the identity every linear layer uses
Section titled “Example 5.9 — the identity every linear layer uses”with , , .
Step 1 — the shape, before any calculus. Since , it follows that . Doing this first catches most errors before they happen.
Step 2 — the entries.
because every term in that sum except the -th is constant with respect to .
Step 3 — collect.
The Jacobian of a linear map is the matrix itself. Verified numerically for shapes , , and , each agreeing with to about .
This is the single most-used derivative in machine learning. Every dense layer’s backward pass is this identity plus the chain rule.
Example 5.10 — the chain rule, with the shapes checked first
Section titled “Example 5.10 — the chain rule, with the shapes checked first”, , with
The book notes the shapes before computing anything:
so their product is — a scalar, as it must be for .
Filling in the pieces:
Checked against a central difference in at six values, agreeing to between and relative:
| chain rule | central difference | |
|---|---|---|
Example 5.11 — the least-squares gradient
Section titled “Example 5.11 — the least-squares gradient”This is the one that Chapter 9 runs on. Given the linear model
with a parameter vector, the input features and the observations, define
Shape first: (Equation 5.78). Then the chain rule:
Using from §3.2,
so
Note how the shapes carry the derivation: , which is what Equation 5.78 predicted before any differentiating happened.
Verified for , : the analytic gradient
agrees with a central-difference
Jacobian to relative, the two forms of Equation 5.83 agree
exactly (0.0e+00), and at the least-squares solution the gradient is
— zero, as an optimum requires.
See it move
Section titled “See it move”From scratch
Section titled “From scratch”import numpy as np
def numeric_jac(f, x, h=1e-6):
"""Definition 5.6: one column per input, one row per output."""
x = np.asarray(x, dtype=float).ravel()
f0 = np.asarray(f(x)).ravel()
J = np.zeros((f0.size, x.size)) # (outputs, inputs) -- numerator layout
for j in range(x.size):
e = np.zeros_like(x)
e[j] = h
J[:, j] = (np.asarray(f(x + e)).ravel() - np.asarray(f(x - e)).ravel()) / (2 * h)
return J
rng = np.random.default_rng(3)
print("Example 5.9: d(Ax)/dx = A")
for (M, N) in [(4, 3), (2, 5), (3, 3), (5, 1)]:
A = rng.normal(size=(M, N))
x = rng.normal(size=N)
J = numeric_jac(lambda v: A @ v, x)
print(f" A is {M}x{N} -> df/dx is {J.shape} and equals A to {np.abs(J - A).max():.1e}")
print()
print("Example 5.10: h(t) = exp(x1 x2^2) with x = (t cos t, t sin t)")
h_of_t = lambda t: np.exp((t * np.cos(t)) * (t * np.sin(t)) ** 2)
def dh_chain(t):
x1, x2 = t * np.cos(t), t * np.sin(t)
e = np.exp(x1 * x2 ** 2)
df_dx = np.array([[e * x2 ** 2, e * 2 * x1 * x2]]) # 1 x 2, Eq 5.73
dx_dt = np.array([[np.cos(t) - t * np.sin(t)],
[np.sin(t) + t * np.cos(t)]]) # 2 x 1, Eq 5.73
return float((df_dx @ dx_dt).item()) # (1x2)(2x1) -> (1,1)
print(f"{'t':>6} {'chain rule':>18} {'central difference':>20} {'rel gap':>10}")
for t in (0.3, 0.7, 1.0, 1.5, 2.0, 2.5):
ch = dh_chain(t)
hh = 1e-6
nu = (h_of_t(t + hh) - h_of_t(t - hh)) / (2 * hh)
print(f"{t:>6.2f} {ch:>18.9f} {nu:>20.9f} {abs(ch-nu)/max(abs(ch),1e-12):>10.1e}")
print()
print("Example 5.11: the least-squares gradient")
rng = np.random.default_rng(11)
N, D = 30, 4
Phi = rng.normal(size=(N, D))
theta_true = rng.normal(size=D)
y = Phi @ theta_true + 0.3 * rng.normal(size=N)
theta = rng.normal(size=D)
L = lambda th: (y - Phi @ th) @ (y - Phi @ th)
e0 = y - Phi @ theta
ana = (-2 * e0 @ Phi).reshape(1, -1) # Eq 5.83
num = numeric_jac(lambda v: np.array([L(v)]), theta)
ana2 = (-2 * (y.T - theta.T @ Phi.T) @ Phi).reshape(1, -1) # Eq 5.83, expanded
print(f" shape {ana.shape} -- Eq 5.78 predicted 1 x D with D = {D}")
print(f" analytic {np.round(ana[0], 6)}")
print(f" numeric {np.round(num[0], 6)}")
print(f" relative error {np.abs(ana - num).max() / np.abs(ana).max():.1e}")
print(f" the two forms of Eq 5.83 agree to {np.abs(ana2 - ana).max():.1e}")
th_star = np.linalg.lstsq(Phi, y, rcond=None)[0]
print(f" at the least-squares optimum the gradient is "
f"{np.abs(-2 * (y - Phi @ th_star) @ Phi).max():.1e}")Example 5.9: d(Ax)/dx = A
A is 4x3 -> df/dx is (4, 3) and equals A to 9.2e-11
A is 2x5 -> df/dx is (2, 5) and equals A to 1.9e-10
A is 3x3 -> df/dx is (3, 3) and equals A to 2.9e-10
A is 5x1 -> df/dx is (5, 1) and equals A to 4.7e-11
Example 5.10: h(t) = exp(x1 x2^2) with x = (t cos t, t sin t)
t chain rule central difference rel gap
0.30 0.036476225 0.036476224 8.8e-10
0.70 0.706288861 0.706288861 9.3e-12
1.00 1.529376673 1.529376673 1.6e-11
1.50 -3.602659477 -3.602659476 1.2e-10
2.00 -0.486106309 -0.486106309 4.4e-11
2.50 0.036977693 0.036977693 3.5e-10
Example 5.11: the least-squares gradient
shape (1, 4) -- Eq 5.78 predicted 1 x D with D = 4
analytic [-86.449975 161.597514 43.111249 73.58558 ]
numeric [-86.449975 161.597514 43.111249 73.58558 ]
relative error 9.3e-10
the two forms of Eq 5.83 agree to 0.0e+00
at the least-squares optimum the gradient is 2.5e-14Three things.
The shape line for Example 5.11 is the point of doing Equation 5.78 first: the gradient came out exactly as predicted, and if it had come out you would know immediately that a transpose went the wrong way — before looking at a single number.
The two forms of Equation 5.83 agree to 0.0e+00, exactly. That is not luck:
and
are the same floating-point operations in the same order once
is substituted.
And at the least-squares solution the gradient is — which is the condition Chapter 9 solves for. Setting Equation 5.83 to zero gives , the normal equations.
On real data
Section titled “On real data”Reading the plot
Section titled “Reading the plot”From the area figure. The determinant is and the area ratio is , and both facts matter. The magnitude is the magnifier; the sign says the map reverses orientation, which the picture shows by and being swapped in handedness relative to and .
The Monte-Carlo estimate is against an exact , from hits out of . The gap of is sampling noise — — so this is a check that passes, not a discrepancy. It matters because the estimate never touches the determinant: it counts points inside the image using coordinates in the frame, so agreement is independent evidence rather than a restatement.
From the local figure. This is the figure that puts a number on the word “approximates”. The gap between the measured area ratio and :
| side | area / side² | gap |
|---|---|---|
Every halving of the side halves the gap. First order — which is exactly what you should expect, because the Jacobian is the best linear approximation and the error is dominated by the first neglected term.
Note the base point: , not somewhere arbitrary. This map’s determinant is , which vanishes on the hyperbola . Base the squares at instead and the largest one reaches , past the fold — and then the shoelace formula returns the difference of two oppositely-oriented areas rather than the area, giving a measured ratio of against a determinant of . That is not a convergence failure; it is a folded polygon, and the figure avoids it deliberately.
From the shapes figure. The row worth pausing on is the last: a matrix argument gives a fourth-order tensor. §5.4 is about making that computable, and the figure previews the two ways — flatten, or partition into blocks.
Pitfalls
Section titled “Pitfalls”Compare
Section titled “Compare”| function | Jacobian | shape | note |
|---|---|---|---|
| Definition 5.6, the general rule | |||
| the gradient | §5.2’s Equation 5.40 | ||
| a column | a curve’s velocity | ||
| Example 5.9, constant everywhere | |||
| : no stretching | |||
| a rotation | the rotation matrix | : no stretching, no flip | |
| Example 5.11, Chapter 9’s gradient |
-
Why does §5.3 add so little to §5.2?
Definition 5.6 with m = 1 IS Equation 5.40. The book says so in a remark right after the definition. That is the payoff the row convention was chosen for.
pch.quizShowAnswer
B — Because §5.2 already chose the row convention, so a function with m outputs is just m of those rows stacked — the shape rule 'rows are outputs, columns are inputs' extends with nothing to transpose — Definition 5.6 with m = 1 IS Equation 5.40. The book says so in a remark right after the definition. That is the payoff the row convention was chosen for.
-
The Monte-Carlo area estimate in the first figure came out as 3.0049 against an exact 3. Why is that worth showing rather than just quoting det J = -3?
The 0.0049 gap is sampling noise of the expected size for 400000 samples. A check that shares no code with the thing being checked is worth more than a tighter one that does.
pch.quizShowAnswer
B — Because the estimate never touches the determinant — it counts sampled points inside the image using coordinates in the original basis, so agreement is independent evidence rather than a restatement of §4.1 — The 0.0049 gap is sampling noise of the expected size for 400000 samples. A check that shares no code with the thing being checked is worth more than a tighter one that does.
-
For a nonlinear map, the measured area ratio approached |det J| with the gap halving each time the side halved. What does that exponent tell you?
0.216, 0.096, 0.045, 0.0218, 0.00852, 0.00423 as the side goes 0.4 down to 0.01 — proportional to the side throughout. 'The Jacobian approximates the map locally' has a rate, and this is it.
pch.quizShowAnswer
B — That the approximation is first order, which is what a LINEAR approximation must be — the error is dominated by the first neglected term, the quadratic one — 0.216, 0.096, 0.045, 0.0218, 0.00852, 0.00423 as the side goes 0.4 down to 0.01 — proportional to the side throughout. 'The Jacobian approximates the map locally' has a rate, and this is it.
-
In the same figure, basing the squares at (0.8, 0.6) gave a measured ratio of 0.04 against a determinant of 0.424. What went wrong?
This is why Chapter 6's change-of-variables formula requires an invertible transformation. Where the Jacobian determinant vanishes you are not in a regime where 'volume magnifier' means anything.
pch.quizShowAnswer
B — Nothing about the calculus. det J = 1 - 1.2uv vanishes at uv = 0.8333 and that square reaches uv = 1.2, so the map FOLDS — and a signed area formula counts the two folded halves with opposite signs. The assumption broke, not the derivative — This is why Chapter 6's change-of-variables formula requires an invertible transformation. Where the Jacobian determinant vanishes you are not in a regime where 'volume magnifier' means anything.
-
Example 5.11 states the shape 1 x D before doing any calculus. What does that buy?
And note where the check stops working: for a square Jacobian the shape composes either way, so you lose it. That is also when the numerator and denominator layouts become indistinguishable by shape.
pch.quizShowAnswer
B — The cheapest possible error check: a wrong transpose usually produces shapes that do not compose at all, so the mistake surfaces before any arithmetic. The derivation then just fills in a (1 x N)(N x D) product — And note where the check stops working: for a square Jacobian the shape composes either way, so you lose it. That is also when the numerator and denominator layouts become indistinguishable by shape.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Example 5.9, at four shapes
Section titled “Exercise 1 – Example 5.9, at four shapes”Exercise 2 – Example 5.10, shapes first
Section titled “Exercise 2 – Example 5.10, shapes first”Exercise 3 – Example 5.11, and the normal equations
Section titled “Exercise 3 – Example 5.11, and the normal equations”Exercise 4 – The determinant as an area magnifier
Section titled “Exercise 4 – The determinant as an area magnifier”Exercise 5 – ‘Locally’ has a rate, and a boundary
Section titled “Exercise 5 – ‘Locally’ has a rate, and a boundary”Recall card
Section titled “Recall card”- The Jacobian is m gradient rows stacked: an m by n matrix with J(i,j) = the partial of output i with respect to input j — Definition 5.6, Equation 5.58.
- §5.2 was this with m = 1. Equation 5.40’s row vector is Definition 5.6’s special case, which is the payoff for choosing rows.
- Numerator layout means rows are outputs; the denominator layout is its transpose. They differ unless the Jacobian is square — and when it is square, the shape cannot tell them apart.
- The Jacobian of a linear map is the matrix itself, everywhere. Verified at four shapes, agreeing to about 1e-10.
- |det J| is the volume magnifier. For the book’s Figure 5.5, det J = −3 so areas triple and orientation flips; a Monte-Carlo count over 400000 samples gives 3.0049.
- For a nonlinear map that is only local, and the rate is first order. Measured: the gap between the area ratio and |det J| halves each time the side halves — 0.216 at side 0.4 down to 0.0042 at 0.01.
- Where det J = 0 the map folds, and a signed area formula then counts two halves against each other. That is why Chapter 6’s change of variables requires invertibility.
- The chain rule is a matrix product whose shapes are stated first. Equation 5.73 gives (1×2)(2×1); Equation 5.78 gives 1×D before any calculus happens.
- The least-squares gradient is −2 e-transpose Phi, shape 1 by D — Example 5.11, and Chapter 9’s whole starting point. Setting it to zero gives the normal equations.
- A (1,1) NumPy array is not a float.
float()on it raises, and that is the shapes composing correctly. Use.item().
Next: Gradients of Matrices — where the derivative becomes a fourth-order tensor, and the two ways to make that computable.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading