SafeZone AI Learn
Learn/ Mathematical Foundations/ Linear Algebra for ML · lesson 5 of 6

Matrix calculus

The handful of identities that generate deep learning's derivatives — gradients, Jacobians, Hessians and the chain rule in matrix form — plus the quadratic-form geometry that makes second-order information visible.

Every training loop in this curriculum runs on derivatives of scalar losses with respect to vectors and matrices, and yet most people compute them by pattern-matching against half-remembered identities. This closing lesson makes the patterns principled: three definitions, five identities, one chain rule — enough to derive by hand every gradient this curriculum has used, and to see (in the widget) what the Hessian’s eigenstructure means before the Deep Learning module automates all of it with autodiff.

Three derivative objects, one convention

For f:RnRf: \mathbb{R}^n \to \mathbb{R}, the gradient fRn\nabla f \in \mathbb{R}^n collects the partials; for F:RnRmF: \mathbb{R}^n \to \mathbb{R}^m, the Jacobian JRm×nJ \in \mathbb{R}^{m \times n} has Jij=Fi/xjJ_{ij} = \partial F_i / \partial x_j; for scalar ff, the Hessian Hij=2f/xixjH_{ij} = \partial^2 f / \partial x_i \partial x_j is the (symmetric, by Schwarz) matrix of curvatures. The honest warning that saves hours of sign errors: two layout conventions exist in the wild (numerator vs denominator layout — whether a gradient is a row or a column), and mixed sources mix them silently. This curriculum uses column gradients (f\nabla f has the shape of xx) and m×nm \times n Jacobians, matching PyTorch/JAX. Check shapes first, always; the correct expression is usually the only one whose shapes compose.

The best mental model is not partial derivatives at all but the linear approximation: the derivative of a map at xx is the matrix that best linearizes it,

F(x+δ)F(x)+Jδ,f(x+δ)f(x)+fδ+12δHδ.F(x + \delta) \approx F(x) + J\,\delta, \qquad f(x + \delta) \approx f(x) + \nabla f^\top \delta + \tfrac{1}{2}\, \delta^\top H\, \delta .

Read against lesson 1: near any point, a differentiable map is a linear map (its Jacobian), so everything this module established about linear maps — rank, eigenstructure, conditioning — applies locally to nonlinear ones. That single observation is why linear algebra governs the training of deeply nonlinear networks.

The identities that do all the work

Derived once from the linearization view (perturb, expand, keep first order), then used forever:

f(x)f(x) or F(x)F(x)DerivativeWhere it earns its keep
axa^\top xf=a\nabla f = aevery linear layer’s bias-side
AxAxJ=AJ = Alinear layers; the Jacobian is the weight matrix
xAxx^\top A xf=(A+A)x\nabla f = (A + A^\top)x, =2Ax= 2Ax if symmetricquadratic losses, regularizers
12Axb2\tfrac{1}{2}\lVert Ax - b \rVert^2f=A(Axb)\nabla f = A^\top (Ax - b)least squares — the normal equations in one line
x2\lVert x \rVert^2f=2x\nabla f = 2xridge/weight-decay terms

Worked example, because it is the module’s recurring character: perturb f(x)=12Axb2f(x) = \tfrac12\lVert Ax - b\rVert^2 by δ\delta, expand 12Axb+Aδ2\tfrac12\lVert A x - b + A\delta \rVert^2, and the first-order term is (Axb)Aδ(Ax - b)^\top A \delta — so f=A(Axb)\nabla f = A^\top(Ax - b), and the Hessian (differentiate again) is AAA^\top A: the matrix whose eigenvalues gave least squares its condition number, whose SVD gave ridge its shrinkage, and whose positive semidefiniteness made the problem convex. One computation, four modules of consequences.

The chain rule in matrix form is Jacobians multiplying in composition order:

JFG(x)=JF(G(x))  JG(x).J_{F \circ G}(x) = J_F\big(G(x)\big)\; J_G(x).

For a deep network (WLσ(WL1σ(W1x)))\ell(W_L \sigma(W_{L-1} \cdots \sigma(W_1 x))), the gradient of the loss with respect to early weights is a product of many Jacobians — and backpropagation is nothing but evaluating that product right-to-left (vector-times-Jacobian at each step, never materializing full Jacobians), which is why it costs only ~2× the forward pass. Two curriculum call-backs land here with a click: products of matrices compound their spectra, so many Jacobians with singular values below 1 give vanishing gradients and above 1 exploding ones — the saturation-plateau story from Non-convex Landscapes, now stated as linear algebra; and initialization schemes (Deep Learning module, ahead) are precisely spectrum-control for these products.

Seeing second order: the quadratic form under your hands

The Hessian’s Taylor term 12δHδ\tfrac12 \delta^\top H \delta is a quadratic form, and its geometry — bowls, saddles, ravines — is fully described by the spectral theorem: eigenvectors are principal axes, eigenvalues are curvatures along them. You have classified these algebraically since the Optimization module; here is the object itself, with the entries of a symmetric AA on sliders:

Start at the default bowl: both eigenvalues positive, elliptical contours, the gold principal axes along the eigendirections — and the readout’s κ is the ratio you have been fighting since gradient descent. Drag a₁₂ upward and watch the ellipses tilt (off-diagonal terms couple the axes; the eigenbasis un-tilts them — that is diagonalization, visually). Now push a₂₂ negative: one curvature flips, contours become hyperbolas, and the readout declares a saddle — the exact object the Deep RL gridworld’s cousin, the non-convex landscapes lesson, warned about. Finally set a₁₂² ≈ a₁₁·a₂₂ and watch a flat direction appear (semidefinite): a ravine floor, curvature zero along one axis. Every Hessian diagnosis you will ever make is one of these three pictures.

What autodiff changes, and what it doesn’t

Frameworks compute all of this mechanically — reverse-mode autodiff is the chain rule with bookkeeping — so why learn it by hand? Three durable reasons. Shapes and conventions still break code daily, and the person who can write WXWY2=2X(XWY)\nabla_W \lVert XW - Y\rVert^2 = 2X^\top(XW - Y) debugs in minutes what shape-guessing debugs in hours. Second, custom losses, custom layers, reparameterization tricks and implicit-differentiation setups all require exactly these derivations at the boundary where the framework can’t see. Third — and this is the module’s closing thought — the derivative objects carry the geometry: the Jacobian’s spectrum explains vanishing gradients, the Hessian’s spectrum explains optimizer behaviour, the gradient’s covariance explained SGD’s noise ball. Autodiff gives you the numbers; this module gave you their meaning.

import torch

X = torch.randn(50, 3)
W = torch.randn(3, 2, requires_grad=True)
Y = torch.randn(50, 2)

loss = 0.5 * ((X @ W - Y) ** 2).sum()
loss.backward()
manual = X.T @ (X @ W.detach() - Y)          # this lesson, by hand
torch.testing.assert_close(W.grad, manual)   # autodiff agrees — it is the chain rule

Exercises

Closing the module

  1. Derive (xAx)=(A+A)x\nabla (x^\top A x) = (A + A^\top)x by first-order perturbation, and explain the factor-of-2 folklore error people make when AA is not symmetric.
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 5 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • K. B. Petersen & M. S. Pedersen, The Matrix Cookbook — the identity reference everyone actually uses; now you can derive its entries.
  • T. Parr & J. Howard, “The Matrix Calculus You Need For Deep Learning”, 2018 — a gentle, convention-explicit companion.
  • A. Griewank & A. Walther, Evaluating Derivatives, 2nd ed. — the definitive treatment of automatic differentiation, including the reverse-mode cost theorem.