Skip to content

1.3 Gradients and matrix calculus

ready≈ 10.5 hoursNeeds: 1.1Unlocks: 1.6, 2.2, 3.2
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Gradient field explorer, Jacobian lens)
  4. 4 Do
  5. 5 Check

Training a network means following derivatives downhill, so this is the most-used module in the course.

A partial derivative ∂f∂xi\frac{\partial f}{\partial x_i}partial derivativeRate of change of f as x_i alone changes, all other inputs held fixed.Introduced in 1.3 Gradients and matrix calculus. changes one input and holds the rest fixed. Stack all of them and you get the gradient ∇xf\nabla_{\mathbf{x}} fgradientVector of partial derivatives ∂f/∂x_i. Same shape as x. Points in the direction of steepest increase.Introduced in 1.3 Gradients and matrix calculus. MML treats gradients as row vectors (§5.2); we follow UDL and CS229 and use the same shape as x., which has the same shape as x\mathbf{x} (MML §5.2). Two facts make it useful. The slope in a unit direction u\mathbf{u} is ∇f⋅u\nabla f\cdot\mathbf{u}, which is largest when u\mathbf{u} points along ∇f\nabla f (Cauchy–Schwarz), so the gradient is the direction of steepest ascent (MML §5.1, p. 142). And it is perpendicular to the level sets, because along a contour ff does not change (MML §7.1). The explorer below lets you see both.

For a vector-valued f:Rn→Rm\mathbf{f}:\mathbb{R}^n\to\mathbb{R}^m, the partials form the m×nm\times n Jacobian J\mathbf{J}JacobianFor f: ℝⁿ → ℝᵐ, the m×n matrix of partials J_{ij} = ∂f_i/∂x_j. The best linear approximation of f near a point.Introduced in 1.3 Gradients and matrix calculus.: the best linear approximation of f\mathbf{f} near a point. Its determinant is the local area factor (MML §5.3). The chain rule says Jacobians multiply. Backprop (3.2) is just that rule applied efficiently.

Notation trap: MML writes gradients as row vectors (MML §5.2, Remark “Gradient as a Row Vector”). We follow UDL and CS229 and use the shape of x\mathbf{x} (see Notation). The math is the same up to a transpose.

Checking gradients numerically. The central difference f(x+h)−f(x−h)2h\frac{f(x+h)-f(x-h)}{2h} has error O(h2)O(h^2). The one-sided f(x+h)−f(x)h\frac{f(x+h)-f(x)}{h} has error O(h)O(h), so prefer central. Compare the two with a relative error, ∣a−n∣∣a∣+∣n∣\frac{|a-n|}{|a|+|n|}, so the threshold does not depend on the gradient’s scale (CS231n, gradient checks). Values around 10−710^{-7} mean correct. Values above 10−210^{-2} mean a bug. The checker you build here verifies every gradient you derive for the rest of the course.

Gradient of a quadratic form xᵀAxstep 1 of 4
  1. f(x)=x⊤Ax=∑i∑jxiAijxjf(\mathbf{x}) = \mathbf{x}^\top\mathbf{A}\mathbf{x} = \sum_i \sum_j x_i A_{ij} x_j

★ Gradient field explorer

Gradient direction, magnitude and level sets

Static view on small screens. Open this page on a laptop to interact.

f(p) = 3.040 ∇f(p) = (3.20, 2.80) ‖∇f‖ = 4.25 slope along u: ∇f·u = 4.24

■ gradient (length log-scaled) · ■ direction u · dashed: tangent to the level set. Turn u until the slope ∇f·u is largest: it lines up with the gradient. Turn it 90° and the slope is zero: you are walking along a contour.

Contours of a function of two variables, with a draggable point. The orange arrow is the gradient, the blue arrow is a direction u, and the dashed line is the tangent to the contour. The readout gives the directional slope ∇f·u. Keyboard: Tab to the point, arrows move it; the slider sets the direction u.

Jacobian lens

The Jacobian as a local linear map

Static view on small screens. Open this page on a laptop to interact.

input: square of side 2h around p
output: ■ true image F(square) · ▢ J·square (linear approximation)
J(p) = [[1.60, -1.00], [1.00, 1.60]] det J = 3.560 actual area ratio = 3.726 mismatch = 0.1662

The curved map warps the grid, but zoom in far enough and it looks linear. Shrink h: the true image (filled) and the parallelogram from the Jacobian (outline) merge, and the area ratio approaches |det J|. That local area factor is the change-of-variables term you will meet again in normalizing flows (6.3).

Left: a small square in the input space. Right: its true image under a nonlinear map (filled) and its image under the Jacobian (dashed outline). As the square shrinks, the two agree and the area ratio approaches |det J|. Keyboard: Tab to the point, arrows move it.
f = lambda x: np.sin(x)
x, true = 0.5, np.cos(0.5)
for h in [1e-1, 1e-2, 1e-3, 1e-4]:
    fwd = (f(x + h) - f(x)) / h
    ctr = (f(x + h) - f(x - h)) / (2 * h)
    print(f'h={h:.0e}  forward err={abs(fwd-true):.1e}  central err={abs(ctr-true):.1e}')

Tab indents · Esc then Tab leaves the editor · Shift+Enter runs

Watch the forward error fall 10× per row and the central error fall 100×. (Push hh down to 10−1210^{-12} and rounding error takes over. That is why h≈10−5h\approx 10^{-5} is the default.)

Build numerical_grad for arrays of any shape, rel_error and grad_check, then derive four gradients by hand and let your checker confirm them. One test feeds logsumexp_grad inputs of 1000: make it stable.

Numerical gradient checker stubs/m1_3_gradients.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m1_3_gradients.py and run mlc check 1.3. The tests are identical; import the results on the progress page.

Hints · numerical_grad 0/3 revealed
Hints · logsumexp_grad 0/3 revealed

Locally: mlc check 1.3.

1. At a point, ∇f = (3, 4). What is the largest possible slope of f in any unit direction?
2. What is the gradient of f(x) = xᵀAx when A is not symmetric?
3. Halving h makes the error of the central difference roughly…
4. Your grad_check returns 0.3. What is most likely?
5. f maps R³ to R². What is the shape of its Jacobian?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.