Chapter 12: Matrix calculus and numerical practice
Previous: LA 11 Change of Basis | LA 00 Course Map
Derivatives of functions with many inputs and outputs are organized as vectors (gradients) and matrices (Jacobians). With that organization, the chain rule becomes matrix multiplication, which is exactly how neural networks are trained. The second half of the chapter is about trust: the condition number tells you whether a computed answer means anything.
- Compute gradients of functions of a vector, and know what the gradient means.
- Memorize and use the three most common matrix-calculus gradients.
- Compute Jacobians, and apply the chain rule as a matrix product.
- Explain backpropagation through a linear layer.
- Analyse gradient descent on a quadratic using eigenvalues.
- Use the condition number, and follow safe numerical habits.
You need partial derivatives from calculus: means “differentiate with respect to , treating the other variables as constants”. For , and . From this course you need symmetric matrices and eigenvalues (LA 09 Symmetric and Positive Definite Matrices) and the SVD (LA 10 Singular Value Decomposition).
12.1 The gradient
Definition
For a function that takes a vector and returns a number, , the gradient collects all its partial derivatives into a vector:
It has the same shape as .
Worked example 12.1. .
At : .
What the gradient means
The gradient gives the best linear approximation of near a point:
For a small step , the change in is (approximately) the dot product of the gradient with the step. From chapter 2, a dot product with fixed is:
- largest when points along ,
- zero when is perpendicular to ,
- most negative when points opposite to .
- points in the direction of steepest increase.
- points in the direction of steepest decrease. That is the direction gradient descent steps in.
- is perpendicular to level curves (moving along a level curve does not change , so that direction has zero dot product with the gradient).
Worked example 12.2. Using example 12.1 at , . Take a small step : the approximation gives . The exact value is . Very close.
- Find for .
- At a point, . In which unit direction does decrease fastest, and at what rate?
Answers. 1. . 2. Direction . The rate is per unit step.
12.2 Three gradients to memorize
Matrix calculus looks intimidating, but nearly everything reduces to three rules. Each mirrors a rule from single-variable calculus.
| Function of | Gradient | Scalar analogue |
|---|---|---|
| , symmetric |
For a non-symmetric , the third becomes .
Why they are true
Rule 1. . Differentiating with respect to leaves . So the gradient is .
Rule 2. . The derivative with respect to is .
Rule 3, checked in 2-D. With , . Then
which is ✓.
A gradient always has the same shape as the variable. If is , so is . If your answer has the wrong shape, it is wrong. This catches most errors.
12.3 Least squares again, now by calculus
Minimize
(The middle term: and are the same number, so they combine into .)
Apply the rules:
- : rule 3 with the symmetric gives .
- : rule 1 gives .
- : a constant, gradient 0.
Set it to zero: . The normal equations, exactly as in chapter 6 from geometry. Two completely different routes, one answer.
The second derivative (Hessian) is , positive semidefinite (chapter 9), so this critical point is a minimum.
12.4 The Jacobian
Definition
For a function with vector inputs and vector outputs, , the derivative is a matrix:
- Row is the gradient of output (transposed).
- Column shows how all outputs respond to input .
And the linear approximation becomes
The Jacobian is the matrix that the function looks like, up close. Every smooth function is approximately linear on a small enough scale, and is that linear map.
Worked example 12.3. .
At : .
Linear functions. has Jacobian everywhere. A linear map is its own best linear approximation.
Worked example 12.4: a two-link robot arm
Link lengths , joint angles . The hand position is
Differentiate each with respect to each joint angle:
It maps joint velocities to hand velocity: .
Its determinant simplifies (use identities) to
That is zero at (arm straight) and (folded back): the singularities, where the hand cannot move in some direction no matter how the joints turn (chapters 5 and 7).
12.5 The chain rule is matrix multiplication
If , with and , then
Derivatives of composed functions multiply, in the same order as the functions compose. Shapes: ✓.
Why: near , looks like and near , looks like . A linear map followed by a linear map is their product (chapter 3).
Worked example 12.5. and . So .
Check directly: , so ✓.
12.6 Backpropagation through a linear layer
A neural network is a long chain , ending in a scalar loss . By the chain rule, is a long product of Jacobians.
Key idea of backpropagation: because the final output is a scalar, multiply the chain starting from the loss end. Then every intermediate result is a vector (a gradient), never a large matrix. That makes training affordable.
One linear layer
Let , with of shape . Suppose the layers above have already computed the upstream gradient (a vector of length ). We need the gradients with respect to the layer’s input (to pass further down) and its weights (to update them):
Why . Each affects every through the weight . So , which is entry of . Gradients flow backwards through the transpose.
Why . affects only , with . So , which is entry of the outer product .
Shape check. must be , like . is and is , so is ✓. This is the only way to combine and into the right shape, which makes the formula easy to rebuild from scratch.
Worked example 12.6. , , so . Loss , so .
Gradient descent would then update .
12.7 Gradient descent on a quadratic
The setup
Take the quadratic bowl
with symmetric positive definite. Then , and the minimum solves .
Gradient descent repeats
where is the step size (learning rate).
Analysing the error
Let be the error. Subtracting from the update:
Each step multiplies the error by the matrix . In the eigenvector basis of (chapter 11), this is diagonal: the error component along eigenvector is multiplied by
at every step.
Consequences
- Convergence requires for every , which means
- Progress in the flattest direction is slow: its error shrinks by per step, which is close to 1 when is small.
- With the best step size, the error shrinks per step by about
The step size is limited by the steepest direction (too big and it overshoots and diverges there), while progress is limited by the flattest direction. A large ratio (a long, narrow valley) means slow, zigzagging convergence.
Worked example 12.7. The loss from 01 Math for Learning has .
- , so descent is stable only for .
- At : the error is multiplied by each step (it flips sign and shrinks slowly, which is the bouncing in the animation). The error is multiplied by .
- At : multiplied by (smooth), by (slow).
- , best-case rate about per step.
This is exactly why the animation shows one rate bouncing and the other crawling.
12.8 Conditioning: can you trust the answer?
The condition number
the ratio of the largest to the smallest singular value (chapter 10).
When solving , a small relative error in can cause a relative error in up to times larger.
Rule of thumb. Double-precision arithmetic carries about 16 significant digits. If , expect to lose about of them.
Worked example 12.8: an ill-conditioned system
- With : solution .
- With : solution .
A change in the fifth significant digit of completely changed the answer. The columns are almost parallel, so is tiny and .
Picture. Each equation is a line. These two lines are nearly parallel, so moving one slightly slides their crossing point a long way.
Why not use the determinant?
Recall chapter 7: in 100 dimensions has determinant but , perfectly conditioned. The determinant measures volume; the condition number measures distortion. Only distortion matters for accuracy.
12.9 Practical rules
- Solve, do not invert.
np.linalg.solve(A, b), notnp.linalg.inv(A) @ b. - Least squares via QR or SVD.
np.linalg.lstsq(A, b). Forming squares the condition number: . - Scale your features. Columns in wildly different units inflate .
- Regularize ill-conditioned problems. Ridge regression solves , lifting every eigenvalue by (chapter 9, exercise C4).
- Check gradients numerically. Compare your formula with the central difference
- Never compare floats with
==. Usenp.allcloseor a tolerance. - Use specialized solvers for special matrices:
eighfor symmetric, Cholesky for positive definite.
Summary
| Idea | Fact |
|---|---|
| gradient | vector of partials; steepest ascent |
| key gradients | ; ; |
| least squares | |
| Jacobian | matrix of partials; local linear map |
| chain rule | |
| linear layer | , |
| GD on a quadratic | error factor ; need |
| condition number | ; lose about digits |
Three facts to remember:
- The gradient points uphill; the Jacobian is the local linear map.
- Chain rule = multiply Jacobians; backprop does it from the loss end.
- Eigenvalues set the speed of gradient descent; singular values set the accuracy of solving.
Exercises
Part A: warm-up
A1. Find for , and evaluate it at .
A2. Find the gradient of for a fixed vector . Where is it zero?
A3. Write the Jacobian of .
A4. has eigenvalues 1 and 100. What is the largest stable learning rate, and what is ?
A1. at .
A2. , zero at : the closest point to is itself.
A3. ().
A4. . .
Part B: core
B1. Find the gradient of and its minimizer, for and .
B2. For the two-link arm with , evaluate and at . Interpret.
B3. A layer computes with and . The upstream gradient is . Compute and .
B4. Run three steps of gradient descent by hand on from with . Predict, using the factors , what happens to each coordinate.
B5. Use the chain rule to find for , viewing it as with and .
B1. . Solve : det 5, .
B2. , . , . The elbow is bent at a right angle, the best-conditioned configuration: the hand can move freely in every direction.
B3. . .
B4. . Factors: for , for . So : ; : . The steep coordinate collapses fast, the shallow one slowly.
B5. , , so . , and the gradient is its transpose: . Same as section 12.3.
Part C: explain and prove
C1. Prove that for any square , by computing of .
C2. Explain why the gradient is perpendicular to the level curves of .
C3. Show that using the SVD. Why does this make the normal equations risky?
C4. In gradient descent on a quadratic, what happens if exactly? What if is a little larger?
C1. .
C2. Along a level curve is constant, so the directional derivative in the tangent direction is zero: the gradient is perpendicular to .
C3. has singular values , so . If , then , losing about 12 of 16 digits.
C4. At exactly , the factor in the steepest direction is : the error flips sign forever without shrinking. Slightly larger, its size exceeds 1 and the error grows without bound: divergence.
Part D: practise with code
D1. Implement numerical_grad(f, x, eps=1e-5) using central differences. Compare it with your formula for A1 at several points.
D2. Implement gradient descent on for with , using . Plot against . How does the slope depend on ?
D3. Build the Hilbert matrix (scipy.linalg.hilbert(n)) for . Print its condition number. Solve for all ones, and report the error. What happens as grows?
D4. Write a tiny two-layer network by hand in NumPy (y = W2 @ np.tanh(W1 @ x)), compute the gradient of a squared loss with respect to W1 using the chain rule, and verify it with numerical_grad.
D2. With , the slow direction shrinks by per step, so falls with slope about : 100 times slower at .
D3. The condition number explodes (about by ), and the computed becomes garbage even though the problem looks innocent.
D4. For , the upstream gradient into is , where is entry-wise multiplication. Then is that vector times .
Where this is used
Everything in 05 Training Neural Policies is this chapter at scale. Jacobians drive velocity kinematics and operational-space control (02 Geometry and Kinematics), and linearizing a nonlinear system around an operating point, the starting move of 03 Dynamics and Feedback, is computing a Jacobian.
You have finished the linear algebra course. Go back to the checkpoint questions in LA 00 Course Map and answer them without notes.