Linear Algebra II
Module 1 gave you the pictures: vectors, transformations, determinants, eigenvectors. This module turns them into the tools that machine learning uses every day. You'll see why perpendicular directions make everything easy, how least squares is just dropping a perpendicular, why every matrix is secretly rotate, stretch, rotate (), how that one fact gives you image compression, PCA and the pseudoinverse, why some problems turn tiny noise into huge errors, and how to keep tensor shapes straight in NumPy and PyTorch. It ends with the low-rank factorizations behind recommender systems and LoRA fine-tuning.
How to use this module
- Watch, then play. Chapters link to the best videos on each idea. Watch, then come back and drag the figure until it feels obvious.
- Questions get harder as you go: Warm-up Practice Think Challenge. Pick one answer, press Check answer, and the worked solution opens.
- Code it: Python runs in your browser and is graded by test cases. The first run downloads Python (internet needed once).
- Your progress is saved in this browser. Tick "mark as done" at the end of each chapter.
Orthogonality and orthonormal bases
Watch: Orthogonal vectors and subspaces (MIT OCW, Gilbert Strang) Rewatch: Dot products and duality (3Blue1Brown)Two vectors are orthogonal when their dot product is zero. A basis of mutually perpendicular unit vectors is the best basis there is: coordinates become dot products, lengths obey Pythagoras, and the matrix that holds the basis is inverted just by transposing it.
In Module 1, chapter 9 you met the dot product: , which equals . The cosine is zero exactly at 90°, so
That's the whole definition of orthogonal (a fancier word for perpendicular that also works in 50 dimensions, where you can't see any angles). For example (2, −1) and (1, 2) are orthogonal because 2 − 2 = 0.
Why perpendicular is special. If then Pythagoras holds: . The cross term vanishes. Perpendicular pieces don't interfere with each other: you can measure, add and remove them separately. Almost every trick in this module comes from that one fact.
Orthonormal bases: coordinates for free
A set of vectors is orthonormal if each has length 1 and each pair is orthogonal:
Orthonormal vectors are automatically independent, so of them in dimensions form a basis. Now the payoff. In a general basis, finding the coordinates of means solving a system of equations (change of basis). In an orthonormal basis, write and dot both sides with . Every term except the first dies, because , and , so
Each coordinate is just "how far does reach along ?" No system to solve. And because the pieces are perpendicular, Pythagoras gives .
Orthogonal matrices
Put orthonormal vectors in the columns of a matrix . The entries of are exactly the dot products , so
When is square this means : inverting is free. Such a is called an orthogonal matrix (the name is a historical accident; "orthonormal matrix" would be better). Geometrically it's a rotation, a reflection, or a mix. It keeps every length and angle, because . Its determinant is (rotation) or (includes a flip), since .
The coordinate formula for all at once is , and rebuilding is .
Careful with tall ones. If is 5×2 with orthonormal columns, still holds, but is a 5×5 matrix that is not the identity: it can't be, since it has rank 2. It turns out to be the projection onto the plane of the two columns. That's the next chapter.
Orthogonal subspaces
Whole subspaces can be perpendicular too: every vector in one is orthogonal to every vector in the other. The most important example hides inside every matrix. If , then each row of dotted with gives 0. So the null space is perpendicular to every row, and hence to the row space (the span of the rows). In these two fill everything between them: their dimensions add up to . They are orthogonal complements. Likewise the column space is perpendicular to the null space of .
Worked exampleCoordinates in a tilted orthonormal basis
Take and . Check: , , and . Orthonormal ✓.
Find the coordinates of :
Check by rebuilding: ✓. And Pythagoras: ✓.
As a matrix: is a rotation by about 53°, , and .
Watch outCommon misconceptions
- "Orthogonal columns make an orthogonal matrix." The columns also need length 1. has perpendicular columns, but , not .
- " means ." Only for square . For a tall , is a projection.
- "Orthogonal means independent, and independent means orthogonal." Nonzero orthogonal vectors are always independent, but (1, 0) and (1, 1) are independent and not orthogonal.
- "Uncorrelated features are orthogonal vectors." Only after you subtract each feature's mean. Correlation is the cosine between centred columns.
In ML & deep learningWhere this shows up
Orthogonal initialisation: starting a deep or recurrent network's weight matrices as random orthogonal matrices keeps signals from blowing up or dying as they pass through many layers, because preserves length. Rotary position embeddings (RoPE) in modern transformers rotate query and key vectors by position-dependent 2D rotations, which are orthogonal, so attention scores depend only on relative position. Cosine similarity between embeddings is the dot product of unit vectors: 0 means "unrelated directions". And PCA (chapter 8) hands you an orthonormal basis in which features are uncorrelated.
Practice (pick one answer per question)
Are (2, −1) and (1, 2) orthogonal?
- Yes, their dot product is 0
- No, their dot product is 4
- No, they have different lengths
- Yes, because both have length √5
, so yes. Lengths don't matter for orthogonality (they happen to be equal here, but that isn't the reason).
For which is orthogonal to ?
, so .
With and , what are the coordinates of ?
and . Check with Pythagoras: ✓. Forgetting the gives (6, 2), whose squares add to 40, not 20.
is a 3×3 orthogonal matrix and . What is ?
- 5
- It depends on
- 25
. Rotations and reflections never change length.
Which of these matrices is orthogonal?
The first has unit columns with dot product . The second has perpendicular columns of length (not unit). The third has unit columns but their dot product is . The fourth is a shear.
is 5×2 with orthonormal columns. Which statement is true?
- is invertible
holds the dot products of the columns, so it's . is 5×5 with rank 2, so it can't be . A non-square matrix has no inverse and no determinant.
If , then is guaranteed to be orthogonal to…
- every row of
- every column of
- the column space of
- only the first row of
Entry of is (row )·. All of them are 0, so is perpendicular to every row and to the whole row space. Columns live in a different space when isn't square, so "orthogonal to the columns" doesn't even make sense in general.
and are orthogonal matrices. Is the product orthogonal?
- Always:
- Only if
- Only if both are rotations
- Never, because the columns get mixed
, and the middle collapses to . Geometrically: doing one length-preserving map after another preserves length. (Two reflections make a rotation, which is still orthogonal.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Projections onto subspaces and least squares
Watch: Projections onto subspaces (MIT OCW, Gilbert Strang) Watch: Projection matrices and least squares (MIT OCW, Gilbert Strang)The closest point to in a subspace is the one where the leftover error is perpendicular to the subspace. Writing "error ⟂ every column of " as an equation gives the normal equations , and that is least-squares regression.
Projecting onto a line
You have a vector and a line through the origin in direction . Which point on the line is closest to ? Picture dropping a perpendicular from the tip of to the line. The foot of that perpendicular is , and the error meets the line at a right angle. Any other point on the line is farther away: by Pythagoras its distance² is plus something positive.
To find , just demand perpendicularity: . Solve for :
The matrix is the projection matrix. If is a unit vector the formula is just , and , the coordinate from chapter 1.
Projecting onto a subspace
Now replace the line by the column space of a tall matrix (say , with independent columns). Points in it look like . We want the making perpendicular to the whole subspace, which means perpendicular to every column of . Stack those dot products into one equation:
These are the normal equations ("normal" as in perpendicular). is a small matrix, invertible exactly when the columns of are independent. Then
Every projection matrix has two signature properties. : projecting something that's already in the subspace does nothing. And : it's symmetric. If the columns are orthonormal (call the matrix ), then and everything simplifies to , which is the tall from chapter 1.
Least squares: solving the unsolvable
Fit a line through data points . Each point gives one equation . With more points than unknowns the system ,
usually has no solution: is not in the column space. So settle for the that makes the total squared error as small as possible. The closest point to in the column space is the projection, so the answer is the normal equations again. Least squares is projection, just in -dimensional "data space" where each axis is one data point.
Calculus agrees: the gradient of is , and setting it to zero gives the same equations.
Worked exampleFit a line through (0, 6), (1, 0), (2, 0)
Here , .
- (the count of points, , ) and (, ).
- Solve , . Subtracting: , so , then . Best line: .
- Predictions , residuals , squared error .
- Check perpendicularity: ✓.
Watch outCommon misconceptions
- "Least squares minimises the perpendicular distance to the line." In regression the residuals are vertical (errors in only). The perpendicular is in the -dimensional data space, not in the scatter plot. Minimising perpendicular distances in the picture is a different problem: that's PCA (chapter 8).
- "Compute and multiply." Mathematically fine, numerically poor. Solve the system (
np.linalg.solve), or better use QR ornp.linalg.lstsq; chapters 3 and 10 explain why. - " simplifies to ." Only if is square and invertible, in which case the subspace is everything and projecting does nothing. A tall has no inverse.
In ML & deep learningWhere this shows up
Linear regression is exactly this chapter: features in the columns of (plus a column of ones for the bias), targets in , and the fitted weights solve the normal equations. The mean-squared-error loss used to train neural networks is the same , just with a nonlinear model so there's no closed form. The final linear layer of a frozen network can be fitted in one shot this way ("linear probing"). Projections also appear directly: removing a "bias direction" from word embeddings projects them onto the orthogonal complement of that direction, .
Practice (pick one answer per question)
Project onto the x-axis.
- (4, 0)
- (0, 3)
- (4, 3)
- (5, 0)
With : , . The error (0, 3) is vertical, perpendicular to the axis. (5, 0) rotates b down instead of dropping a perpendicular.
Project onto the line through .
- (1, 2)
- (5, 10)
- (3, 6)
- (1.5, 0.5)
, , so and . Check: and ✓. (5, 10) forgets to divide by .
What is the projection matrix onto the line through ?
. Check : each entry is , so ✓. The all-ones matrix forgets to divide by 2; it doubles vectors on the line.
For any projection matrix , equals…
After one projection you're in the subspace; projecting again changes nothing. (A reflection would give .)
In least squares, the residual is orthogonal to…
- every column of
- every row of
That's exactly what says: each column of dotted with is zero. lives in data space (length ), the same space as the columns. It is usually not perpendicular to .
Fit by least squares to the points (0, 1), (1, 3), (2, 4).
, . Then and give , , . Check: residuals , , sum to 0 ✓. The line through the first two points () ignores the third.
If already lies in the column space of (independent columns), least squares returns…
- the exact solution of , with zero residual
- an approximate solution with a small positive error
- no answer, because becomes singular
Then is its own closest point: , , and solves exactly. depends only on , not on , so it stays invertible.
projects onto a 3-dimensional subspace. What is the trace of (the sum of its diagonal entries)?
- 3
- 10
- 7
- 1
Vectors in the subspace are kept (: eigenvalue 1, three independent directions) and vectors perpendicular to it are killed (eigenvalue 0, seven directions). The trace is the sum of eigenvalues: . Equivalently, with an orthonormal basis , .
Code it (optional: real Python runs in your browser and is graded by test cases)
Gram–Schmidt and the QR decomposition
Watch: Orthogonal matrices and Gram–Schmidt (MIT OCW, Gilbert Strang)Gram–Schmidt turns any independent vectors into an orthonormal basis for the same space: take each vector, subtract its projections onto the ones already done, and normalise. Keeping track of what you subtracted gives , with orthonormal and upper triangular.
Chapter 1 showed that orthonormal bases make life easy. But real data rarely hands you one: the columns of a data matrix point wherever they like. Gram–Schmidt is the recipe that straightens them out.
The recipe
Start with independent vectors
- First vector: just normalise it. .
- Second vector: remove the part of that points along (that's its projection, chapter 2), then normalise what's left: is the error vector of projecting onto the line of , so it's perpendicular to by construction.
- Third vector: remove its components along both earlier directions:
- And so on: each new vector loses its shadow on everything before it.
Because the 's are orthonormal, removing the projection onto their span is just a sum of separate one-dimensional projections (no normal equations needed). At every step, span exactly the same space as . If some comes out as zero, then was already in the span of the earlier vectors: the columns weren't independent.
QR: Gram–Schmidt written as a matrix
Read the recipe backwards. Each original vector is a combination of the 's that came before or with it:
where (the amounts we subtracted) and (the lengths we divided by). In matrix form, with the 's as the columns of :
is upper triangular because never needs a later . Its diagonal is positive. And since , you can always recover it as .
Why QR is the grown-up way to do least squares
Put into the normal equations : , and and the invertible cancel, leaving
Triangular systems are solved by back-substitution: the last equation has one unknown, the one above it has two, and so on. More importantly, you never form , which squares the sensitivity of the problem to rounding errors (chapter 10). This is what serious least-squares solvers do.
In practice nobody runs the textbook version. Modified Gram–Schmidt subtracts each projection from the running vector one at a time (), which is far less sensitive to rounding. Libraries like np.linalg.qr use Householder reflections, which are more stable still. The answer is the same and (up to signs).
Worked exampleGram–Schmidt on two vectors in 3D
, .
- , so and .
- . Subtract: .
- Check: ✓.
- , so .
So . Check the second column: ✓.
Watch outCommon misconceptions
- "Gram–Schmidt only normalises the vectors." Normalising makes them unit length; the subtraction is what makes them perpendicular. Both are needed.
- "The order doesn't matter." always points along . Reorder the inputs and you get a different orthonormal basis (for the same overall span).
- "Subtract the projection onto , not : same thing." It is the same projection, but if you use you must divide by . Forgetting that is the classic bug.
- " is just bookkeeping." It carries real information: for square , and a tiny warns that column is nearly dependent on the earlier ones.
In ML & deep learningWhere this shows up
Orthogonal initialisation in PyTorch (torch.nn.init.orthogonal_) takes a random Gaussian matrix and runs QR on it, keeping . Least-squares solvers (np.linalg.lstsq, statsmodels, R's lm) use QR or SVD rather than the normal equations. Gram–Schmidt-style orthogonalisation appears in optimisers that keep weight matrices orthogonal, in Krylov methods (Lanczos, Arnoldi) that compute a few eigenvectors of huge matrices like Hessians, and in the QR algorithm, the standard way computers find all eigenvalues of a matrix.
Practice (pick one answer per question)
The first Gram–Schmidt step on gives
- (0.6, 0.8)
- (3, 4)
- (0.75, 1)
- (0.8, 0.6)
Divide by the length 5: .
Continue with . What is ?
- (0.8, −0.6)
- (−0.8, 0.6)
- (0.64, −0.48)
- (1, 0)
. , with length . So . The opposite vector (−0.8, 0.6) is also perpendicular to , but Gram–Schmidt keeps the direction of (so ). (0.64, −0.48) is before normalising.
In from Gram–Schmidt, is…
- upper triangular with a positive diagonal
- diagonal
- lower triangular
- orthogonal
Column of only uses , so entries below the diagonal are 0. The diagonal entries are the lengths .
The entry of equals…
Row , column of is : how much of lies along . is , which is 0.
Running Gram–Schmidt, you get . What does that tell you?
- is a combination of and
- is perpendicular to and
- you made an arithmetic mistake, since can never be zero
is what's left of after removing its projection onto span. Nothing left means was entirely inside that span: the columns are dependent. If were perpendicular, nothing would be removed and .
With (tall , independent columns), the least-squares solution of comes from…
- solving by back-substitution
- solving
Substitute into : , and cancel . The other options don't even have matching shapes in general.
For (the columns from the first two questions), what is , and what is ?
- ,
- ,
- ,
- ,
, , . Since , . Directly: ✓.
Code it (optional: real Python runs in your browser and is graded by test cases)
Symmetric matrices and the spectral theorem
Watch: Symmetric matrices and positive definiteness (MIT OCW, Gilbert Strang) Rewatch: Eigenvectors and eigenvalues (3Blue1Brown)A symmetric matrix () always has real eigenvalues and perpendicular eigenvectors. So it is just a stretch along some set of perpendicular axes: , "rotate to the axes, stretch, rotate back".
In Module 1, chapter 14, eigenvectors were the special directions a matrix only stretches. For a general matrix they can be a disappointment: a rotation has none (in real numbers), a shear has only one direction, and even when there are enough of them they meet at odd angles. Symmetric matrices are the happy case where everything works perfectly.
A matrix is symmetric when it equals its own transpose: the entry in row , column equals the one in row , column , so it's a mirror image across the diagonal. For example .
The spectral theorem
Every real symmetric matrix has
- real eigenvalues (no complex numbers, ever), and
- a full set of orthonormal eigenvectors .
Put the eigenvectors in the columns of an orthogonal matrix and the eigenvalues on the diagonal of . Then , and since ,
Read it right to left, as in Module 1: takes the coordinates of along the eigenvector axes (chapter 1: coordinates are dot products), stretches each coordinate by its eigenvalue, and puts the result back in standard coordinates. The second form says is a weighted sum of projections onto its eigen-directions (each is a projection matrix from chapter 2).
Why are the eigenvectors perpendicular? Take and with . Compute two ways: it's , and, using , it's also . Two different numbers times the same are equal only if . (If an eigenvalue repeats, you get a whole plane of eigenvectors and can pick perpendicular ones inside it.)
The picture: circles become ellipses with eigenvector axes
Apply to every point of the unit circle. Along points are stretched by , along by , and those directions are perpendicular. So the circle becomes an ellipse whose axes point along the eigenvectors, with semi-axis lengths and . A negative eigenvalue flips that axis over but the ellipse looks the same.
Where symmetric matrices come from
They are everywhere in ML, because anything built as "all pairwise dot products" is symmetric:
- for any (it's the Gram matrix of the columns; ).
- Covariance matrices: entry is the covariance of features and .
- Hessians: the matrix of second derivatives of a loss, because .
- Kernel matrices , graph adjacency matrices and graph Laplacians.
Worked exampleDiagonalise and compute
Trace 4, determinant 3, so : , . Eigenvectors: (check: ) and (check: ). They're perpendicular, as promised.
Spectral form: ✓.
Powers are now easy, because (the inner 's cancel):
The same trick gives any function of : , , : apply the function to the eigenvalues.
Watch outCommon misconceptions
- "Every matrix has perpendicular eigenvectors." Only symmetric ones (more precisely, "normal" ones) are guaranteed to. has eigenvectors (1, 0) and (1, −1), at 45°.
- "Symmetric means invertible." No: is symmetric with eigenvalue 0.
- "Symmetric means positive eigenvalues." has eigenvalues 1 and −1. Positivity is the next chapter's extra condition.
- "Use
np.linalg.eig." For symmetric matrices usenp.linalg.eigh: it's faster, guarantees real output and orthonormal eigenvectors, and returns eigenvalues in ascending order.
In ML & deep learningWhere this shows up
PCA diagonalises the covariance matrix: its eigenvectors are the principal directions (chapter 8). The Hessian of a loss at a minimum is symmetric; its eigenvalues measure the curvature along perpendicular directions, which explains why gradient descent zig-zags when they differ wildly and is used to study "sharp" versus "flat" minima. Spectral clustering and graph neural networks are built on eigenvectors of graph Laplacians. Kernel methods (SVMs, Gaussian processes) rely on symmetric kernel matrices, and the "neural tangent kernel" describes very wide networks the same way.
Practice (pick one answer per question)
Which matrix is symmetric?
Symmetric means . Only the first has equal off-diagonal entries. The second is "skew-symmetric" (), a rotation-like matrix.
What are the eigenvalues of ?
- 6 and 1
- 5 and 2
- 7 and 6
- 3 and 4
Trace 7, determinant . Two numbers with sum 7 and product 6: 6 and 1. (5 and 2 are the diagonal entries; those are eigenvalues only for triangular matrices.)
(2, 1) is an eigenvector of that for . Which is an eigenvector for ?
- (1, −2)
- (1, 2)
- (2, −1)
- (−2, −1)
Eigenvectors of a symmetric matrix for different eigenvalues are perpendicular, so we need a vector perpendicular to (2, 1): (1, −2). Check: ✓. (−2, −1) is just , the same eigen-direction for 6.
maps the unit circle to an ellipse. What are its semi-axes?
- length 6 along (2, 1) and length 1 along (1, −2)
- length 5 along the x-axis and length 2 along the y-axis
- length 6 along (1, −2) and length 1 along (2, 1)
- length √6 along (2, 1) and length 1 along (1, −2)
The axes are the eigenvectors and each is stretched by its eigenvalue: 6 along (2, 1), 1 along (1, −2). (√6 would be the answer for .)
Which property is not guaranteed for every real symmetric matrix ?
- is invertible
- all eigenvalues of are real
- the eigenvectors can be chosen orthonormal
- with orthogonal
The spectral theorem promises real eigenvalues and an orthonormal eigenbasis, which is exactly . Nothing stops an eigenvalue from being 0, e.g. , so can be singular.
is a 3×2 matrix. What can you say about ?
- It is 2×2 and symmetric
- It is 3×3 and symmetric
- It is 2×2 but symmetric only if is
- It is 3×2
(2×3)(3×2) = 2×2. Its entry is (column )·(column ), which is the same as the entry. Formally .
. What is the top-left entry of ?
- 29525
- 1024
- 59049
- 29524
, and both projections have top-left entry ½. So . (1024 is , wrongly powering the entry; 29524 is the off-diagonal entry.)
Over all unit vectors , what is the largest value of for ?
- 6
- 5
- 7
- 9
In eigen-coordinates with . That's a weighted average of 6 and 1, largest (6) at . This ratio is the Rayleigh quotient; its max and min are the largest and smallest eigenvalues. (5 is the value at , not the max.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Positive-definite matrices and quadratic forms
Watch: Positive definite matrices and minima (MIT OCW, Gilbert Strang) Watch: Positive definite and semidefinite matrices (MIT 18.065, Gilbert Strang)A symmetric matrix defines a "quadratic form" , a bowl, a saddle or a dome. is positive definite when the bowl points up in every direction: for all , which happens exactly when all eigenvalues are positive.
Quadratic forms
For and ,
The diagonal entries give the squared terms; the off-diagonal entry (used twice) gives the cross term. Any expression with only degree-2 terms can be written this way, in any number of dimensions. The graph of is a surface over the plane, and it comes in a few shapes:
- positive definite (PD): except at the origin. A bowl; the origin is the unique minimum.
- positive semidefinite (PSD): . A bowl that may be flat along some direction (a trough).
- indefinite: is positive in some directions and negative in others. A saddle.
- negative definite: except at the origin. A dome.
Eigenvalues tell you everything
Use the spectral theorem (chapter 4): . In the eigenvector coordinates , the cross terms disappear:
A sum of squares weighted by the eigenvalues. It's positive for every nonzero exactly when every . One negative and you can walk downhill along its eigenvector: a saddle. A zero gives a flat direction. So:
The level curves of a PD matrix are ellipses with axes along the eigenvectors and semi-axis lengths : a big eigenvalue means a steep direction and a narrow ellipse.
Other tests that don't need eigenvalues
All of these are equivalent ways to say " is positive definite":
- Energy: for every .
- Eigenvalues: all .
- Leading minors (Sylvester's test): the top-left 1×1, 2×2, …, determinants are all positive. For 2×2: and .
- Cholesky: with lower triangular with a positive diagonal. Computers test PD by just trying Cholesky: it fails exactly when isn't PD.
- Gram form: for some with independent columns. Indeed , and it's 0 only if .
That last one explains why and covariance matrices are always at least PSD: they are sums of squares in disguise.
Worked exampleIs positive definite?
- Quadratic form: , a sum of squares that is zero only at the origin. PD ✓.
- Minors: and ✓.
- Eigenvalues: trace 4, det 3, so , both positive ✓. Eigenvectors for 3 and for 1, so the level curve is an ellipse reaching along and along .
- Cholesky: . Check : top-left 2, off-diagonal , bottom-right ✓.
Watch outCommon misconceptions
- "Positive entries mean positive definite." has all positive entries, but . Its eigenvalues are 4 and −2.
- "A negative entry rules it out." above is PD. (Negative diagonal entries do rule it out: .)
- "Checking and is enough." You need the determinant too: has positive diagonal but .
- "Positive determinant means PD." (2×2) has determinant and is negative definite. Two negative eigenvalues multiply to a positive number.
In ML & deep learningWhere this shows up
Minima of a loss: near a critical point a loss looks like a quadratic form in the Hessian. A PD Hessian means a true local minimum; an indefinite one means a saddle point, and in high-dimensional deep nets most critical points are saddles. Convexity: a twice-differentiable function is convex exactly when its Hessian is PSD everywhere, which is why least squares (Hessian ) has no bad local minima. Covariance matrices must be PSD, and a multivariate Gaussian needs a PD covariance ; sampling it uses the Cholesky factor (). Mahalanobis distance and kernel matrices in SVMs and Gaussian processes are PD quadratic forms too. And the ratio of the Hessian decides how badly gradient descent zig-zags (chapter 10).
Practice (pick one answer per question)
Write for and .
with . The off-diagonal 2 appears twice, giving .
Is positive definite?
- Yes: and
- No: the off-diagonal entry is bigger than
- No:
- We can't tell without computing the eigenvectors
Leading minors: and . In fact . The size of off-diagonal entries alone doesn't decide anything.
For which is positive definite?
always, and . At it's only semidefinite.
For , what is , and what shape is the graph of ?
- −4; a saddle
- 8; a bowl
- −4; a dome
- 2; a bowl
, so , while . Positive one way, negative another: indefinite, a saddle. Eigenvalues: 4 and −2.
The level curve is an ellipse with semi-axes…
- ½ along x and 1 along y
- 4 along x and 1 along y
- 2 along x and 1 along y
- 1 along x and ½ along y
, semi-axes : along x and 1 along y. Check: gives ✓. The steep direction (big λ) is the short axis.
For any matrix , the matrix is…
- always positive semidefinite, and positive definite exactly when has independent columns
- always positive definite
- positive definite exactly when is square
- indefinite unless is symmetric
. It equals 0 for some exactly when has a nonzero solution, i.e. the columns are dependent.
A 2×2 PD matrix has eigenvalues 9 and 1. In its level curve , what is the ratio of the longest axis to the shortest?
- 3
- 9
- 1/3
- 81
Semi-axes are and , so the ratio is . (The ratio of eigenvalues, 9, is the condition number; the axes' ratio is its square root.)
The gradient of is . For , what is it at ?
- (2, 2)
- (1, 1)
- (4, 4)
- (2, −2)
, so . Directly: , and ✓. (1, 1) forgets the factor 2.
Code it (optional: real Python runs in your browser and is graded by test cases)
The singular value decomposition: rotate, stretch, rotate
Watch: SVD overview (Steve Brunton) Watch: SVD mathematical overview (Steve Brunton) Watch: Singular value decomposition (MIT OCW, Gilbert Strang) Watch: SVD visualized (Visual Kernel)Every matrix, of any shape, is a rotation, then a stretch along the axes, then another rotation: . The stretch factors are the singular values, and they tell you almost everything about the matrix.
The spectral theorem (chapter 4) was wonderful but picky: it only works for symmetric matrices. Most matrices in ML aren't symmetric, and most aren't even square: a weight matrix maps 768 numbers to 3072, a data matrix has 10,000 rows and 50 columns. The singular value decomposition is the version that works for every matrix.
The statement
Any matrix can be written
- is an orthogonal matrix. Its columns are the right singular vectors, an orthonormal basis of the input space.
- is and zero except on its diagonal, which holds the singular values .
- is an orthogonal matrix. Its columns are the left singular vectors, an orthonormal basis of the output space.
Column by column, says
That's the key sentence: there is a perpendicular set of input directions that maps to a perpendicular set of output directions, just stretched by . Eigenvectors asked for , the same direction in and out, which often fails. The SVD lets the output basis differ from the input basis, and then it never fails.
The picture
Read right to left, like any product of transformations (Module 1, chapter 4):
- rotates (or reflects) the input so that the special directions line up with the coordinate axes.
- stretches along each axis by (and, if , adds or drops dimensions).
- rotates (or reflects) the axes into the output directions .
So a unit circle always becomes an ellipse (in 2D) whose semi-axes are and . Even a shear, which looks nothing like a stretch, is secretly rotate–stretch–rotate.
Where the pieces come from
Multiply by its transpose and the 's cancel:
That's a spectral decomposition of the symmetric PSD matrix ! So the are the eigenvectors of , and its eigenvalues are . In the same way the are eigenvectors of . A practical recipe for small matrices: find the eigenvalues and eigenvectors of , take square roots, then get each . (Real libraries avoid forming , for the accuracy reasons in chapter 10.)
What the singular values tell you
- Rank = the number of nonzero . The first columns of span the column space; the last columns of span the null space.
- Biggest stretch: , reached at . This is the spectral norm .
- Determinant (square ): , since rotations don't change area.
- Sum of rank-one pieces: , ordered from most to least important. Chapter 7 is built on this.
The thin (economy) SVD keeps only the first or columns of and ; np.linalg.svd(A, full_matrices=False) returns that. Note that numpy returns (called Vh), not , and the singular values as a 1-D array.
Worked exampleSVD of
- . Eigenvalues: trace 50, determinant , so 45 and 5.
- Singular values and . Check: ✓.
- Eigenvectors of : , .
- and . They're perpendicular: ✓.
So the unit circle becomes an ellipse with its long axis (length 6.708) along (1, 3) and its short axis (2.236) along (3, −1). Note that 's eigenvalues are 3 and 5 (it's triangular): not the singular values.
Watch outCommon misconceptions
- "Singular values are the eigenvalues." Only for symmetric PSD matrices. In general . has eigenvalues 0, 0 but singular values 2, 0.
- "Singular values can be negative." Never: signs are absorbed into or . A symmetric matrix with eigenvalues 4 and −3 has singular values 4 and 3.
- "The SVD is unique." The singular values are. The vectors are only unique up to sign (flip and together), and less unique when singular values repeat. Two libraries can give different-looking but equally correct answers.
- "
np.linalg.svdreturns V." It returnsU, S, VhwhereVhis : the right singular vectors are its rows.
In ML & deep learningWhere this shows up
The SVD may be the single most useful matrix fact in data science. The next four chapters are all applications: low-rank compression (chapter 7), PCA (chapter 8), the pseudoinverse and least squares (chapter 9), and the condition number (chapter 10). In deep learning, of each weight matrix bounds how much a layer can amplify its input, which is why spectral normalisation (dividing by ) stabilises GAN training and why it appears in robustness and generalisation bounds. The singular-value spectrum of trained weight matrices is used to diagnose training, and it's typically dominated by a few large values, which is the observation that makes LoRA work (chapter 12). Latent semantic analysis, the ancestor of word embeddings, is an SVD of a word–document matrix.
Practice (pick one answer per question)
What are the singular values of ?
- 3 and 2
- 3 and −2
- 9 and 4
- √3 and √2
It stretches x by 3 and y by 2 (with a flip). The flip goes into ; singular values are always . (9 and 4 are the eigenvalues of .)
For , what is ?
- 15
- 45
- 8
- 225
, and rotations don't change area, so the product of the stretches is 15. Check with the worked example: ✓. (225 is .)
The columns of (right singular vectors) are eigenvectors of…
, a spectral decomposition, so 's columns are its eigenvectors. has the 's instead.
A matrix has singular values 7, 2 and 0. What is its rank?
- 2
- 3
- 9
- 1
Rank = number of nonzero singular values. One direction is squashed to 0.
is 5×3. What are the shapes in the full SVD ?
- : 5×5, : 5×3, : 3×3
- : 5×3, : 3×3, : 3×3
- : 3×3, : 3×5, : 5×5
- : 5×5, : 3×3, : 3×5
is a basis of the output space , of the input space , and has 's shape. The second option is the thin SVD, which is also valid, but it isn't the full one.
has eigenvalues 0 and 0. What are its singular values?
- 2 and 0
- 0 and 0
- 2 and 2
- 4 and 0
, eigenvalues 4 and 0, so . sends (0, 1) to (2, 0): a real stretch by 2 that the eigenvalues completely miss.
What is the largest value of over unit vectors , for ?
- 5
- 45
It's , reached at : , length ✓. is the Frobenius norm , which is bigger than any single stretch.
A symmetric matrix has eigenvalues 4 and −3. What are its singular values?
- 4 and 3
- 4 and −3
- 16 and 9
- 2 and √3
; move the sign of −3 into one column of the left factor: with . That's an SVD with . For symmetric matrices, .
Code it (optional: real Python runs in your browser and is graded by test cases)
Low-rank approximation (Eckart–Young) and image compression
Watch: SVD matrix approximation (Steve Brunton) Watch: SVD image compression (Steve Brunton) Watch: Eckart–Young, the closest rank-k matrix (MIT 18.065, Gilbert Strang)The SVD writes a matrix as a sum of rank-one layers, , sorted from most to least important. Keeping the first layers gives the best possible rank- approximation (the Eckart–Young theorem), and the error is exactly the singular values you threw away.
A matrix is a stack of rank-one layers
Multiply out column-times-row and you get
Each is an outer product: a whole matrix built from one column and one row. Every row of it is a multiple of and every column a multiple of , so it has rank 1. If is a grayscale image, each layer is a "plaid" pattern: a fixed row profile, faded up and down by a column profile. The 's say how loud each layer is, and they're sorted.
The rank- truncation keeps the first layers:
where and are the first columns. Storing it takes columns of length , rows of length and numbers: numbers instead of .
Eckart–Young: you can't do better
The remarkable fact is that this greedy choice is optimal. Among all matrices of rank at most ,
and no rank- has a smaller error in either norm. Here is the largest stretch (chapter 6) and is the Frobenius norm, the square root of the sum of all squared entries, which also equals . So the error of the best rank- approximation is read straight off the discarded singular values, and
Real data usually has a fast-decaying spectrum: a few big singular values carrying the structure, then a long tail of small ones that is mostly noise or fine detail. That's why low-rank approximations work so well, and why truncating can even remove noise.
Worked exampleHow much does truncation cost?
Suppose a 3×3 matrix has singular values 6, 3, 2.
- Best rank-1 approximation: spectral error , Frobenius error . Energy kept: .
- Best rank-2: spectral error 2, Frobenius error 2, energy kept .
Now an image: a 512×512 grayscale picture with . Storage numbers instead of : about 19.6% of the original. For photos, usually looks nearly perfect. (JPEG does better with a different transform, but the idea of keeping the big coefficients is the same.)
Watch outCommon misconceptions
- "Rank- means keeping rows or columns of the picture." Every layer covers the whole matrix. is a blurry version of the entire image, not its first row.
- "Low rank always saves space." Only when . For a 100×100 matrix, already costs more than the original.
- "The error is the first dropped singular value in every norm." In the spectral norm, yes. The Frobenius error is the root-sum-square of all the dropped ones.
- "You could pick better layers by hand." Eckart–Young says no: for these norms no rank- matrix beats .
In ML & deep learningWhere this shows up
Model compression: replace a dense weight matrix () by its truncated SVD, i.e. two thin layers and , cutting parameters and compute from to . LoRA (chapter 12) trains only a low-rank update. Recommender systems assume the user–item ratings matrix is approximately low-rank. Denoising and matrix completion rely on signals being low-rank while noise is spread over all singular values. Attention matrices, embedding tables and gradients are often approximately low-rank too, which methods like Linformer and GaLore exploit.
Practice (pick one answer per question)
How many numbers does a rank-10 SVD approximation of a 100×200 matrix need (, and the 's)?
- 3,010
- 20,000
- 3,000
- 2,000
, versus 20,000 for the full matrix. (3,000 forgets the 10 singular values; you could also fold them into and store 3,000.)
has singular values 6, 3, 2. What is , the spectral-norm error of the best rank-1 approximation?
- 3
- 6
- 5
Eckart–Young: . The leftover stretches by at most 3.
Same . What is the Frobenius error ?
- 5
- 3
- 13
. Adding them (5) isn't how norms of perpendicular pieces combine; 13 forgets the square root.
Same . What fraction of the squared Frobenius norm ("energy") does keep?
- 45/49 ≈ 91.8%
- 9/11 ≈ 81.8%
- 36/49 ≈ 73.5%
- 2/3 ≈ 66.7%
. Using the unsquared 's gives (6+3)/11, which isn't energy. 36/49 is what keeps.
What does the Eckart–Young theorem say?
- No matrix of rank is closer to than , in the spectral or Frobenius norm
- equals whenever
- Every matrix has rank at most
- The singular values of are
Truncating the SVD is the optimal rank- approximation. The singular values of are the first ; those of are the rest.
For a 100×100 matrix, what is the smallest at which storing numbers no longer saves space?
- 50
- 100
- 49
- 10
Need , so . At : 9,849 (still saves). At : 10,050 (more than the original).
What are the singular values of the rank-one matrix ?
- and 0
- 11 and 0
- 5 and
- 3 and 8
, so and the other is 0. Check with Frobenius: ✓. (11 is the trace, which is the nonzero eigenvalue, not the singular value.)
You compress a photo with . What does the result look like?
- A "plaid" image: every row is a scaled copy of the same row pattern
- The first row of the photo, repeated
- A single-colour image of the average brightness
- The photo at a lower resolution, with square pixels
: row is , so all rows share the shape , just brighter or darker. It captures the dominant horizontal and vertical structure of the whole picture, not any single row.
Code it (optional: real Python runs in your browser and is graded by test cases)
PCA through the SVD
Watch: Principal Component Analysis, step by step (StatQuest) Watch: Principal Component Analysis (Steve Brunton) Watch: Principal Component Analysis (Visually Explained)PCA finds the orthonormal directions along which centred data varies the most. Take the SVD of the centred data matrix, : the rows of are the principal directions, gives each point's coordinates along them, and is the variance each direction captures.
You have data points with features each, stored as the rows of an matrix . Maybe pixel values per digit image, or measurements per patient. You'd like a few new axes, combinations of the features, that capture as much of the data's spread as possible, so you can plot it, compress it or denoise it. That's principal component analysis.
The recipe
- Centre the data: subtract each column's mean, . PCA is about spread around the centre, not the location of the cloud.
- Covariance: , a symmetric PSD matrix. Entry is the variance of feature ; entry is the covariance of features and .
- The variance of the data along a unit direction is , a quadratic form (chapter 5). It's maximised by the top eigenvector of (the Rayleigh quotient from chapter 4), and the maximum variance is the top eigenvalue. The next-best direction perpendicular to it is the second eigenvector, and so on.
So the principal directions are the eigenvectors of the covariance matrix: you saw this in Module 1's PCA-from-scratch problem. Now the SVD shortcut.
PCA is the SVD of the centred data
Take the SVD . Then, as in chapter 6,
That is the spectral decomposition of , handed to us for free. Reading it off:
- Principal directions (also called components, or loadings) = the columns of = the rows of
Vt. - Variance along direction = .
- Scores (each point's coordinates along the principal axes) = .
- Explained variance ratio of component = .
To reduce to dimensions keep the first scores, (an matrix). To go back, . By Eckart–Young (chapter 7), this reconstruction is the best rank- approximation of the centred data: PCA minimises the total squared perpendicular distance from the points to a -dimensional subspace.
Why go through the SVD rather than forming and calling eigh? Forming squares the condition number (chapter 10), losing accuracy for the small components, and when is huge the matrix may not even fit in memory. scikit-learn's PCA uses the SVD.
Worked examplePCA of four points
Points (2, 1), (−2, −1), (1, 2), (−1, −2). The mean is already (0, 0), so .
- , with eigenvalues 18 and 2, so , .
- Principal directions: , .
- Variances (with ): along PC1, along PC2. PC1 explains .
- Scores on PC1: . Check: ✓.
Compressing to one number per point keeps 90% of the variance.
Watch outCommon misconceptions
- "You can skip centring." Without it the first "component" mostly points at the mean of the data, not along its spread.
- "PCA is the same as the regression line." Regression minimises vertical errors in (chapter 2); PCA minimises perpendicular distances and treats all features alike. They give different lines.
- "Units don't matter." A feature measured in millimetres has a million times the variance of the same feature in kilometres and will dominate. Standardise (divide each feature by its standard deviation) when units differ; that's PCA on the correlation matrix.
- "The sign of a component means something." and are equally valid; different libraries may flip them.
- "PCA finds clusters or the most useful features for prediction." It finds directions of large variance. Those can be irrelevant to the label you care about.
In ML & deep learningWhere this shows up
Dimensionality reduction before training or clustering, and visualisation of embeddings (often PCA to 50 dimensions, then t-SNE or UMAP). Whitening: rotate onto the principal axes and divide by so the features are uncorrelated with unit variance. Eigenfaces for face recognition. Analysing neural networks: PCA of hidden activations or of word embeddings reveals the main directions of variation, and probing work finds concepts lying along a few directions. A linear autoencoder trained with squared error learns exactly the PCA subspace.
Practice (pick one answer per question)
What is the first step of PCA?
- Subtract the mean of each feature (column)
- Normalise each data point (row) to length 1
- Sort the data points
- Compute the inverse of
Centre each column. PCA measures spread around the mean. Normalising rows changes the data's geometry, and a data matrix usually has no inverse.
If (rows = data points), the principal directions are…
- the columns of (rows of )
- the columns of
- the rows of
- the diagonal of
holds eigenvectors of , which live in feature space (length ). 's columns have length : one entry per data point (they're the normalised scores).
A centred dataset with points has singular values 6 and 3. What is the variance along PC1?
- 4
- 3.6
- 6
- 36
. Dividing by instead gives 3.6 (the biased version; numpy's np.cov uses ).
Same data. What fraction of the variance does PC1 explain?
- 80%
- 66.7%
- 50%
- 90%
. Using the unsquared 's gives , which is wrong: variance goes with .
The PCA scores (each point's coordinates along the principal axes) are…
Coordinates in an orthonormal basis are dot products (chapter 1): row of holds . And . doesn't even have matching shapes unless .
You run PCA on height (in mm) and weight (in kg) without standardising. What happens?
- PC1 points almost entirely along height, just because its numbers are bigger
- Nothing; PCA is unit-free
- PC1 points along weight because kg is the SI unit
- PCA refuses to run on mixed units
Heights in mm have variances in the thousands, weights in kg in the tens to hundreds. Variance depends on units, so height dominates. Standardise first if the units are arbitrary.
For the points (2, 1), (−2, −1), (1, 2), (−1, −2), what fraction of the variance lies along PC1?
- 90%
- 50%
- 80%
- 100%
, eigenvalues 18 and 2, so . (They don't all lie on a line, so it can't be 100%.)
A dataset has points in dimensions. After centring, at most how many principal components have nonzero variance?
- 49
- 50
- 1000
- 950
is 50×1000, so its rank is at most 50. Centring makes the rows sum to zero, a dependency among them, so the rank drops to at most 49. At most 49 nonzero singular values, hence 49 components with positive variance.
Code it (optional: real Python runs in your browser and is graded by test cases)
The pseudoinverse
Watch: Linear systems, least squares and the pseudoinverse (Steve Brunton) Watch: Left and right inverses; pseudoinverse (MIT OCW, Gilbert Strang)Every matrix has a pseudoinverse : undo the rotations, and invert every stretch you can (the nonzero 's) while leaving the squashed directions at zero. is the best answer to there is: the least-squares solution, and the shortest one if there are many.
exists only for square matrices that don't squash anything (Module 1, chapter 7). But we constantly want to "solve" systems that are too tall (more equations than unknowns, no exact solution), too wide (fewer equations than unknowns, infinitely many solutions), or squashed (rank-deficient, often both problems at once). The pseudoinverse handles all of them with one formula.
Building it from the SVD
means: rotate by , stretch by , rotate by . To undo it, go backwards: rotate back by , un-stretch by , rotate back by . The only problem is : that direction was crushed and can't be recovered, so we leave it at 0. Define (shape ) by putting where and 0 elsewhere. Then
It maps each back to , and sends everything perpendicular to the column space to .
What means
Split the problem in two, using the orthonormal bases:
- Output side: might not be reachable. The part of along the 's (the column space) can be hit; the rest can't. So we aim at the projection of onto the column space: the least-squares choice (chapter 2). Indeed is exactly that projection.
- Input side: if has a null space, adding any null-space vector to a solution gives another solution. only ever produces combinations of the with , which span the row space, perpendicular to the null space. By Pythagoras, adding anything from the null space only makes the vector longer. So is the minimum-norm solution. is the projection onto the row space.
In short: minimises , and among all minimisers it has the smallest .
Familiar special cases
- Square and invertible: .
- Tall, independent columns (regression): , the normal-equations solution from chapter 2. It's a left inverse: , but .
- Wide, independent rows (underdetermined): , a right inverse: . It picks the shortest of infinitely many exact solutions.
- Rank-deficient: neither formula works (the inverted matrix is singular), but the SVD formula still does.
Small singular values: the cutoff
In floating point, a singular value is rarely exactly 0; it's instead, and would be a monstrous . So np.linalg.pinv treats any below a cutoff (rcond times ) as zero. Raising the cutoff deliberately is a form of regularisation called truncated SVD: you give up fitting the weak directions to avoid amplifying noise. Chapter 10 explains why that matters.
Worked examplePseudoinverse of
squashes the plane onto the line through (1, 1). Its SVD has , , and . So
Solve . Every output of has equal entries, so (2, 0) is unreachable; the closest reachable point is its projection onto (1, 1), which is (1, 1). Any with hits it: (1, 0), (0, 1), (2, −1), … The pseudoinverse gives , and it's the shortest of them, with length versus 1 for (1, 0). It's also perpendicular to the null-space direction (1, −1) ✓.
Watch outCommon misconceptions
- " and ." Both are projections. They're identities only when is invertible; for a tall full-rank just the first one is.
- "Pseudoinverse means 'approximately the inverse' of a nearly singular matrix." For an invertible matrix it is exactly the inverse, however badly conditioned. The cutoff is what changes things, and only for tiny 's.
- ", just like inverses." Not in general. It holds in special cases (e.g. with orthonormal columns), but don't rely on it.
- "Use
pinvto solve every regression." It works, butnp.linalg.lstsq(which uses the SVD without forming ) is cheaper and is the standard tool.
In ML & deep learningWhere this shows up
Linear regression in closed form is , and it still works when features are duplicated or collinear (the "dummy variable trap"). Over-parameterised models (more weights than data points) have infinitely many weight vectors that fit the training data perfectly. Gradient descent on linear least squares started from zero converges to exactly the minimum-norm one, : an example of the "implicit bias" of gradient descent, and a starting point for understanding double descent. Pseudoinverses also appear in ridge regression as , in robotics (inverse kinematics) and in recovering linear layers or signals from measurements.
Practice (pick one answer per question)
What is the pseudoinverse of ?
- It doesn't exist, because the matrix is singular
Invert the nonzero stretch, leave the zero alone. Every matrix has a pseudoinverse; that's the point of it.
If is square and invertible, equals…
All , so and . is the inverse only for orthogonal matrices.
One equation, two unknowns: . What is the minimum-norm solution ?
- (1, 1)
- (2, 0)
- (0, 2)
- (0.5, 0.5)
, , so , length . (2, 0) also solves it but has length 2. (0.5, 0.5) doesn't solve it.
The matrix is…
- the projection onto the column space of
- always the identity
- the projection onto the null space of
- the zero matrix when is singular
, the projection onto the span of the with : the column space.
is tall with independent columns. Which statement is true?
- and , but
- and
- and are both
is invertible (independent columns), giving the left inverse. is a singular matrix, so the second formula fails, and is a projection onto an -dimensional subspace of , not the identity.
is 3×5. What is the shape of ?
- 5×3
- 3×5
- 3×3
- 5×5
maps ; goes back, . Same shape as .
For and , what is ?
- (1.5, 1.5)
- (3, 3)
- (2, 1)
- (4, 2)
, so . Check: , the projection of (4, 2) onto the line through (1, 1) ✓. (3, 3) is that projection, the output, not the input.
Why does np.linalg.pinv zero out singular values below a small cutoff instead of inverting them?
- Inverting a tiny gives a huge that blows up rounding errors and noise
- Small singular values are always exactly zero in theory
- To make the result symmetric
- To make
A of is usually rounding error; multiplying by would turn tiny noise in along into an enormous component along . Cutting it off trades a little bias for a lot of stability (chapter 10).
Code it (optional: real Python runs in your browser and is graded by test cases)
Norms and the condition number
Watch: Survey of difficulties with Ax = b (MIT 18.065, Gilbert Strang) Watch: SVD and optimal truncation (Steve Brunton)Norms measure the size of vectors and matrices. The condition number measures how much solving can magnify a small relative error in . An ill-conditioned problem (huge ) turns tiny noise into huge mistakes, no matter how good your algorithm is.
Vector norms: different ways to measure size
A norm is a length: zero only for , scales as , and obeys the triangle inequality . Three are used constantly:
- , the ordinary Euclidean length. Its "unit ball" is a circle.
- , the "taxicab" length. Unit ball: a diamond.
- , the largest entry. Unit ball: a square.
For (3, −4): , , . In ML, the L2 penalty (weight decay) shrinks all weights smoothly, while the L1 penalty (lasso) pushes many weights to exactly zero: the corners of the diamond lie on the axes.
Matrix norms
- Spectral norm : the biggest stretch (chapter 6).
- Frobenius norm : treat the matrix as one long vector.
Both satisfy , which is what lets you bound how errors grow through a chain of layers.
The condition number
Suppose and the right-hand side is measured with a small error . The solution moves by . How bad can that be, relatively?
- : an error along the weakest direction gets blown up by .
- , so .
Multiply them:
The condition number is the worst-case magnification of relative error, and the worst case really happens: when lies along and the error along . always; for orthogonal matrices (perfect); for singular ones.
Rule of thumb: you lose about significant digits. Double precision carries about 16, so leaves you around 6 trustworthy digits, and at the answer can be pure noise.
Geometrically, in 2D: solving means intersecting two lines. If the lines are nearly parallel, nudging one of them slides the intersection a long way. That's a large .
Why the normal equations are risky, and what to do
has singular values , so . If , forming gives and throws away 5 extra digits. That's why QR (chapter 3) and SVD-based solvers are preferred for least squares. Other remedies:
- Rescale features so columns have similar sizes (a column in metres next to one in micrometres is a self-inflicted large ).
- Regularise: ridge regression solves . Adding lifts every to , so the condition number becomes .
- Truncate: drop tiny singular values (the pseudoinverse cutoff, chapter 9).
- Precondition: solve an equivalent, better-conditioned system.
Worked exampleA tiny change, a huge jump
, . The solution is .
Now change to , a relative change of . The new solution is ! The relative change in is : an amplification of about 2,800.
The bound explains it: , , so . The two equations describe nearly the same line, so the data barely pins down where they cross.
Watch outCommon misconceptions
- "A small determinant means ill-conditioned." (10×10) has determinant but : it's perfectly conditioned. Conditioning is about the ratio of stretches, not their product.
- "A better algorithm fixes ill-conditioning." A stable algorithm avoids adding error (e.g. by not squaring ), but the sensitivity is a property of the problem. If the data has noise, a large amplifies it whatever you do; only changing the problem (more data, regularisation) helps.
- " only matters for solving equations." It also governs how fast gradient descent converges on a quadratic: the number of steps grows roughly like the condition number of the Hessian.
In ML & deep learningWhere this shows up
Optimisation: on a loss surface whose Hessian has condition number , gradient descent zig-zags across the narrow valley and needs roughly times more steps. Feature standardisation, batch normalisation and adaptive optimisers (Adam, RMSProp) all act partly as cheap preconditioners. Deep networks: the product of many weight matrices can have exploding or vanishing singular values; orthogonal initialisation and normalisation layers keep the spectrum near 1. Regression: collinear features (multicollinearity) give a huge and wildly unstable coefficients; ridge regression is the standard fix. Numerics: training in float16 or bfloat16 has only about 3 significant digits, so conditioning matters even more.
Practice (pick one answer per question)
What is ?
- 7
- 5
- 4
- −1
Sum of absolute values: . (5 is the L2 norm, 4 the L∞ norm, and −1 forgets the absolute values.)
What is ?
- 6
- 2
- 9
- −6
The largest absolute entry: 6.
What is the condition number of ?
- 50
- 2.5
- 5
- 1
The singular values are 5, 2 and 0.1, so . (2.5 uses the wrong smallest value.)
What is the Frobenius norm of ?
- 5
- 9
- 25
. It's a rank-one matrix , so is its only nonzero singular value, and the two norms agree.
and is accurate to about 7 significant digits. Roughly how many digits of the solution can you trust in the worst case?
- about 1
- about 7
- about 13
- none at all
You lose about digits: . Adding the digits (13) gets the direction backwards.
. What is ?
- 1000
- 2000
has singular values , so the ratio is squared. That's why the normal equations are avoided for ill-conditioned least squares.
What is the condition number of any orthogonal matrix ?
- 1
- 0
- it depends on the size of
All singular values of are 1 (it preserves lengths), so , the best possible. Rotations never amplify relative errors.
has singular values 10 and 0.1. Ridge regression uses with . What is its condition number (compared with for )?
- 100
- 101
- 10
Eigenvalues of are 100 and 0.01; adding 1 gives 101 and 1.01, a ratio of exactly 100. Regularisation trades a little bias for a hundredfold improvement in conditioning here.
Code it (optional: real Python runs in your browser and is graded by test cases)
Tensors, broadcasting and einsum
Watch: Broadcasting in Python (DeepLearning.AI, Andrew Ng) Watch: Einsum is all you need (Aladdin Persson)Real ML code works with tensors: arrays with many axes, like a batch of sentences of token vectors, shape (B, T, D). Broadcasting stretches size-1 axes so arrays of different shapes can be combined, and einsum names every axis so you can say exactly which ones to multiply and which to sum. Most PyTorch bugs are shape bugs; these rules are how you avoid them.
Tensors are just arrays with more axes
A scalar has shape (), a vector (n,), a matrix (m, n). Keep going and you have a tensor (in ML, "tensor" just means an n-dimensional array). Typical shapes:
- a batch of images:
(B, C, H, W)in PyTorch (batch, colour channels, height, width),(B, H, W, C)in TensorFlow; - a batch of token embeddings in a transformer:
(B, T, D)(batch, sequence length, model dimension); - attention scores:
(B, heads, T, T).
Every operation says what it does to each axis. x.sum(axis=1) removes axis 1; keepdims=True keeps it with size 1, which (as we'll see) is often what you need to broadcast the result back. reshape regroups the same numbers in a new shape (order preserved); transpose / permute reorders axes. Mixing those two up silently scrambles your data.
Broadcasting: the rules
Element-wise operations (+ - * /, comparisons) need equal shapes, except that numpy and PyTorch will broadcast:
- Line the two shapes up from the right. If one has fewer axes, pad it on the left with 1s.
- For each axis, the sizes must be equal, or one of them must be 1.
- A size-1 axis is (virtually) copied to match the other; the result takes the larger size. No memory is actually copied.
So (B, T, D) + (D,) works: the bias vector is added to every token of every sequence. (4, 3) + (3,) → (4, 3). (5, 1) + (1, 6) → (5, 6), an "outer sum". But (2, 3) + (2,) fails: lined up from the right, 3 meets 2. To add a per-row value you need shape (2, 1), e.g. x - x.mean(axis=1, keepdims=True).
The silent killer: y of shape (n,) minus y_hat of shape (n, 1) broadcasts to (n, n). No error, just a wrong loss computed from meaningless differences. Check your shapes, or use .squeeze() / .reshape(-1) deliberately.
Matrix multiplication on tensors
A @ B treats the last two axes as matrices and broadcasts all the axes in front as a batch: (B, T, D) @ (D, E) → (B, T, E) (one linear layer applied to every token), and (B, h, T, d) @ (B, h, d, T) → (B, h, T, T).
einsum: name your axes
np.einsum (and torch.einsum) takes a little formula. Give every axis of every input a letter, then list the output's letters after ->. The rule: multiply matching entries; any letter that doesn't appear in the output is summed over.
| einsum | meaning | math |
|---|---|---|
'i,i->' | dot product | |
'i,j->ij' | outer product | |
'ij,j->i' | matrix × vector | |
'ij,jk->ik' | matrix × matrix | |
'ij->ji' | transpose | |
'ii->' | trace | |
'bij,bjk->bik' | batched matmul | |
'bhqd,bhkd->bhqk' | attention scores per batch and head |
Letters that share a name must have the same size. The cost is the product of the sizes of all distinct letters: for 'ij,jk->ik' that's multiply-adds, the familiar cost of a matrix product.
Worked exampleShapes inside self-attention
A batch of sentences, tokens each, model dimension : X has shape (2, 5, 8). A query weight matrix is (8, 8).
Q = X @ W_Q: (2, 5, 8) @ (8, 8) → (2, 5, 8). The matmul acts on the last two axes and broadcasts over the batch.- Scores:
np.einsum('btd,bsd->bts', Q, K)→ (2, 5, 5): for each sentence, every query token dotted with every key token; is summed because it's missing from the output. Equivalent toQ @ K.transpose(0, 2, 1). Cost: multiply-adds. - Scale and normalise:
scores / np.sqrt(8)broadcasts a scalar; the softmax subtractsscores.max(axis=-1, keepdims=True), shape (2, 5, 1), which broadcasts back across the last axis. Withoutkeepdimsit would be (2, 5) and line up wrongly against (2, 5, 5): 5 meets 5, 2 meets 5, error (or worse, a silent bug if the sizes happened to match).
Watch outCommon misconceptions
- "Shapes are aligned from the left." From the right.
(3,) + (3, 4)fails (3 meets 4), even though the first axes match. - "
(n,)and(n, 1)are the same vector." They broadcast completely differently.(n,)behaves like a row(1, n). - "
reshapeandtransposedo the same thing."x.reshape(3, 2)of a 2×3 array keeps the reading order 1,2,3,4,5,6;x.Tmoves entries. Only one of them is a matrix transpose. - "
*is matrix multiplication." In numpy and PyTorch*is element-wise (with broadcasting);@is the matrix product.
In ML & deep learningWhere this shows up
Everywhere. Adding a bias, normalising features, layer norm (subtract the mean over the last axis with keepdims), softmax, masking attention with a (T, T) mask broadcast over batch and heads, pairwise distances for k-NN and contrastive losses (X[:, None, :] - Y[None, :, :], shape (n, m, d)), and every attention implementation are broadcasting and einsum. Libraries such as einops extend einsum's "name your axes" idea to reshapes and repeats, because named axes make shape bugs hard to write.
Practice (pick one answer per question)
What is the shape of A + b with A of shape (4, 3) and b of shape (3,)?
- (4, 3)
- error
- (3, 4)
- (4, 3, 3)
Pad b to (1, 3); then 3 meets 3 and 1 stretches to 4. The vector is added to every row.
Shape of (5, 1) + (1, 6)?
- (5, 6)
- error
- (5, 1)
- (6, 5)
Each axis has a 1 on one side, so both stretch: an "outer sum" table of shape (5, 6).
Shape of (2, 3) + (2,)?
- error
- (2, 3)
- (2, 2, 3)
- (3, 2)
Right-aligned, 3 meets 2: neither is 1, so it fails. Reshape the second to (2, 1) to add one number per row.
A is (3, 4) and x is (4,). What is np.einsum('ij,j->i', A, x)?
- the matrix–vector product , shape (3,)
- the outer product, shape (3, 4)
- an error, because
jappears twice - the element-wise product, shape (3, 4)
j is in both inputs but not the output, so it's summed: . Repeating letters is the whole point of einsum.
y has shape (100,) and y_hat has shape (100, 1). What does ((y - y_hat)**2).mean() compute?
- a mean over a (100, 100) array of all pairwise differences: a silent bug
- the correct mean squared error
- an error about mismatched shapes
- a (100, 1) array
(100,) is treated as (1, 100); against (100, 1) both axes stretch, giving (100, 100). No error is raised. Fix with y_hat.reshape(-1) or y_hat[:, 0].
Q and K both have shape (2, 4, 10, 16) = (batch, heads, tokens, head dim). Shape of np.einsum('bhqd,bhkd->bhqk', Q, K)?
- (2, 4, 10, 10)
- (2, 4, 16, 16)
- (2, 4, 10, 16)
- (2, 4, 10)
Output letters b, h, q, k have sizes 2, 4, 10, 10. d (16) is summed away. One 10×10 score matrix per batch and head.
What does np.einsum('ii->', A) compute for a square A?
- the trace
- the sum of all entries
- the diagonal as a vector
- the determinant
Using the same letter twice in one input picks the diagonal; leaving it out of the output sums it. 'ii->i' would return the diagonal itself, and 'ij->' the sum of all entries.
How many multiply-adds does np.einsum('bij,bjk->bik', A, B) take with b = 8, i = 32, j = 64, k = 16?
- 262,144
- 4,096
- 16,384
- 8,192
The product of all distinct letters' sizes: . (4,096 = 8·32·16 is the number of output entries; each needs 64 multiply-adds.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Matrix factorizations in ML: recommenders, LoRA and low-rank updates
Watch: How does Netflix recommend movies? Matrix factorization (Luis Serrano) Watch: LoRA explained visually, with PyTorch code (Umar Jamil)A recurring trick in ML: approximate a big matrix by the product of two thin ones, with only columns each. In recommender systems the thin factors are learned "taste" and "trait" vectors; in LoRA they're a tiny trainable update added to a frozen giant weight matrix. Both work because the important structure is low-rank.
The pattern
An matrix of rank can always be written as with of shape and of shape (the truncated SVD of chapter 7 is one way, with ). Instead of numbers you store . Entry becomes a dot product of two short vectors:
When the SVD isn't available (missing entries) or isn't what we want (we want to learn the factors by gradient descent), we optimise and directly. That is a matrix factorization model.
Recommender systems
Take a ratings matrix : one row per user, one column per movie, most entries missing (nobody has seen everything). Guess that tastes are driven by a few hidden factors (how much action, how much romance, …). Give every user a taste vector and every movie a trait vector , and predict : high when the user's tastes line up with the movie's traits (cosine-similarity intuition from chapter 1).
You can't just take the SVD of : the missing entries aren't zeros, and filling them with 0 would teach the model that unseen means hated. Instead, fit only the observed entries, with a penalty to keep the vectors small:
Alternating least squares (ALS) exploits a nice fact: if you freeze all the movie vectors, finding each user's vector is an ordinary small ridge regression (chapters 2 and 10): , using the movies that user rated. Then freeze the users and solve for each movie the same way. Alternate until it settles. (Gradient descent on the same loss also works and is what deep-learning recommenders do, with the dot product replaced or joined by a neural network.)
LoRA: fine-tuning with a low-rank update
A large language model has weight matrices like of shape 4096×4096: 16.8 million numbers each, and hundreds of them. Fine-tuning all of them for every new task is expensive, and storing a full copy per task is worse. LoRA (Low-Rank Adaptation) freezes and learns only a low-rank change:
- Parameters: instead of . With and : 65,536 instead of 16,777,216, about 0.4%.
- Forward pass: . Computing first (shape ) keeps it cheap; you never build the matrix during training.
- Initialisation: random, , so and training starts exactly at the pretrained model.
- Deployment: after training, merge once. No extra cost at inference, and switching tasks means swapping tiny pairs.
Why should a rank-8 update be enough? Empirically, the change that fine-tuning makes to a pretrained weight matrix has most of its energy in a few singular directions (an "intrinsic low rank"), so by Eckart–Young a low-rank captures most of it.
The same idea, elsewhere
- Compressing layers: replace a trained by its rank- SVD, i.e. two thin layers (chapter 7).
- Embeddings: word2vec and GloVe can be read as implicitly factorising a matrix of word co-occurrence statistics; the word vectors are the rows of one factor.
- Attention: the score matrix has rank at most the head dimension, because it's a product through a thin bottleneck.
- Non-negative matrix factorization () gives parts-based, interpretable factors for topics and images.
Worked exampleA prediction and a parameter budget
Recommender: with factors (action, romance), a user with and a movie with get . For a romance with : . Recommend the first.
LoRA: a model with 32 layers, each with four 4096×4096 attention matrices, has billion weights in those matrices. LoRA with on all of them trains numbers: 0.39%. With the Adam optimiser storing two extra numbers per trainable weight, the memory saving is even larger.
Watch outCommon misconceptions
- "Missing ratings can be treated as zeros." Then the model learns that people dislike everything they haven't seen. Fit only the observed entries.
- "LoRA makes the model itself low-rank." Only the update is low-rank. is still full-rank.
- "The factors are unique and interpretable." for any invertible : you can rotate or rescale the latent space without changing a single prediction. "Action" and "romance" axes are a story we tell, not something the math guarantees.
- "Larger or is always better." More factors fit the training data better but overfit the sparse observations; and are tuned on held-out data.
In ML & deep learningWhere this shows up
This whole chapter is the ML box. Matrix factorization won the Netflix Prize era of recommenders and still powers candidate retrieval in large systems (two-tower models compute user and item embeddings and rank by dot product). LoRA and its variants (QLoRA, which also quantises to 4 bits; DoRA) are the default way to fine-tune large language and image models on a single GPU. Low-rank structure is also exploited to compress gradients during training (GaLore) and to speed up attention (Linformer).
Practice (pick one answer per question)
A user's taste vector is (1, 2) and a movie's trait vector is (3, 1). What rating does the model predict?
- 5
- (3, 2)
- 7
- 4
. The prediction is a dot product: a single number. (3, 2) is the element-wise product before summing.
How many trainable parameters does LoRA add to a 1024×1024 weight matrix with rank ?
- 8,192
- 4,096
- 1,048,576
- 16,384
is 1024×4 and is 4×1024: , versus 1,048,576 for the full matrix (0.78%).
is 1000×8 and is 8×1000. What is the largest possible rank of the 1000×1000 matrix ?
- 8
- 1000
- 16
- 992
Every column of is a combination of the 8 columns of , so the column space has dimension at most 8.
Why not just take the SVD of the ratings matrix with missing entries set to 0?
- The zeros would be treated as real ratings, teaching the model that unseen movies are disliked
- The SVD only works on square matrices
- The SVD can't handle more than 2 factors
- Ratings matrices are always full rank
Missing isn't the same as zero. The SVD works for any shape and rank; the problem is that it fits every entry, including the made-up zeros. So we fit only observed entries (ALS or gradient descent).
LoRA initialises (and randomly). What is the effect?
- at the start, so fine-tuning begins exactly at the pretrained model
- Training can't start, because the gradient with respect to is zero forever
- It forces to stay rank 0
- It makes trainable
initially, so the model's outputs are unchanged. The gradient with respect to is not zero (it involves ), so starts moving immediately, and then gets gradients too.
In alternating least squares, with every movie vector fixed, finding one user's vector is…
- a small (ridge) least-squares problem using the movies that user rated
- an eigenvalue problem for the whole ratings matrix
- impossible without the other users' vectors
- a full SVD of
The predictions are linear in once the are fixed, so minimising squared error plus is ridge regression: . Each user is independent of the others in this step.
You replace a 4096×4096 dense layer by a rank-256 factorization (4096×256) times (256×4096). What fraction of the original parameters remains?
- 1/8
- 1/16
- 1/4
- 1/256
versus : exactly . (1/16 forgets that there are two factors.)
For a 4096×4096 matrix, LoRA with trains what fraction of the parameters a full fine-tune would?
- about 0.39%
- about 0.2%
- about 3.9%
- about 25%
. (0.2% counts only one of the two factors.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Final tests
3 full-length tests covering the whole module, with single-concept and multi-concept questions and Python problems graded by test cases. You get a score, a chapter-by-chapter breakdown and the worked answer to every question. Your best score is saved in this browser.
One-page cheat sheet
The whole module, compressed. On paper, it prints on its own (figures hidden).
Orthogonality (ch 1)
; then .
Orthonormal basis: coordinates , i.e. .
Orthogonal : , , keeps lengths and angles, .
Null space ⟂ row space; column space ⟂ null space of .
Projections & least squares (ch 2)
Onto a line: , .
Normal equations: ; ; with orthonormal : .
; residual every column: .
Gram–Schmidt & QR (ch 3)
, .
: , , upper triangular.
Least squares: solve (no ).
Symmetric matrices (ch 4)
real 's, orthonormal eigenvectors.
; .
Unit circle → ellipse with axes along . Use np.linalg.eigh (ascending).
Positive definite (ch 5)
.
PD all leading minors Cholesky , independent columns.
2×2: and . Saddle = indefinite. .
SVD (ch 6)
: rotate, stretch by , rotate.
; = eigenvalues of .
rank = # nonzero ; ; . numpy returns U, s, Vh with Vh = .
Low rank (ch 7)
; = first terms, stored in numbers.
Eckart–Young: , , and nothing of rank does better.
Energy kept .
PCA (ch 8)
Centre: . SVD .
Directions = rows of ; variances ; scores ; ratio .
Standardise if units differ.
Pseudoinverse (ch 9)
.
= least-squares solution of smallest norm. projects onto the column space, onto the row space.
Tall: . Wide: . Invertible: .
Norms & conditioning (ch 10)
, , .
; ; lose digits.
. Ridge: .
Tensors (ch 11)
Broadcasting: align shapes from the right; sizes equal or one is 1; result takes the max.
(n,) vs (n,1) → (n,n): silent bug. Use keepdims=True.
einsum: letters missing from the output are summed. 'ij,jk->ik' matmul, 'ii->' trace, 'bhqd,bhkd->bhqk' attention.
Factorizations in ML (ch 12)
, ; fit observed entries only (ALS = alternating ridge regressions).
LoRA: , params vs ; at start; merge after training.
Glossary
- Alternating least squares (ALS)
- Fitting a factorization by freezing one factor, solving a least-squares problem for the other, and alternating. (Ch 12)
- Broadcasting
- Combining arrays of different shapes by aligning them from the right and stretching size-1 axes. (Ch 11)
- Cholesky factorization
- with lower triangular; exists exactly when is positive definite. (Ch 5)
- Condition number
- : the worst-case factor by which solving magnifies relative errors. (Ch 10)
- Covariance matrix
- for centred data; symmetric and positive semidefinite. (Ch 8)
- Eckart–Young theorem
- The truncated SVD is the closest rank- matrix to in the spectral and Frobenius norms. (Ch 7)
- einsum
- Einstein-summation notation for tensor operations: name each axis with a letter; letters absent from the output are summed. (Ch 11)
- Explained variance ratio
- The fraction of total variance captured by a principal component: . (Ch 8)
- Frobenius norm
- . (Ch 7, 10)
- Gram–Schmidt
- Turning independent vectors into an orthonormal basis of the same span by subtracting projections and normalising. (Ch 3)
- Least squares
- Choosing to minimise ; solved by the normal equations, QR or the SVD. (Ch 2)
- LoRA
- Low-Rank Adaptation: fine-tuning a frozen weight by learning a low-rank update . (Ch 12)
- Low-rank approximation
- Replacing a matrix by one of small rank, usually the truncated SVD. (Ch 7)
- Matrix factorization
- Writing a matrix as a product of simpler or thinner matrices, e.g. , , . (Ch 3, 6, 12)
- Normal equations
- : the condition that the residual is perpendicular to every column of . (Ch 2)
- Orthogonal complement
- All vectors perpendicular to a subspace; e.g. the null space is the orthogonal complement of the row space. (Ch 1)
- Orthogonal matrix
- A square matrix with orthonormal columns: , so . A rotation, reflection or both. (Ch 1)
- Orthonormal
- Unit length and mutually perpendicular. (Ch 1)
- Outer product
- : a rank-one matrix whose rows are all multiples of . (Ch 7)
- PCA (principal component analysis)
- Finding orthonormal directions of maximum variance in centred data; computed from the SVD of the data matrix. (Ch 8)
- Positive definite / semidefinite
- A symmetric with (resp. ) for all ; equivalently all eigenvalues (resp. ). (Ch 5)
- Projection matrix
- with ; maps every vector to its closest point in a subspace. (Ch 2)
- Pseudoinverse
- ; is the minimum-norm least-squares solution. (Ch 9)
- QR decomposition
- with orthonormal columns in and upper-triangular . (Ch 3)
- Quadratic form
- , a function made only of degree-2 terms. (Ch 5)
- Rayleigh quotient
- ; its maximum and minimum are the largest and smallest eigenvalues. (Ch 4)
- Ridge regression
- Least squares with a penalty : ; improves conditioning. (Ch 10, 12)
- Singular values / vectors
- , , with : the stretches and the input/output directions of the SVD. (Ch 6)
- Spectral norm
- , the largest factor by which stretches a vector. (Ch 6, 10)
- Spectral theorem
- Every real symmetric matrix is with orthogonal and real diagonal . (Ch 4)
- SVD
- Singular value decomposition : every matrix is rotate, stretch, rotate. (Ch 6)
- Symmetric matrix
- . (Ch 4)
- Tensor
- In ML, an array with any number of axes, such as (batch, tokens, features). (Ch 11)
- Whitening
- Transforming data so its features are uncorrelated with unit variance, using the eigen-decomposition of the covariance. (Ch 8, final tests)