Section 1
Lossy compression of points
How to use this pageClick the colored symbols to see what they mean. Move every slider and press every button before you read on, and commit to each Predict first guess.
data point code decoder angle, eigenvalue
Picture 1,000 pins strung along one straight road. Two numbers per pin (east, north) is more than you need; the distance along the road says almost everything.
Below, the decoder is a line through the origin. Drag across the cloud to swing it. The orange sticks are what gets lost.
One number per point
Show the numbers of this cloud
Along the cloud, the sticks shrink. Across it, they grow. The lower chart plots the total squared stick length against the angle: one smooth valley.
Challenge +8 XPSwing the line until the total error is within 10% of the lowest point of the valley. Do it by hand, then tick Reveal to check.
Principal components analysis (PCA) is that idea as an algorithm. The book derives it from basic linear algebra, and so will we, one small step at a time.
- You have points , each a list of numbers, so lives in .
- For each point you store a shorter code in , with . Shorter means less memory.
Predict first. Each pin is stored as one number instead of two. Does the rebuilt map stay exact?
- The encoder writes the code, . The decoder rebuilds a point, so that .
- The rebuild is not exact. This is lossy compression: less memory, a little precision gone. We want to lose as little as possible.
Section 2
Encoder, decoder and constraints
A decoder is a recipe. PCA picks the simplest recipe there is, one matrix multiplication:
Click any coloured symbol to see what it means.
has rows and columns. Each column is an arrow in , and the code says how far to walk along each arrow. With one column, the walk stays on one line: the line from the demo.
Two rules keep the arrows tidy. The columns must be orthogonal, meaning every two different columns have dot product 0, which keeps the best code easy to find. Each column must also have unit norm, meaning length 1.
Predict first. You double one column and halve the matching code entry . Where does the rebuilt point go?
Click any coloured symbol to see what it means.
Entry of is the dot product of columns and . Zeros off the diagonal mean orthogonal, ones on it mean length 1. (The book notes that is still not an “orthogonal matrix” unless , because it is not square.)
Drag the big point and the tip of the teal arrow. Then slide the code until the purple dot lands on the hollow circle, the best possible rebuild.
Choose a code by hand
the point reconstruction errorall decodable points
The rebuilt point can only sit on the line, so the best one is the foot of the perpendicular. The lower chart is a parabola with one lowest point. Now stretch the arrow to length 2 and press Set the code to its best value: the hollow circle stays put, and the code value halves.
Challenge +8 XPMake the column at least 2.0 long, then slide the code by hand until the purple dot sits on the hollow circle (error within 0.02 of its lowest value).
Section 3
The optimal code
Given the decoder, which code rebuilds best? The book answers: the one that puts nearest to . Here means “the that makes what follows smallest”.
Click any coloured symbol to see what it means.
The book squares the norm. For non-negative numbers, squaring keeps the order of any two candidates, so the winner does not change:
Click any coloured symbol to see what it means.
Now expand the square. Step through the algebra, one line at a time. Each line is clickable too.
A squared length is the vector dotted with itself (Equation 2.30).
Multiply the brackets out term by term, as you would for the square of a difference.
The two middle terms are the same single number (a number equals its own transpose), so they merge.
The first term has no in it. It lifts every candidate by the same amount, so the winner does not change. Drop it.
Drop the identity: multiplying by it changes nothing.
The trick of dropping a constant deserves a look before you trust it.
Predict first. The first term is dropped. Does the lowest point of the curve move?
Dropping the constant
full errorafter dropping the constant (appears after your guess)best code
Same bowl, shifted down. To find its bottom, the book uses calculus (Section 4.3): at the bottom of a smooth bowl the gradient, the vector of slopes, is zero.
Click any coloured symbol to see what it means.
The slopes of the two terms are and . Setting their sum to zero gives
Click any coloured symbol to see what it means.
Click any coloured symbol to see what it means.
That is the whole result: the best code is the dot product of the point with each column. No search needed.
Going deeper: why this is a bottom and not a top
The second derivative with respect to is , which is positive, so the bowl opens upward and the zero-gradient point is a minimum. This remark is added here and is not printed in the book.
Check Equations 2.63 to 2.65 below. The demo takes and , a fixed point and a fixed . Drag the black point over the map. It compares the formula’s gradient with one measured by nudging each code entry.
Gradient check
gradient (uphill)best code equal function value
The contours are circles around . The arrow always points uphill, directly away from the center, and is twice as long as the distance to it.
Challenge +8 XPDrag the black point to where the gradient arrow disappears (its length under 0.1). The formula and the nudged estimate must agree there too.
Section 4
Encoder and reconstruction
The optimal code costs one matrix-vector product. That is the encoder:
Click any coloured symbol to see what it means.
Entry of says how far reaches along column of . Decode the code and you get the PCA reconstruction:
Click any coloured symbol to see what it means.
Think of as a lamp that casts every point’s shadow onto the line or plane spanned by the columns. A shadow of a shadow is the shadow again.
Going deeper: the shadow of a shadow
Applying the matrix twice gives by the constraint. This remark is added here. The table in the demo below shows it with numbers.
Here is a seeded 3D cloud. Drag on the picture to swing the first column, or use the sliders, and watch the sticks. Try both tabs.
Encode and reconstruct a cloud in three dimensions
pointsreconstructions errorspan of the columns
Show codes, reconstructions and the shadow of the shadow
With a plane, each point costs 2 numbers instead of 3, and the error is lower than with a line, since every line lies inside some plane. The last two columns of the table are equal: the shadow of a shadow.
Challenge +8 XPOn the tab, aim the line so that it keeps at least 70% of the cloud (the readout shows the share).
Section 5
Choosing the decoder for all points
The code was best for one point. But a single decodes every point, so now all of them vote. The book minimizes the total squared error over all coordinates of all points (the Frobenius norm, a square root of that total):
Click any coloured symbol to see what it means.
To find the algorithm, start with . Then is one column of length 1, and plugging in Equation 2.67 gives
Click any coloured symbol to see what it means.
Going deeper: two cosmetic rewrites (Equations 2.70 and 2.71)
The book notes that 2.69 puts the number to the right of the vector , and that it reads better with numbers on the left:
Click any coloured symbol to see what it means.
Since a number equals its own transpose, , one can also write
Click any coloured symbol to see what it means.
The book wants you to get comfortable with such rearrangements. The table in the next demo shows that all the forms give the same number.
Next, stack the points as rows of a design matrix , so row is . The whole sum becomes one matrix norm:
Click any coloured symbol to see what it means.
Going deeper: why the sum becomes a matrix norm
Row of is , the transposed reconstruction of point . So row of is the transposed error of that point, and the squared Frobenius norm adds up the squared lengths of all rows.
See it with your own eyes. Swing the line, then click a point to read its row of the error matrix.
All four forms give the same value at every angle, and it is the same valley as in Section 1. Equation 2.72 is the form we keep, because matrices obey the trace rules of Section 2.10.
Challenge +8 XPClick the point that adds the most to the total error at the current angle. Then move the line and find the new champion.
Section 6
The trace derivation
The goal: turn the error into one number that is easy to maximize. The tools are the trace rules of Section 2.10: the squared Frobenius norm is a trace (Equation 2.49), a trace survives a transpose (2.50), and you can rotate the factors of a product inside a trace (2.51, 2.52). Step through the chain.
Start from the objective of 2.72 and set the constraint aside for a moment.
A squared Frobenius norm is (Equation 2.49).
Expand the two brackets, term by term and in order.
The trace of a sum is the sum of the traces.
The first trace has no in it, so it cannot change the winner. Drop it.
The two middle traces are equal (transpose and cyclic rules, 2.50 to 2.52), so they merge into one with coefficient 2.
In the last trace, rotate the leading to the back.
Now bring the constraint back. The next step needs it.
Inside the last trace, because .
Coefficient −2 plus coefficient +1 leaves −1.
The smallest value of the negative is the largest value of the quantity. Write argmax.
Rotate from the back to the front. The trace of a single number is that number: a quadratic form.
Now check every line with numbers. The cloud is the seeded one from Section 1. Stretch away from length 1 and see which lines break.
Every line of the derivation, with numbers
| Equation | What it computes | Value |
|---|
At length 1, neighboring rows agree except where a step dropped a constant (2.77) or flipped a sign (2.83). Off length 1, rows 2.79 and 2.81 split, because 2.81 used the constraint. The last row is the quadratic form, and the verdict of the derivation: the best direction makes this one number as large as possible.
Challenge +8 XPBreak the constraint: stretch or shrink until rows 2.79 and 2.81 disagree by more than 1.
Section 7
The first principal component
We want the unit vector that makes biggest. The book says to use eigendecomposition: the answer is the eigenvector of with the largest eigenvalue. It does not prove this. Here is a short argument, added for this lesson.
The matrix is symmetric, so (Section 2.7) it has orthonormal eigenvectors and real eigenvalues . Write in that basis and the quadratic form becomes
Click any coloured symbol to see what it means.
The weights are never negative and add up to 1. So the form is a weighted average of the eigenvalues, like a class average that can never beat the best grade. It reaches only when all the weight sits on , that is when .
Predict first. Here is the cloud at its default settings. Along which angle does it stretch most?
Drag across the cloud to aim a line along what you think is its longest direction. The principal directions stay hidden until you tick Reveal.
Principal directions from the eigendecomposition
Show the numbers of this cloud
The lower chart traces the quadratic form against your angle. Its peak, of height , sits at the first eigenvector, and its lowest point, , at the second. The error of the first component is .
Challenge +8 XPAim the test line within 3° of the cloud’s first principal direction.
Now provoke a failure. The derivation looks for directions through the origin. If the cloud sits far from the origin, the offset swamps the shape.
Challenge +8 XPUntick Subtract the mean first and raise the offset until the first principal direction swings more than 30° away from where it points for the centered cloud.
Going deeper: what the offset does, in numbers
This remark is added here and is not stated in the printed derivation. With the default cloud, the first direction of the centered data is near 108°. Untick the box and raise the offset to its maximum (it pushes the cloud along about 37°): the first direction swings to about 40°, and the error of the first component, the second eigenvalue, grows from about 17 to about 94. Tick the box again and the demo subtracts the average first, so the direction follows the spread. PCA is applied to centered data in practice, and every other cloud in this module is centered.
Section 8
Several components and the algorithm
For the book states the pattern: holds the eigenvectors with the largest eigenvalues. It leaves the proof as an exercise (induction). A short argument, added here, follows the same steps as before and gives, for orthonormal columns,
Click any coloured symbol to see what it means.
So the error is a constant minus a quantity to maximize. That trace equals , where says how much of eigenvector lies inside the span of the columns. Each is between 0 and 1, and they add up to . To score highest, put full weight on the biggest eigenvalues. What is left over is the error:
Click any coloured symbol to see what it means.
The whole algorithm, with an eigendecomposition doing the heavy lifting:
- Subtract the mean from the data and stack the points as rows of .
- Form and compute its eigenvectors and eigenvalues.
- Pick and let the columns of be the eigenvectors of the largest eigenvalues.
- Encode each point with .
- Reconstruct with . The error is the sum of the discarded eigenvalues.
Going deeper: why the shares add up to the code length
The columns of are orthonormal vectors. Each one has total squared length 1 spread over the eigenvector basis, so summing over the columns the squared coordinates add up to , and is the share that lands on . Each share cannot exceed 1, because has length 1. The greedy choice, 1 for each of the top eigenvalues, is the best possible.
Predict first. The seeded 3D cloud below has three eigenvalues. How much of its total squared size does the best plane () keep?
PCA on a three dimensional cloud
pointsreconstructionserrorprincipal subspace
Show the numbers of this cloud
At the first component leaves the two small eigenvalues as error. At only the third remains. At nothing is lost, because is only a rotation. Throw some random subspaces: none beats the PCA one, which is what the derivation promised.
Challenge +8 XPFind the smallest number of components that keeps at least 95% of the total squared size. Click that tab.
- PCA compresses points in into codes in . The decoder is with .
- For a given decoder the best code is (Equations 2.54 to 2.65). Encoder , reconstruction .
- For all points, the error becomes a constant minus , so the best maximizes that form (Equations 2.72 to 2.84).
- The maximizer is the top eigenvector of . In general holds the top eigenvectors, and the error is the sum of the others.
- Center the data first.
Final quizCheck yourself
Questions that mix the whole module. Each one is scored, and the score feeds your mastery of this module.
Source: Ian Goodfellow, Yoshua Bengio and Aaron Courville, Deep Learning, MIT Press, 2016, Section 2.12 (pages 48–52), free to read at deeplearningbook.org. Where the book prints equation numbers, the numbers here follow the book. The order of ideas follows the book. The explanations and all demos were written for this page.