Discover: a few numbers for a face
In 1991, Matthew Turk and Alex Pentland at the MIT Media Lab built a system that could recognise a face in about 0.4 seconds. That was a hard problem. A greyscale photo is a list of 65,536 numbers: one point in 65,536-dimensional space (Chamber 1's data as vectors). Comparing faces pixel by pixel is slow, and it's thrown off by small changes in lighting or position. Turk and Pentland described each face with a handful of numbers instead, computed like this:
Spotted in the wild
Read it aloud: “omega k equals u k transpose, times gamma minus psi”. (capital gamma) is a new face image, unrolled into one long column of pixels. (capital psi) is the average face of the training set, so is “how this face differs from the average face”. Each is an eigenface, a ghostly face-shaped pattern, and the weight (omega k) says how much of pattern this face contains. In many of their tests, trained on images, they kept just seven eigenfaces (, “M prime”): seven numbers per face instead of tens of thousands of pixels.
That raises three questions. Where do the patterns come from? Why those patterns and not others? And how can so few numbers carry so much? The answers are the singular value decomposition, which says that every matrix is built from a few strong layers and many weak ones, and principal component analysis, which is the same idea applied to a cloud of data.
In , the face , the average face and the eigenface are all columns of pixel values. What kind of object is the weight ?
Learn: rotate, stretch, rotate
In Chamber 4 you watched matrices move the plane. Apply a matrix to the unit circle and, unless it flattens the plane, you get an ellipse. An ellipse has a longest axis and a shortest axis, at right angles to each other. Here's the surprise: there is always a pair of perpendicular unit vectors that the matrix sends exactly onto those axes. It sends to the long semi-axis, of length (“sigma one”) in the direction of a unit vector , and to the short one, of length along :
Put the 's in the columns of a matrix , the 's in the columns of , and the 's on the diagonal of (capital sigma). The two equations become one, . Since has orthonormal columns, and (Chamber 7), so multiplying on the right by gives
read “A equals U sigma V transpose”. This is the singular value decomposition (SVD), and the remarkable fact is that every real matrix has one: square or rectangular, invertible or not.
Read the factorisation from right to left, as three steps applied to a vector :
- Rotate. lists the dot products : the coordinates of in the basis of 's (Chamber 3). Because is orthogonal, this step is a rotation, possibly with a reflection. No length changes.
- Stretch. multiplies coordinate by . This is the only step that changes lengths. When it also pads with zeros or drops coordinates, which is how you get from to .
- Rotate. turns the stretched axes to point along in the output space.
So every linear map, however tangled it looks, is a rotation, a stretch along perpendicular axes, and another rotation. A sphere always becomes an ellipsoid (possibly flattened), with semi-axes . In particular, is the biggest stretch applies to any unit vector. (Write a unit vector as with . Then , which is at most .)
- “A equals U sigma V transpose”The singular value decomposition: rotate with , stretch with , rotate with . Every real matrix has one.
- “sigma i”The -th singular value: how much stretches along its -th direction. Never negative, and sorted from largest to smallest.
- “capital sigma, the matrix”The matrix with on its diagonal and zeros everywhere else. In this chamber it is neither a sum nor a covariance.
- “u i, a left singular vector”Column of : a unit vector in the output space , the direction where the -th stretch lands.
- “v i, a right singular vector”Column of : a unit vector in the input space . It is an eigenvector of with eigenvalue .
- “A sub k”The truncated SVD: keep the first layers and drop the rest. It has rank , and it is the best rank- approximation of .
- “the Frobenius norm of A”The length of unrolled into one long vector: the square root of the sum of all squared entries. It equals .
- “the spectral norm of A”The biggest stretch applies to any unit vector. It equals the largest singular value.
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “A equals U sigma V transpose” | The singular value decomposition: rotate with , stretch with , rotate with . Every real matrix has one. | ||
| “sigma i” | The -th singular value: how much stretches along its -th direction. Never negative, and sorted from largest to smallest. | ||
| “capital sigma, the matrix” | The matrix with on its diagonal and zeros everywhere else. In this chamber it is neither a sum nor a covariance. | ||
| “u i, a left singular vector” | Column of : a unit vector in the output space , the direction where the -th stretch lands. | ||
| “v i, a right singular vector” | Column of : a unit vector in the input space . It is an eigenvector of with eigenvalue . | ||
| “A sub k” | The truncated SVD: keep the first layers and drop the rest. It has rank , and it is the best rank- approximation of . | ||
| “the Frobenius norm of A” | The length of unrolled into one long vector: the square root of the sum of all squared entries. It equals . | ||
| “the spectral norm of A” | The biggest stretch applies to any unit vector. It equals the largest singular value. |
A worked example. Take . Its SVD is with
Multiply the three out and you get back.
So , , and . Check one column by hand: , and . The same vector.
This turns the unit circle into an ellipse with semi-axes and . The circle's area becomes , and indeed (Chamber 5). For any square matrix, : the rotations don't change volume, only the stretch does.
Learn: where the SVD comes from
Why should every matrix have such perpendicular directions? The derivation is short, and it rests on the matrix (“A transpose A”), an matrix that you met in the normal equations of Chamber 7.
Theorem. Every real matrix has a singular value decomposition.
Proof. We build , then , then .
- 1
A transpose A is symmetric
. By the spectral theorem (the last section of this chamber), a symmetric matrix has real eigenvalues and an orthonormal basis of eigenvectors. Call the eigenvectors , with eigenvalues ordered .
- 2
Its eigenvalues are never negative
Since is a unit vector,
So we can take square roots. Define .
- 3
Divide to get the u's
Let be the number of non-zero . For , define . These are orthonormal:
the Kronecker delta (1 if , 0 otherwise), because is 0 when , and when the fraction is .
- 4
Fill in the rest
For , , so . Extend to an orthonormal basis of (Gram–Schmidt, Chamber 7). Now for every up to , and for any beyond . Column by column, that is exactly .
- 5
Multiply by V transpose
is orthogonal, so , and .
The proof tells you more than existence:
- The singular values are , and the are eigenvectors of . By the same argument with , the are eigenvectors of , which has the same non-zero eigenvalues.
- The rank of is , the number of non-zero singular values. are an orthonormal basis for the column space of , and for its null space (Chamber 6). The SVD hands you orthonormal bases for the subspaces Chamber 6 introduced.
For the worked example, has eigenvalues 45 and 5, with eigenvectors along and . Their square roots, and , are the singular values we found.
A matrix has with eigenvalues , and . What are the singular values of , and what is its rank?
Learn: a sum of layers, and the best low-rank copy
Chamber 4 gave four views of matrix multiplication. The fourth, columns times rows, turns into a sum:
Each is an outer product, a rank-one matrix (Chamber 6): every row is a multiple of the same row . Drawn as an image it looks like a plaid, stripes in two directions. The SVD writes any matrix as a sum of plaids, sorted from strongest to weakest. Keep the first and drop the rest, and you get the truncated SVD, “A sub k”:
has rank . How close is it to ? To answer, we need the size of a matrix. The Frobenius norm unrolls into one long vector and takes its length (Chamber 2):
read “the Frobenius norm of A”. Then is the distance between two matrices, entry by entry. For images, it's the square root of the total squared pixel error.
Claim. .
Proof. First, multiplying by an orthogonal matrix doesn't change the Frobenius norm. For any vector , (Chamber 7). The squared Frobenius norm of a matrix is the sum of its squared column lengths, so . Multiplying on the right is the same argument applied to rows: transposing only rearranges entries, so , since is orthogonal too. Now peel the orthogonal factors off the SVD:
the last step because the only non-zero entries of are the .
The same argument measures the truncation error. is again of the form , with replaced by zeros, so
The error is exactly the size of the singular values you threw away. You can read the quality of every truncation straight off the list of singular values, the spectrum.
We won't prove Eckart–Young here, since the proof takes a page. The readings below include a proof of the spectral-norm version and an intuitive argument for the Frobenius one. But notice what it means for machine learning. Whenever a method approximates a known matrix by a low-rank one, say to compress the weights of a trained layer, the truncated SVD is the benchmark: no rank- matrix gets closer in the Frobenius norm. (LoRA, from Chamber 6, is different: it learns a low-rank update instead of approximating a known one.)
Storage. To store you keep columns of ( numbers each), columns of ( each) and singular values: numbers instead of . A photo at rank 50 needs numbers, about a tenth of the original million. Try it on two images, each a matrix of brightness values between 0 (black) and 1 (white).
Interactive lab
The low-rank artist
Error 51.1%: still above 10%. Add more layers.
relative error
51.1%
energy kept
73.8%
numbers stored
129
of the 4,096
3.1%
Singular values σ₁ ≥ σ₂ ≥ … ≥ σ₆₄
Gold bars are kept. The error is the length of what's thrown away: ‖A − A₁‖F = √(σ₂² + … + σ₆₄²).
Things to try:
- At rank 1 the picture is a plaid: every row is a multiple of . Step up one layer at a time and watch the third panel, the newest layer , gold where it adds brightness and blue where it removes it. Every layer is another plaid.
- Watch the spectrum while you go. The error readout is computed from the bars you haven't kept, exactly as the formula above says. The “energy kept” is minus the relative error squared.
- Switch to the Greek key. At some rank the error drops to exactly zero and the spectrum falls off a cliff. Why? (Hint: how many different rows does the image have, and are any two of them multiples of each other? Think back to Chamber 6.)
- The challenge: for either image, find the smallest rank that rebuilds it with under 10% relative error, and leave the slider there.
A matrix has singular values . What is , the error of its best rank-one approximation?
Learn: principal component analysis
Now switch from one matrix to a dataset: points , stored as the rows of an data matrix . Which directions matter?
In 1901 Karl Pearson asked for the line (and the plane) of closest fit to a cloud of points, measuring each point's distance perpendicular to the line rather than vertically, as regression does. Pythagoras turns this into a question about variance. Suppose the data are centred (their mean is ) and the line runs along a unit vector . Each point splits into a part along the line, of length , and a perpendicular part:
The left side doesn't depend on . So making the total squared distance small is the same as making large: the best-fitting line points in the direction along which the data vary the most. That direction is the first principal component.
- 1
Centre
Compute the mean (“x bar”) and subtract it from every row: (“X centred”). The best-fitting line passes through the mean, so this loses nothing.
- 2
Form the covariance matrix
, a matrix. Entry is the covariance of features and , and the diagonal holds the variances. Statisticians often divide by instead of : the eigenvectors are the same and the eigenvalues scale.
- 3
Find its eigenvectors
is symmetric, so with orthonormal eigenvectors (the principal directions) and eigenvalues (the variances along them).
- 4
Measure the explained variance
Component explains the fraction of the total variance. Plotting these fractions (a “scree plot”) shows how many components are worth keeping.
- 5
Project
Keep the top directions, , and replace each point by its scores : numbers instead of .
- “x bar, the mean vector”The average data point. PCA subtracts it from every point first.
- “X centred”The data matrix (one point per row) with the mean subtracted from every row.
- “C, the covariance matrix”The matrix of covariances between features, with the variances on its diagonal. Symmetric, and its eigenvalues are never negative.
- “lambda i”The -th eigenvalue of : the variance of the data along the -th principal direction.
- “the explained variance ratio”The fraction of the total variance that component captures.
- “z i, the scores”The low-dimensional code for data point : its coordinates along the top principal directions.
- “S equals Q lambda Q transpose”The spectral theorem: a symmetric matrix has orthonormal eigenvectors (the columns of ) and real eigenvalues (the diagonal of ).
| Symbol | Say it | Meaning | LaTeX |
|---|---|---|---|
| “x bar, the mean vector” | The average data point. PCA subtracts it from every point first. | ||
| “X centred” | The data matrix (one point per row) with the mean subtracted from every row. | ||
| “C, the covariance matrix” | The matrix of covariances between features, with the variances on its diagonal. Symmetric, and its eigenvalues are never negative. | ||
| “lambda i” | The -th eigenvalue of : the variance of the data along the -th principal direction. | ||
| “the explained variance ratio” | The fraction of the total variance that component captures. | ||
| “z i, the scores” | The low-dimensional code for data point : its coordinates along the top principal directions. | ||
| “S equals Q lambda Q transpose” | The spectral theorem: a symmetric matrix has orthonormal eigenvectors (the columns of ) and real eigenvalues (the diagonal of ). |
Why the top eigenvector? The variance of the data along a unit vector is
using , and the fact that a sum of outer products of the rows is (columns times rows again).
Claim. Over all unit vectors , the variance is largest at , where it equals .
Proof. Write in the orthonormal eigenbasis: , with . Then , and because for , all the cross terms vanish:
The inequality holds because every , and reaches the bound, since .
Repeat the argument among directions perpendicular to and you get , and so on. This is word for word the definition in the eigenfaces paper, whose Equation 1 asks for the for which is a maximum, subject to the 's being orthonormal. It also tells you what PCA throws away. By Pythagoras again, the average squared distance from the points to the best -dimensional subspace is : exactly the variance in the directions you dropped.
A worked example. Take four points in : , , and .
- The mean is . The centred points are , , and .
- The covariance matrix is .
- gives and , with eigenvectors and .
- The first component explains of the variance.
- The scores along are , , and . Their variance is , as promised. Keeping one component squashes the last two points onto the mean, and the average squared distance lost is .
PCA through the SVD. Take the SVD of the centred data, . Then
That is an eigendecomposition of . The principal directions are the right singular vectors of , the variances are , and the scores come for free: . In the worked example, has singular values 6 and 2, and indeed and . This is how PCA is computed in practice (scikit-learn's PCA centres the data and takes an SVD), because it's more accurate than forming , and because it's cheap when there are far fewer points than features. That was Turk and Pentland's situation: they found eigenvectors of the small matrix and formed the eigenfaces as , which is step 3 of our derivation of the SVD without the division by .
A dataset's covariance matrix has eigenvalues , , and . What percentage of the total variance do the first two principal components explain?
Learn: the spectral theorem
You've now leaned on one fact three times: and are symmetric, so they have real eigenvalues and perpendicular eigenvectors. Time to name it.
Read it “S equals Q lambda Q transpose”. Each projects onto the line through (Chamber 7), so a symmetric matrix simply stretches space by along perpendicular axes. That's the SVD's picture with the same axes going in and coming out. For a symmetric matrix with no negative eigenvalues, such as or , the eigendecomposition is an SVD: and . When some eigenvalues are negative, the singular values are and the signs move into .
The proof has three parts.
- The eigenvalues are real. The proof needs complex numbers, and it's in the box below.
- Eigenvectors for different eigenvalues are perpendicular. You proved this yourself in Chamber 8's Your turn: compute in two ways and use .
- Even when eigenvalues repeat, there are enough perpendicular eigenvectors to fill a basis. This needs an induction argument that we'll skip; Theorem 4.15 of Mathematics for Machine Learning states it, and linear algebra textbooks prove it.
Why a symmetric matrix has real eigenvalues
Suppose with , allowing and to be complex. Write for the complex conjugate (flip the sign of every imaginary part; this bar is not a mean). Then .
Compute in two ways. First, . Second, conjugating gives , because is real. Then, using ,
So , and dividing by the positive number gives : is real.
Read beyond the course
The SVD sits at a crossroads of numerical computing, statistics and machine learning, so every field has written about it. These are free, and each one shows the ideas from a different side.
Lecture notes · free online · ~40 min
CS168 Lecture #9: The Singular Value Decomposition (SVD) and Low-Rank Matrix ApproximationsTim Roughgarden & Gregory Valiant (Stanford) · Sections 4–6
Clear, example-led notes from Stanford's “Modern Algorithmic Toolbox” course. Section 5 states the Eckart–Young optimality in the Frobenius norm (their Fact 5.1), and Section 6 shows how PCA reduces to the SVD, then uses that to explain why the fact holds. Read it now to see this chamber's ideas from a computer scientist's side.
Lecture notes · free online · ~35 min
CS168 Lecture #7: Understanding and Using Principal Component Analysis (PCA)Tim Roughgarden & Gregory Valiant (Stanford) · From “A Toy Example” to the end, including “Failure Cases”
PCA as a practitioner uses it: why you centre and scale, a genetics study in which the top two components of 1,387 Europeans' DNA draw a map of Europe, and the cases where PCA fails. The best antidote to thinking PCA always works.
Book · free online · ~90 min
Mathematics for Machine LearningMarc Peter Deisenroth, A. Aldo Faisal & Cheng Soon Ong · Sections 4.5–4.6 (SVD, matrix approximation) and Chapter 10 (PCA)
The textbook treatment, in notation close to this course's. Section 4.6 proves the Eckart–Young theorem for the spectral norm (Theorem 4.25), and Chapter 10 derives PCA twice, as maximum variance and as best projection, then lists the key steps in practice (Section 10.6).
Article · free online · ~30 min
A Tutorial on Principal Component AnalysisJonathon Shlens · Sections V–VI
A widely read tutorial whose stated goal is to take the magic out of PCA. Section V solves PCA with an eigendecomposition and Section VI with the SVD, side by side, so you can check your understanding of why they agree.
Book · free online · ~60 min
Data-Driven Science and EngineeringSteven L. Brunton & J. Nathan Kutz · Chapter 1: Sections 1.1–1.2, 1.5–1.6
The authors' free chapters open with the SVD, and the video below follows this chapter. Sections 1.5 and 1.6 run PCA and a full eigenfaces example with code, so read them right after the paper.
Papers and lectures
The eigenfaces paper is one of the most readable classics in machine learning, and you now know everything its central sections use. Read Calculating Eigenfaces (Equations 1–6) and then Using Eigenfaces to Classify a Face Image (Equations 7–9). One thing to watch: the paper stores each face as a column, so its matrix is the transpose of our . On a first read, skip the later sections on locating faces in a scene and tracking moving heads.
Eckart and Young's paper is eight pages long and written in the notation of 1936. Its abstract is worth reading for one sentence: the normal equations of least squares (Chamber 7) “cannot be immediately written down”, because the entries of a low-rank matrix aren't independent of one another. They solve it by “first expressing the matrices in a canonic form”, which is the SVD. Pearson's paper is where PCA began: fitting a line or a plane by perpendicular distance, rather than by the vertical errors of regression.
Eigenfaces for RecognitionMatthew Turk, Alex Pentland · Journal of Cognitive Neuroscience 3(1), 71–86, 1991PCA on photographs of faces: the covariance eigenproblem, the small-matrix trick and recognition by distance in “face space”. A landmark of computer vision.
The approximation of one matrix by another of lower rankCarl Eckart, Gale Young · Psychometrika 1(3), 211–218, 1936The best rank- approximation is the truncated SVD. Written for psychologists, now used everywhere a matrix is compressed.
On lines and planes of closest fit to systems of points in spaceKarl Pearson · The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science 2(11), 559–572, 1901The origin of principal component analysis: fitting a line or a plane by perpendicular distance.
Now take apart the equation at the heart of the eigenfaces paper.
Decode the paper · Eq. (3), section “Calculating Eigenfaces”
Eigenfaces for RecognitionMatthew Turk, Alex Pentland · Journal of Cognitive Neuroscience 3(1), 1991
Turk and Pentland's eigenfaces are the eigenvectors of this matrix: “the vectors and scalars are the eigenvectors and eigenvalues, respectively, of the covariance matrix”. Each face is an image unrolled into a column of pixels. Match each symbol to its meaning.
Options
Watch
Brunton's overview follows Chapter 1 of his book, where each data point is a column (as in the eigenfaces paper), so his holds the patterns and the weights: the transpose of this chamber's rows convention. StatQuest works PCA out slowly on a small example, from finding PC1 to the percentage of variation per component and the scree plot. Watch how he scales things: he works with sums of squared distances, where this chamber divides by to get variances. The directions and the percentages come out the same.
Your turn
You've already found the smallest rank in the lab above. Now match the symbols, assemble one proof and write another, and then compress, decompose and recognise in code.
Match · Symbols ↔ Meaning
What each piece means
Match each piece of the SVD to what it tells you about the matrix .
Options
Match · Maths ↔ NumPy
From symbols to NumPy
Match each formula to the NumPy that computes it. Two details: np.linalg.svd returns the singular values as a 1D array S (not a matrix), and it returns (called Vt), not . The data matrix X has one point per row.
Options
Proofs
The puzzle runs the SVD backwards: start from and show the 's are eigenvectors of . The second shows why PCA's explained-variance fractions add up to exactly 1.
Proof puzzle
Right singular vectors are eigenvectors
Claim
If is an SVD ( and orthogonal, diagonal with entries ), then every right singular vector is an eigenvector of , with eigenvalue .
Tap lines in the order they should appear. Not every line belongs. Tap a line in your proof to send it back.
Your proof
- Pick the first line below.
Available lines
Prove it yourself
The eigenvalues share out the total variance
Claim
Let be a centred data matrix whose rows are , and let be the eigenvalues of its covariance matrix . Prove that
The right-hand side is the total variance: the average squared distance of the points from their mean. (This is why is the fraction of the variance that component explains.) You may use two results from this chamber: , where the are the singular values of , and .
Your typeset proof appears here.
Code it up
Each problem has one answer. The first two use np.linalg.svd; the third applies the eigenfaces paper to a tiny dataset of “faces”.
Problem 25·Warm-up
One layer of a staircase
Let be the matrix with entries for . Its first row is and its last row is .
The best rank-one approximation of is its first SVD layer, . What fraction of the squared Frobenius norm does that single layer keep? That is, compute
and give it to 4 decimal places.
Problem 26·Standard
Compressing a disc
A black-and-white image shows a white disc of radius 15 in the middle of a black square:
Let be its rank- truncated SVD. Find the smallest for which the relative error is strictly below 5%:
Give as an integer.
Problem 27·Challenge
Distance from face space
Apply the eigenfaces paper to a tiny dataset. Turk and Pentland project a face onto a few eigenfaces and measure what's left over: a face that is far from “face space” may not be a face at all.
For , training face is an image with pixel values
for (angles in radians). Flatten each image row by row into a vector of length 64: pixel goes to position .
1. Compute the average face and the differences . 2. Find eigenfaces : unit eigenvectors of the covariance matrix (the paper's Eq. 3) with the three largest eigenvalues. 3. A new image has pixels . Compute its weights (Eq. 7), its projection onto face space , and its squared distance from face space (Eq. 9)
Give to 4 decimal places.
Key takeaways
- Every matrix is rotate, stretch, rotate: , with . The singular values are the square roots of the eigenvalues of , and the rank is the number of non-zero ones.
- The SVD is a sum of rank-one layers, strongest first. Keeping of them gives , the best rank- approximation (Eckart–Young), with error in the Frobenius norm.
- Storing costs numbers instead of . That's the whole idea behind compressing with low rank.
- PCA: centre the data, find the eigenvectors of the covariance matrix , keep the top few. They're the directions of greatest variance, and is the variance each explains.
- PCA is the SVD of the centred data: the principal directions are the right singular vectors of , and .
- The spectral theorem: a symmetric matrix has real eigenvalues and orthonormal eigenvectors, . It's why the SVD and PCA always exist.
Checkpoint
Prove it to the labyrinth
Answer every question to clear this chamber. First-try answers earn the most XP.
A dataset of 100 examples with 20 features is stored as a matrix . In its full SVD , what are the shapes?
A matrix turns the unit circle into an ellipse with semi-axes of length and . What is ?
A matrix has singular values , , and . Which statement is true?
A greyscale photo is a matrix. How many numbers do you need to store its rank-50 truncation (the kept columns of and , plus the singular values)?
What does the Eckart–Young theorem say about the truncated SVD ?
Why does PCA subtract the mean from the data before finding directions?
A centred data matrix has rows, and its largest singular value is . With , what is the largest eigenvalue of ?
Which matrix is guaranteed by the spectral theorem to have an orthonormal basis of eigenvectors?
End of the chamber
Clear this chamber
- Questions in this chamber (0/12 solved)Next unsolved
- Bonus: Low-rank artist (+50 XP)
- Bonus: Problem 25: One layer of a staircase (+20 XP)
- Bonus: Problem 26: Compressing a disc (+35 XP)
- Bonus: Problem 27: Distance from face space (+50 XP)
- Bonus: Proof: Right singular vectors are eigenvectors (+25 XP)
- Bonus: Proof: The eigenvalues share out the total variance (+40 XP)
- Bonus: Decode the paper (+30 XP)
- Bonus: Match: What each piece means (+25 XP)
- Bonus: Match: From symbols to NumPy (+25 XP)