A spreadsheet with forty columns is a cloud of points in forty dimensions — and nobody can look at that. But most clouds are not really forty-dimensional. They are long in a few directions and thin in all the rest. This unit finds those few directions. You will photograph a cloud from its best angle, discover that spread is information, put a direction on a leash and watch it turn into an eigenvector, and see the same answer come back as the smallest rebuild error, as columns that never repeat each other, and as the best compressed copy of your data. Then the practical side: finding eigenvectors by just multiplying, data far wider than it is tall, the recipe, and the traps.
≈ 125 min read + play16 interactive widgets · 7 in 3D · a cloud you can photograph, peel and flatten22 inline checks🧾 15 proofs, folded away — open "if you want the algebra" when you are ready✍ 12 solved practice problems
drag the cloud to orbit
1
Pick the better line
Imagine this
Your cousin wants a photo of his new cricket bat for his WhatsApp status.
Hold the bat side-on and the photo shows everything: the long blade, the handle, how wide it is. Now point the camera straight down the handle. The photo shows a small dark rectangle. You cannot even tell it is a bat.
Same bat. Same camera. The only thing you changed is the direction you looked from.
A cloud of data points works the same way. From some directions it looks spread out, and you can tell the points apart. From others it collapses into a blob. Try it on a cloud shaped like a bat.
Photograph the cloudFour hundred points shaped like a cricket bat. The lamp behind you throws every point's shadow onto the glass screen — that shadow is the photo. The chip says how much of the cloud's spread the photo keeps. Drag to orbit.
Try: press end-on — the photo shrinks to a blob and keeps only about 5% of the spread. Then press side-on: over 99%. Now press ▶ and watch the number rise and fall as the camera walks around the bat.
drag the picture to orbit
—
Now make it smaller. Here are five points: (1,2),(4,5),(7,8),(8,4),(10,6). Say you are allowed to keep only one number per point. Which number should it be?
Option 1: keep only the first number. You get 1,4,7,8,10. Their average is 6. The distances from the average are −5,−2,1,2,4. Square them and take the average: (25+4+1+4+16)/5=10.
That number, the average squared distance from the middle, is how we measure spread. Its proper name is the variance.
Option 2: keep only the second number. You get 2,5,8,4,6, and the spread is only 4.
Option 3: a slanted line that goes 2 steps right for every 1 step up. Drop each point onto it and read where it lands. The spread comes out to 12. That beats both axes.
So the best single number is not one of the columns you were given. It is a mix of them, read along a slanted line. Finding that line is the whole job of this unit.
Here is the same game with 90 points. Each point drops onto the line along a grey thread, the shortest way. That drop is called projecting the point onto the line.
Pick the better lineEvery point drops onto the line along a grey thread. The coloured dots on the line are where they land. The meter measures how spread out those dots are.
Try: drag the orange tip round, or press ▶ sweep. Watch the marker ride the hump below: it peaks at λ1 and dips to λ2 exactly a quarter-turn later. Then switch to the five points and find the angle where the spread is 12.
drag the orange tip to turn the line
The realization
Look at the cloud from every direction. For each one, drop the points onto the line and measure how spread out they land. Keep the direction with the biggest spread.
That is principal component analysis (PCA). Everything else in this unit is the machinery that does this search quickly, and the reason it works. On the 90 points, line A has spread 5.45 and line B only 0.41. You have just done PCA by eye.
Pause & predict
On line B the 90 dots crowd into a short stretch. What goes wrong if you describe each point only by where it lands on B?
Pause & predict
Sweep the line through every angle and the spread traces one smooth hump. How far apart are the best angle and the worst angle?
Here is the path through this unit, one step at a time:
①Why spread is the information — a column that never changes can never explain anything.
②Centre, then build one small table — the covariance matrix C holds every spread you will need.
③One score per direction — the spread along any direction w is w⊤Cw.
④The leash — fix the length of w and the best directions turn out to be eigenvectors.
⑤The multiplier is the spread — the eigenvalue tells you how much spread each direction keeps.
⑥The second, the third, the rest — and a fixed budget that says how many to keep.
⑦Three more views of one answer — smallest rebuild error, columns that never repeat each other, and the SVD.
⑧PCA in the real world — finding eigenvectors by just multiplying, data wider than it is tall, the recipe, the traps, and one example done start to finish.
In one sentence: PCA looks at a cloud of data from every direction and keeps the direction along which the points land most spread out.
2
Why spread is the information
Imagine this
A chai stall owner wants to know why he sells 300 cups on some days and only 80 on others. So every evening he writes down a few things: the temperature, whether it rained, the day of the week — and the colour of his kettle.
The kettle is the same steel kettle every single day. Can it explain why sales go up and down?
Of course not. Something that never changes cannot explain something that changes.
Every model you will ever build has the same skeleton. Something you want to predict, y, is driven by your inputs x, plus some noise ε for everything you did not measure:
y=f(x)+ε
A straight line, a decision tree and a neural network are all just different choices of f.
Now read that line as a statement about change. If y moves, it moved because x moved, or because of the noise. So for every input column, the useful question is simple: how much does this column change? The tool that measures change is the one you met in §1 — the variance.
Here is a small example. We want to predict salaries from four columns: age, years of experience, number of certifications and number of trainings. Their variances are:
column
variance
what it means
age
64
changes a lot from person to person
experience
41
changes a lot too
certifications
0.09
almost everyone has zero
trainings
0.04
almost everyone has zero
The last two columns hardly move. Like the steel kettle, they cannot explain why one salary is higher than another. Dropping them costs almost nothing.
That leaves age and experience. These two have a different problem: they are twins. Older people usually have more experience, so the two columns mostly say the same thing. A normal feature-selection method would delete one twin. PCA does something smarter. It builds one new direction that carries what both were saying, and a second direction, at right angles, that carries the little that is left.
Which columns can explain anything?Left: how much each column of the salary table changes. Right: age against experience for the same forty employees — the twins.
Try: switch the bars to a log scale to see the two tiny columns at all. Then press combine the twins: one new direction appears through the cloud, and the readout says how much of the twins' spread it carries on its own.
The one surprising move
Look at what PCA was given: only the four columns. It never sees a single salary. As Prof. Saurabh puts it in class: "PCA doesn't get bothered by what you have in y. It only takes your x input features."
That is its strength — you can rank directions before you ever look at the target. It is also its main weakness, and §14 shows a case where it bites.
Because PCA swaps D old columns for M new ones, people describe it with three different names. All three are right:
People call it
because
compared with the usual way
dimension reduction
D columns go in, fewer (M) come out
the plain description of what happens
feature selection
you choose which directions survive
the usual way needs a model first, then feature importance, then a cut; PCA chooses before any model exists
feature engineering
each new column is a fresh mix z1=a1x1+⋯+aDxD
like building "loan ÷ income" by hand, except PCA finds the weights for you
And you get a bonus for free: the new columns never repeat each other. §10 shows why.
The realization
A model can only explain change in y using change in x. So a direction along which the data barely changes carries almost no information, whatever the target is.
That is why PCA ranks directions by their spread — and why it can do so without ever looking at y.
Pause & predict
A fifth column is added: "works in the Pune office". Every employee in this data works in Pune, so the column is the same for everyone. How much of the difference in salaries can it explain?
In one sentence: a column that barely changes cannot explain anything, so PCA ranks directions by their spread, and it does this without ever looking at the thing you want to predict.
3
Centre first, then build one small table
Imagine this
A PT teacher measures every child's height from the floor: 142 cm, 150 cm, 138 cm, 146 cm. Every number is big, and most of each number is just the distance up from the floor.
Now she measures from the class average instead: −2, +6, −6, +2. Suddenly every number tells you something: who is taller than usual, and by how much.
Measuring from the average is called centring. PCA always does it first.
Take the five points from §1 again: (1,2),(4,5),(7,8),(8,4),(10,6).
Step 1: find the middle. The average of the first numbers is 30/5=6. The average of the second numbers is 25/5=5. So the middle of the cloud is (6,5).
Step 2: subtract the middle from every point. Write the answers as the rows of a table. That table is the centred data matrix X: one row per point (N=5 rows), one column per feature (D=2 columns).
X=−5−2124−303−11
Quick check: each column now adds up to zero. −5−2+1+2+4=0 and −3+0+3−1+1=0. The cloud now sits around the origin.
Step 3: build one small table. For every pair of columns, multiply them row by row, add up, and divide by the number of points.
column 1 with itself: (25+4+1+4+16)/5=50/5=10
column 2 with itself: (9+0+9+1+1)/5=20/5=4
column 1 with column 2: (15+0+3−2+4)/5=20/5=4
Put the three numbers in a square:
C=N1X⊤X=[10444]
This is the covariance matrix. Read it like this:
The diagonal holds each column's own spread: 10 for the first column, 4 for the second. These are exactly the numbers you found in §1.
The off-diagonal number says how much the two columns move together. It is positive here, so when a point is to the right of the middle, it also tends to be above it.
C is symmetric: "column 1 with column 2" is the same as "column 2 with column 1".
Two details that cost marks
Divide by N, not N−1. Here N=5, so we divide by 5. Many software packages divide by N−1=4 by default, which gives [12.5555] — the same directions, but different numbers. This course divides by N.
Centre first. The formula N1X⊤X is the covariance only when every column averages to zero. Skip the centring and you get a different matrix with different eigenvectors.
Build C by handDrag any of the five points. The cross marks the mean; the table shows every point measured from it; the matrix is built from the table. Hover a cell of the matrix to see which columns it compares.
Try: drag the top-right point up and right, and watch the off-diagonal entry grow as the cloud tilts. Then switch to forgot to centre and see every entry jump — and the ellipse's long axis swing toward the mean.
drag the points
The realization
C=N1X⊤X
After centring, one small D×D table says how much each column moves (the diagonal) and which columns move together (the rest). From here on, C is the only thing about the data that PCA will ever use.
Pause & predict
For the five centred points, which covariance matrix does this course use?
Pause & predict
You forget to centre and compute 51X⊤X on the raw points (1,2),…,(10,6). You get [46343429]. What is wrong with it?
If you want the algebra · 2 proofs, step by step
Prove it · what each entry of C measures
Claim. For centred data X (N×D, rows xi), the entry Cjk of C=N1X⊤X is N1∑ixijxik: the variance of column j when j=k, and the covariance of columns j and k otherwise. C is symmetric.
1
Entry (j,k) of X⊤X is row j of X⊤ times column k of X. Row j of X⊤ is column j of X. So
(X⊤X)jk=i=1∑Nxijxik."Multiply the two columns row by row and add" — the recipe used on the five points.
2
Each column has mean 0, so xij is already "distance from the mean". Hence Cjj=N1∑ixij2 is the average squared distance from the mean — the variance of column j — and Cjk=N1∑ixijxik is the covariance of columns j and k.
A product xijxik is positive when both columns are on the same side of their means, negative when they are on opposite sides. The average says which usually happens.
3
Swapping j and k does not change ∑ixijxik, so Cjk=Ckj: C⊤=C.
∎Symmetry is what later guarantees real eigenvalues and perpendicular eigenvectors (Unit 4's spectral theorem).
Prove it · forgetting to centre adds the mean
Claim. If X~ holds the raw (uncentred) points with mean μ, then N1X~⊤X~=C+μμ⊤. For the five points this is [10444]+[36303025]=[46343429].
1
Write each raw point as mean plus deviation, x~i=μ+xi, where the deviations xi add up to 0. Then
N1i∑x~ix~i⊤=N1i∑(μ+xi)(μ+xi)⊤=μμ⊤+μxˉ⊤+xˉμ⊤+N1i∑xixi⊤,
where xˉ=N1∑ixi is the mean of the deviations.
N1X⊤X is the same as N1∑ixixi⊤: a sum of one small table per point.
2
The deviations add up to zero, so xˉ=0 and the two middle terms vanish. The last term is C. So the raw table is C+μμ⊤.
∎The extra piece μμ⊤ points along the mean. That is why the uncentred matrix's top direction swings toward (6,5) — it is describing where the cloud sits, not how it spreads.
In one sentence: subtract the average from every column, then one small symmetric table C=N1X⊤X records how much each column moves and which columns move together.
4
Every direction gets one score
Imagine this
Your tailor takes your measurements once and writes them in a small notebook. After that, you never need to stand in his shop again. He can tell how any new kurta design will fit you — straight from the notebook.
C is the data's notebook. Once you have it, you can work out the spread along any direction without touching the data again.
Pick a direction and write it as an arrow of length 1, w. Each centred point xi lands on the line at zi=xi⊤w — one dot product per point. All of them together are z=Xw.
The landing spots average to zero, because the data is centred. So their spread is just the average of their squares. Watch the data disappear:
spread of z=N1z⊤z=N1(Xw)⊤(Xw)=w⊤(N1X⊤X)w=w⊤Cw.
The left side talks about the projected points. The right side has only C and w. The data has vanished into C.
Try it on the five points, with C=[10444]:
w=(1,0): w⊤Cw=10. The spread of the first column, as in §1.
w=(0,1): w⊤Cw=4. The second column.
w=51(2,1): w⊤Cw=51(40+8+8+4)=12. The slanted line from §1.
The same three numbers as in §1. This time, not one data point was touched.
So every direction gets one score. You can picture all the scores at once as a surface: over each arrow (w1,w2), stand a height w⊤Cw. It is a bowl. The directions of length 1 form a ring on the floor, and the ring lifted onto the bowl is a wavy rim. Its highest point is the best direction.
The score bowlOver every arrow (w1,w2) stands the height w⊤Cw. The glowing ring is every arrow of length 1, lifted onto the bowl. Its highest point is PC1 (orange); its lowest is PC2 (green). Drag to orbit.
Try: press ▶ and ride the marker around the ring. It climbs to 12 and drops to 2, twice each lap, because w and −w are the same line. Switch to [5445]: the high points swing to 45∘.
drag the picture to orbit
—
The height at an arrow of length 1 is the spread of the data along it. Only the ring matters: inside it the arrows are too short, outside too long.
The realization
spread along w=w⊤Cw
For any arrow w of length 1: one number for every direction, and no data needed. PCA is now a clean question: which unit arrow w makes w⊤Cw as big as possible?
Pause & predict
With C=[10444], what is the spread along the 45° direction w=21(1,1)?
If you want the algebra · 1 proof, step by step
Prove it · the spread along w is wᵀCw
Claim. For centred data X and a unit vector w, the landing positions zi=xi⊤w have mean 0 and variance w⊤Cw.
1
The mean of the zi is N1∑ixi⊤w=(N1∑ixi)⊤w=0⊤w=0.
Projection is linear, so the projected mean is the projection of the mean — and the mean is 0.
2
With mean 0, the variance is the average square. Stack the zi as z=Xw:
Var(z)=N1i∑zi2=N1z⊤z.A sum of squares is a dot product of a vector with itself.
3
Substitute and regroup, using (AB)⊤=B⊤A⊤:
N1(Xw)⊤(Xw)=N1w⊤X⊤Xw=w⊤(N1X⊤X)w=w⊤Cw.∎The data is gone — only C is left. This is also why C can never have a negative eigenvalue: w⊤Cw is an average of squares, so it is never below 0.
In one sentence: the spread along any unit direction w is w⊤Cw, so once you have C every direction gets a score without looking at the data again.
5
The leash — why the arrow must have length one
Imagine this
School sports day. The rule: "whoever throws the ball farthest wins". One boy quietly walks ten metres past the line before he throws. Of course he wins.
But he did not throw better. He changed the rules. For a fair contest, everyone has to throw from the same line.
Our contest has the same loophole. Take the winning direction from §4, w=51(2,1), with spread 12. Now double the arrow to 2w. Every landing number zi doubles, so every square grows four times, and the "spread" jumps to 48. Triple it and you get 108.
The arrow did not point anywhere better. It just got longer. We care about the direction, not the length.
So we put the arrow on a leash of length 1. The length of an arrow is ∥w∥=w⊤w, so "length 1" is the same as w⊤w=1. Now the question is fair:
wmaxw⊤Cwsubject tow⊤w=1.
Make something as big as possible, while obeying a rule. You met exactly this in Unit 11: there was a wall, and we turned the wall into a fine. Do the same here. Write the rule as "something =0", namely w⊤w−1=0, and charge a fine λ for breaking it:
L(w,λ)=w⊤Cw−λ(w⊤w−1).
At the best point, the slope of L with respect to w is zero. The slope of w⊤Cw is 2Cw, and the slope of w⊤w is 2w. So
2Cw−2λw=0⟹Cw=λw.
Stop and look at that. We asked a question about spread, and the answer came back as the definition of an eigenvector (Unit 4): an arrow that C only stretches, never turns. The best direction must be an eigenvector of C. Nothing else is even a candidate.
Why the fine works — the picture
The leash lets w walk only on the unit circle. Stand at the best point on the circle. If a tiny step along the circle made the score go up, you would take it — so at the top, a step along the circle changes nothing.
That means the uphill arrow of the score, ∇f=2Cw, has no part along the circle. It must point straight out of the circle. And "straight out of the circle" is the direction of w itself — the uphill arrow of the rule, ∇g=2w. Two arrows pointing the same way: ∇f=λ∇g, which is Cw=λw again.
The leash and the two arrowsContour rings of the score w⊤Cw, and the unit circle — the leash. At the bead: the uphill arrow of the score ∇f=2Cw (orange) and the uphill arrow of the rule ∇g=2w (grey).
Try: drag the bead around the circle and watch the parallel meter. The two arrows line up — angle 0∘ — at exactly two kinds of place: the top of the score (PC1) and the bottom (PC2). Everywhere else the orange arrow leans along the circle, telling you which way is uphill.
drag the bead along the circle
The realization
Cw=λw
On the leash, the best direction is the place where the uphill arrow 2Cw points straight along w. That is exactly what an eigenvector is. The directions PCA is looking for are the eigenvectors of C.
Pause & predict
Why can't we simply maximise w⊤Cw with no leash at all?
Pause & predict
You slide w around the unit circle. At the best point, which way does the uphill arrow 2Cw point?
If you want the algebra · 2 proofs, step by step
Prove it · the fine turns into Cw = λw
Claim. Any w that maximises w⊤Cw subject to w⊤w=1 satisfies Cw=λw for some number λ.
1
For a symmetric matrix A, the gradient of q(w)=w⊤Aw is 2Aw. Write q=∑j,kAjkwjwk and differentiate by wm:
∂wm∂q=k∑Amkwk+j∑Ajmwj=2(Aw)m.wm appears once as wj and once as wk; symmetry Ajm=Amj makes the two sums equal. With A=I this gives ∇(w⊤w)=2w.
2
The Lagrangian is L(w,λ)=w⊤Cw−λ(w⊤w−1). Setting both partial derivatives to zero:
∂w∂L=2Cw−2λw=0,∂λ∂L=−(w⊤w−1)=0.The second equation just gives the leash back. The first is the new information.
3
Divide the first by 2: Cw=λw, with w=0 because it has length 1. So w is an eigenvector of C and λ its eigenvalue.
∎The slides write the fine with the opposite sign, L=b⊤Sb+λ(1−b⊤b). It is the same function, so the same answer.
Prove it · why the two arrows must line up
Claim. If w⋆ maximises f(w) on the curve g(w)=c, and ∇g(w⋆)=0, then ∇f(w⋆)=λ∇g(w⋆) for some λ.
1
Take a tiny step δ that stays on the curve. Then g does not change, so to first order ∇g⋅δ=0: the step is at right angles to ∇g.
On the unit circle, ∇g=2w points straight out, and every step along the circle is at right angles to it.
2
At the best point, that step cannot change f either: if ∇f⋅δ>0 you would step forward, and if it were <0 you would step backward, and f would go up. So ∇f⋅δ=0 as well.
This is the "you would take it" argument from the page, written as one line.
3
In two dimensions the steps along the curve form one line, and both ∇f and ∇g are at right angles to it. Two arrows at right angles to the same line are parallel: ∇f=λ∇g. (In more dimensions the same holds, because both are at right angles to every allowed step.) With f=w⊤Cw, g=w⊤w: 2Cw=2λw.
∎The Lagrangian is just bookkeeping for this picture: ∂L/∂w=0 is "the arrows line up", and ∂L/∂λ=0 is "stay on the curve".
In one sentence: fix the arrow's length to 1, turn that rule into a fine, and setting the slope to zero leaves Cw=λw — the best directions are eigenvectors of C.
6
The fine turns out to be the spread
Imagine this
The commentator says, "the required run rate is 9". That one number means three things at once. It is runs per over. It is how fast the score must climb. And it is the slope of the worm chart.
Three readings, one number. The λ in PCA is like that.
We know the best direction is an eigenvector. But C has several. Which one wins? Put Cw=λw back into the score:
w⊤Cw=w⊤(λw)=λw⊤w=λ⋅1=λ.
The spread along an eigenvector is its eigenvalue. So the winner is simple: the eigenvector with the largest eigenvalue.
Check it on C=[5445] with w=21(1,1). Then Cw=21(9,9)=9w, so λ=9. And w⊤Cw=21(5+4+4+5)=9. The other eigenvector, 21(1,−1), has λ=1 and spread 1. No direction does better than 9, and none does worse than 1.
So the same number λ plays three parts:
Read it as
it is
where you see it
the fine (Lagrange multiplier)
the price of the rule ∥w∥=1
L=w⊤Cw−λ(w⊤w−1)
an eigenvalue
how much C stretches w
Cw=λw
a variance
the spread of the data along w
w⊤Cw=λ
Keep the two roles apart. The principal component is the eigenvector w — a direction. The eigenvalueλ is the spread along it — a number.
One number, three readingsTurn one arrow w and watch three panels. Left: how much C stretches w. Middle: the spread of the data along w. Right: the fine in the Lagrangian. At an eigenvector all three say the same number.
Try: press snap to PC1. The orange arrow Cw lies exactly on top of w, the landing dots spread as wide as they can, and all three panels read λ1. Now turn w a little: the three numbers split apart.
The realization
w⊤Cw=λ
The spread along an eigenvector is its eigenvalue. So the largest spread is the largest eigenvalue, and it lives along that eigenvector. The same number is the stretch, the spread and the fine. That is why we always list eigenvalues from biggest to smallest, λ1≥λ2≥…: it is a ranking of directions by how much of the data they show.
Pause & predict
For C=[5445], what is the largest spread you can get along any unit direction?
Pause & predict
For C=[5228] the top eigenvalue is 9, with eigenvector direction (1,2). A student forgets to shrink it to length 1 and computes the spread along (1,2) itself. What does she get?
If you want the algebra · 1 proof, step by step
Prove it · spread = λ, and nothing beats λ₁
Claim. (a) If Cw=λw, then w⊤Cw=λ∥w∥2, which is λ for a unit vector. (b) For every unit w, λD≤w⊤Cw≤λ1.
1
(a) w⊤Cw=w⊤(λw)=λw⊤w=λ∥w∥2.
So the unit length is not optional: for (1,2) with λ=9 the "spread" is 9×5=45.
2
(b) Write any unit w in the orthonormal eigenvectors: w=c1w1+⋯+cDwD, with c12+⋯+cD2=1. Then
w⊤Cw=d∑λdcd2.The cross terms vanish because the eigenvectors are at right angles: wj⊤Cwk=λkwj⊤wk=0 for j=k.
3
That is a weighted average of the λd with weights cd2 adding to 1. An average can never exceed the largest value or fall below the smallest:
λD=λDd∑cd2≤d∑λdcd2≤λ1d∑cd2=λ1.
The top is reached only when all the weight sits on w1.
∎This is the hump from §1 in one line: every direction's spread is a blend of the eigenvalues, and the blend is biggest when it is pure λ1.
In one sentence: put Cw=λw back into the score and it becomes λ, so the fine, the stretch and the spread are one number, and the top eigenvector wins.
7
The second direction, and all the rest
Imagine this
You give an auto driver directions: "Go straight down MG Road for 3 km." That covers most of the trip.
Then: "Now turn left, 400 metres." The second instruction only helps because it goes a new way. Telling him "go straight another 400 m" would just repeat the first instruction.
The first component gets the biggest share of the spread. The second one should get the biggest share of what is left — without repeating the first. There are two ways to say this, and they give the same answer.
Route A — add a second leash. Ask for the best unit direction w2 that is also at right angles to the first: w2⊤w1=0. That is one more rule, so one more fine, μ:
L=w2⊤Cw2−λ(w2⊤w2−1)−μw2⊤w1.
Set the slope to zero, then multiply by w1⊤. Almost every term dies, and you are left with μ=0. The second fine is free! So the condition is again Cw2=λw2: the second component is also an eigenvector, the one with the second-largest eigenvalue.
Route B — peel off what you already have. This is the way the slides do it. Take the part of every point that lies along w1, and remove it:
X^=X−Xw1w1⊤.
(The slides store points as columns, so they write X^=X−b1b1⊤X. Same thing.) The cloud is squashed flat along w1. Now find the top direction of this cloud. Its covariance C^ has the same eigenvectors as C, except that w1's eigenvalue has dropped to 0. So the new winner is w2. Peel again to get w3, and so on.
Route A · second leash
Route B · peel it off
the idea
best direction at right angles to the ones you have
best direction of what the old ones did not explain
what you solve
Cw2=λw2, after showing μ=0
the top eigenvector of C^
the answer
w2, with spread λ2
w2, with spread λ2
One more gift. We never had to force the components to be at right angles. C is symmetric, and Unit 4's spectral theorem says a symmetric matrix always has a full set of eigenvectors that are all at right angles to each other. Perpendicular comes free. Its eigenvalues are also real and never negative — they are spreads, after all.
Find it, peel it, repeatA 3-D cloud with spreads 9,4,1 along its hidden axes. Find the top direction, then peel it off: every point slides along that direction onto the glass plane through the middle. The bars on the right are the eigenvalues of what is left. Drag to orbit.
Try: press the buttons in order. After the first peel the orange bar falls to 0 and the other two do not move at all — then the top of what is left is exactly the second direction. Or press ▶ and watch the whole story.
drag the picture to orbit
The realization
Cwd=λdwdλ1≥λ2≥⋯≥λD≥0
Each new component is the best direction of what is left. Whether you add a leash or peel off the old components, you land on the next eigenvector of the same C — and they all meet at right angles for free.
Pause & predict
A 3-D cloud has eigenvalues 9,4,1. You peel off the first component. What are the eigenvalues of what is left?
If you want the algebra · 2 proofs, step by step
Prove it · the second fine is free (μ = 0)
Claim. Maximising w2⊤Cw2 subject to w2⊤w2=1 and w2⊤w1=0, where Cw1=λ1w1, gives Cw2=λw2.
1
Two rules, two fines: L=w2⊤Cw2−λ(w2⊤w2−1)−μw2⊤w1. Setting the gradient to zero:
2Cw2−2λw2−μw1=0.The gradient of w2⊤w1 with respect to w2 is just w1.
2
Multiply on the left by w1⊤, and use w1⊤C=(Cw1)⊤=λ1w1⊤. The three terms become 2λ1(w1⊤w2), 2λ(w1⊤w2) and μ(w1⊤w1), and w1⊤w2=0, w1⊤w1=1:
0−0−μ⋅1=0⟹μ=0.C is symmetric, so w1⊤C is the transpose of Cw1.
3
With μ=0, step 1 reads Cw2=λw2. Among eigenvectors at right angles to w1, the spread λ is biggest for λ2. Repeat for w3 with two right-angle rules, and so on.
∎The right-angle rule costs nothing because the best free answer already obeys it: eigenvectors of a symmetric matrix are perpendicular anyway.
Prove it · peeling keeps the eigenvectors (both cases)
Claim. Let B=w1w1⊤+⋯+wm−1wm−1⊤ (the flattener onto the used directions) and X^=X−XB. Then C^=N1X^⊤X^=(I−B)C(I−B) has every eigenvector wi of C: with eigenvalue 0 if i≤m−1, and with the same λi if i≥m.
1
B is symmetric and X^=X(I−B), so
C^=N1(I−B)⊤X⊤X(I−B)=(I−B)C(I−B)=C−CB−BC+BCB.This is the slides' expansion S−SB−BS+BSB, in our row layout.
2
Case i≥m (not yet used). wi is at right angles to every used direction, so Bwi=0. Also BCwi=λiBwi=0. Hence
C^wi=Cwi=λiwi
(the other three terms are 0).
Untouched directions keep exactly their spread.
3
Case i≤m−1 (already used). Now Bwi=wi, so (I−B)wi=0, and therefore
C^wi=(I−B)C(I−B)wi=0,
because the last factor (I−B)wi is already 0.
So the used directions are still eigenvectors, now with eigenvalue 0. The largest eigenvalue of C^ is therefore λm, with eigenvector wm.
∎So peeling never invents a new direction. It just switches off the ones you have, and the next eigenvector of the original C moves to the top.
In one sentence: every later component is the top eigenvector of what the earlier ones left behind, and because C is symmetric they all come out at right angles.
8
The spread budget is fixed
Imagine this
A family has ₹50,000 a month. They can move money between rent, groceries and school fees however they like. But no amount of moving creates one extra rupee.
PCA does the same with spread. Turning the axes moves spread between directions. It never creates it and never destroys it.
For the five points, the total spread in the original columns is 10+4=14 — the sum of the diagonal of C, called the trace. Along the two principal directions the spreads are λ1=12 and λ2=2. And 12+2=14. The same budget, split differently.
This always holds, for any number of columns:
tr(C)=C11+C22+⋯+CDD=λ1+λ2+⋯+λD.
So each eigenvalue is a slice of one fixed budget, and its share is easy:
share kept by the top M=λ1+⋯+λDλ1+⋯+λM.
For the five points, one component keeps 12/14=85.71% of the spread. Plot every eigenvalue as a bar, biggest first, and you have a scree plot (scree is the pile of stones at the foot of a cliff — the bars fall like one). Plot the running total and you get the curve people actually decide from.
How many components M should you keep? People use three rules:
rule
how it works
good for
watch out
hit a target share
keep adding components until the running total passes 90 %, 95 % or 99 %
the most common choice; easy to defend
you must pick the target
find the elbow
stop where the scree stops falling steeply and flattens out
a long, flat tail of noise
some plots have no clear elbow
keep λ>1 (Kaiser)
keep a component only if it carries more than one original column's worth
standardised data, where every column contributes exactly 1
meaningless if the columns were not standardised
A big percentage is not always good news
"PC1 explains 98 %" can mean the data really lies near a line. It can also mean one column is measured in units that make its numbers huge — say, salary in rupees next to age in years — and it simply dominates the total. Check that you standardised (§14) before you celebrate.
The scree plot and three rulesBars: each eigenvalue's share of the budget. Line: the running total. The kept bars light up. Below: how many components each of the three rules would keep.
Try: on the practice-set eigenvalues, move the target to 90%: the third bar lights up, because two components only reach 82.5%. Then open the noisy tail and compare the three rules — they do not agree, and that is normal.
The realization
tr(C)=λ1+λ2+⋯+λD
Turning the axes never changes the total spread. PCA just pushes as much of it as possible into the first few directions — which is exactly why keeping only those few loses so little.
Pause & predict
A five-column dataset has eigenvalues 4.5,2.1,0.9,0.4,0.1. What is the total spread, and what share do the first two keep?
Pause & predict
Same eigenvalues. What is the smallest number of components that keeps at least 90%?
If you want the algebra · 1 proof, step by step
Prove it · the trace is the sum of the eigenvalues
Claim.tr(C)=∑dCdd=∑dλd: the total spread of the original columns equals the total spread along the principal directions.
1
The spectral theorem gives C=WΛW⊤ with W⊤W=I (all D eigenvectors as columns).
Symmetric C always has a full set of perpendicular unit eigenvectors.
2
The trace does not change when you move the first factor of a product to the end: tr(AB)=tr(BA). So
tr(C)=tr(WΛW⊤)=tr(ΛW⊤W)=tr(Λ)=d∑λd.∎Why tr(AB)=tr(BA): both are ∑j,kAjkBkj — the same terms added in a different order.
In one sentence: the eigenvalues add up to the trace, so they split one fixed spread budget, and you keep the biggest slices until you have the share you need.
9
The second view — the smallest rebuild error
Imagine this
You text a friend where a dhaba is, using just one number: "7.2 km along the highway from the toll plaza". Your friend drives 7.2 km and stops on the highway.
If the dhaba is actually 300 m off the road, those 300 m are lost. They never fitted into your one number. That gap is the rebuild error.
If you get to choose the road, pick the one the dhabas hug most closely.
So far PCA has been about keeping the most spread. Here is the same thing seen from the other side: losing the least.
With the kept directions as the columns of W, a point is squeezed into a short code and then rebuilt:
encode:decode:z=W⊤x(one number per kept direction)x~=Wz=WW⊤x(back to a point on the line)
With one direction w, the rebuilt point x~ is the foot of the thread from x to the line. The point, the foot and the origin make a right-angled triangle. Pythagoras says:
∥x∥2=kept(x⊤w)2+lost∥x−x~∥2.
Add this up over all the points. The left side is the total spread — fixed, whatever line you choose. So whatever you gain in "kept", you lose in "lost". It is a seesaw. The line that keeps the most spread is exactly the line that loses the least.
And the average loss has a clean value: it is the sum of the eigenvalues you dropped. For the five points, keeping one direction loses on average λ2=2 per point.
One point, all the way through
A new point arrives: (12,9). Use the five points' mean (6,5) and their top direction w1=51(2,1).
Centre it:(12−6,9−5)=(6,4).
Encode:z=w1⊤(6,4)=512+4=516≈7.155.
Decode:zw1=516(2,1)=(6.4,3.2). Add the mean back: x~=(12.4,8.2).
The error:(6−6.4)2+(4−3.2)2=0.16+0.64=0.80.
And here is the neat part. Along the direction we threw away, w2=51(1,−2), the point's score is z2=56−8, and z22=54=0.80. The error is exactly the squared score along the dropped direction.
Two products that look alike
W⊤W=I: a small M×M table. It just says the kept directions have length 1 and meet at right angles.
WW⊤ is the big D×D one, and it is the flattener. It squashes any point onto the kept line (or plane). It equals I only if you keep every direction. Whatever it squashes away is the rebuild error.
The seesaw: kept against lostEvery point is rebuilt from its landing spot. The red threads are what the rebuild loses. The bar underneath is one fixed total, split into kept (blue) and lost (red).
Try: turn the line slowly. The red part of the bar grows exactly as the blue part shrinks — the total never moves. The lost part is smallest precisely where the kept part is biggest. Then open the 3-D tab and tilt a glass plane through a 3-D cloud.
drag the orange tip to turn the line
drag the picture to orbit
The realization
lost=total−keptN1i∑∥xi−x~i∥2=λM+1+⋯+λD
Because the total is fixed, "keep the most spread" and "lose the least" are one instruction. The slides call these the maximum-variance view and the projection view of PCA. They are two sides of one seesaw.
Pause & predict
The new point (12,9) was rebuilt from one number as (12.4,8.2). Its squared error is 0.80. Why is that the same as z22, the square of its score along w2?
Pause & predict
For the five points (λ1=12,λ2=2) you keep one component. What is the average squared rebuild error over the five points?
If you want the algebra · 1 proof, step by step
Prove it · the average error is the dropped eigenvalues
Claim. With orthonormal kept directions W (D×M) and x~=WW⊤x: ∥x−x~∥2=∥x∥2−∥W⊤x∥2, and averaged over the centred data N1∑i∥xi−x~i∥2=tr(C)−tr(W⊤CW). With W = the top M eigenvectors this is λM+1+⋯+λD, the smallest possible.
1
Expand the square, using W⊤W=I:
∥x−WW⊤x∥2=x⊤x−2x⊤WW⊤x+x⊤W(W⊤W)W⊤x=∥x∥2−∥W⊤x∥2.For one direction: error =∥x∥2−(x⊤w)2 — Pythagoras, in symbols.
2
Average over the points. N1∑i∥xi∥2=tr(C), and N1∑i∥W⊤xi∥2=tr(W⊤CW), the total spread kept. So average error = total − kept.
The total does not depend on W. Minimising the error and maximising the kept spread are the same problem — the seesaw.
3
With W=[w1⋯wM], W⊤CW=diag(λ1,…,λM), so the kept spread is λ1+⋯+λM and the average error is λM+1+⋯+λD. Choosing the top eigenvectors keeps the most, so it loses the least.
∎Five points, M=1: the error is λ2=2 on average; the new point (12,9) happens to lose 0.80.
In one sentence: by Pythagoras, what a direction keeps plus what it loses always adds up to the same total, so the line with the most spread is also the line with the smallest rebuild error.
10
New columns that never repeat each other
Imagine this
Two friends rush in with the same news, at the same moment, in almost the same words. From the second one you learn nothing new.
Age and experience are like those two friends: when one goes up, the other usually does too. PCA swaps them for new columns that never echo each other.
The new columns are the scores Z=XW: one column per kept direction. What does their covariance look like? Do the same three-line move as §4:
Cov(Z)=N1Z⊤Z=W⊤(N1X⊤X)W=W⊤CW=Λ=λ1⋱λM.
The last step uses CW=WΛ (all the eigen-equations side by side) and W⊤W=I.
Everything off the diagonal is zero. Off-diagonal entries are how much two columns move together — so the new columns are uncorrelated. And each new column's spread is its eigenvalue: "spread =λ" once more, for all components at once.
This is why PCA is popular before a regression. Correlated inputs make a model unsure which twin is doing the work. The usual fix deletes one twin and throws information away. PCA keeps all the information but re-expresses it along directions that never overlap.
Reading a component: the loadings
"But then I no longer know what my columns mean!" Not quite. Each component is a recipe:
z1=a1x1+a2x2+⋯+aDxD,w1=(a1,…,aD).
The weights ad are called the loadings. They are just the entries of the eigenvector. Say three columns — age, experience, certifications — give
Age has the biggest weight in w1, so PC1 is "mostly an age axis". Experience leads w2, so PC2 is "mostly an experience axis". The meaning is still there; you just read it one level deeper.
Any real set of loadings must pass two checks:
Length 1:491(36+9+4)=1 and 51(1+4+0)=1. ✓
Right angles:w1⊤w2=751(−6+6+0)=0. ✓
If a proposed pair fails either check, it is not a pair of principal components.
One more thing: the sign of a component means nothing. If Cw=λw, then also C(−w)=λ(−w). Two programs may hand you opposite signs for the same data. Read the pattern — which loadings are big, which have the same sign — not whether one is +0.7 or −0.7.
Twins no moreLeft tab: two correlated columns, turned into their principal-component scores. Right tab: three columns — age, experience, certifications — and each component read as a recipe: walk its loading along age, then along experience, then up certifications, and you arrive at the tip of the component's arrow.
Try: press ▶ rotate and watch the correlation fall from 0.78 to 0.00 as the cloud turns to lie along the axes. On the loadings tab, press flip the signs: every bar changes sign, and nothing about the meaning changes.
drag the picture to orbit
The realization
Cov(Z)=W⊤CW=Λ
The new columns are uncorrelated by construction, and each one's spread is its eigenvalue. The loadings are the recipe for each new column: read the pattern, not the sign.
Pause & predict
Someone hands you three proposed pairs of loadings for two columns. Which pair could really be the two principal components?
If you want the algebra · 1 proof, step by step
Prove it · the scores are uncorrelated
Claim. The scores Z=XW, with W holding unit eigenvectors of C as columns, have mean 0 and covariance Cov(Z)=Λ=diag(λ1,…,λM).
1
Each score column averages to zero, because X does (§4, step 1). So its covariance is N1Z⊤Z:
N1Z⊤Z=N1W⊤X⊤XW=W⊤CW.The same three-line move as w⊤Cw, with a whole matrix of directions at once.
2
All eigen-equations side by side read CW=WΛ. And W⊤W=I. So
W⊤CW=W⊤WΛ=Λ.∎Off-diagonal zeros: no two components move together. Diagonal: each component's spread is its eigenvalue. For the five-eigenvalue example, Cov(Z)=diag(4.5,2.1,0.9,0.4,0.1).
In one sentence: the scores have covariance W⊤CW=Λ, so the new columns never repeat each other, and the loadings are the recipe that says what each one is made of.
11
Turn, stretch, turn — the SVD route
Imagine this
When you send a photo on WhatsApp, it is squeezed so it travels fast. Squeeze it a little and nobody notices. Squeeze it too hard and faces turn to blocks.
A photo is just a big table of numbers — a matrix. The best possible way to squeeze a matrix turns out to be PCA again, in a different coat.
Unit 5 showed that every matrix, however messy, does three simple things in a row: turn, stretch, turn. That is the singular value decomposition (SVD):
X=UΣV⊤.
U and V are pure turns (their columns have length 1 and meet at right angles), and Σ is a diagonal stretch with the singular values σ1≥σ2≥⋯≥0.
Now feed the SVD into the covariance matrix. The inner U⊤U is I, so it drops out:
C=N1X⊤X=N1VΣU⊤UΣV⊤=VNΣ2V⊤.
Compare that with the eigen-split C=WΛW⊤. Same shape: a turn, a diagonal, the turn back. So they must be the same thing:
W=V,λd=Nσd2.
Why squared?C is built from X⊤X: the data appears twice, so a stretch of σ becomes σ2.
Why divide by N?X⊤X is a sum over all N points, and a variance is an average.
U or V? Ask which one has D rows — that one lives in feature space and holds the directions. With points in rows (our way) it is V. The slides store points in columns, so for them it is U.
Most software takes this route. It never builds C at all, which keeps more decimal places, and it can stop after the top few pieces.
The best squeeze: Eckart–Young
The SVD writes X as a sum of simple layers, each one a single stretch σdudvd⊤. Keep only the top M layers:
X~M=σ1u1v1⊤+⋯+σMuMvM⊤=UMΣMVM⊤.
The Eckart–Young theorem says no matrix of rank M comes closer to X. And the error is made of exactly what you dropped:
∥X−X~M∥2=σM+1,∥X−X~M∥F=σM+12+σM+22+⋯
(The first is the biggest stretch left over; the second is the square root of the sum of every squared entry of the error.)
Packing for the trip home
You are going home for Diwali and the suitcase fits M things. The obvious plan: pack the biggest, most useful things first, and stop when it is full.
What is not obvious — and what Eckart–Young actually proves — is that no clever repacking beats this greedy order. Taking the top M singular layers is not just sensible. It is the best there is.
Keep the biggest layersA drawn picture of a village scene is just a table of numbers. Its SVD splits it into layers, biggest first. Keep k layers and see what comes back — and how big the error is in both norms.
Try: drag k from 1 upward. By k=6 you can see the sun, the hills and the tree; by k=20 it is hard to tell from the original. The error readout always equals the first dropped singular value (spectral) and the root of the sum of the dropped squares (Frobenius). Then open the data cloud tab.
the original
rebuilt from 6 layers
drag the picture to orbit
The realization
C=VNΣ2V⊤W=V,λd=Nσd2
The principal directions are the right singular vectors of the centred data. Cutting the SVD after M layers is the best possible rank-M copy of the data — PCA again, seen as compression.
Pause & predict
A centred data matrix has N=100 rows and singular values 20,10,5,1. What are the eigenvalues of C?
Pause & predict
Same matrix. You keep the best rank-2 copy. How big is the error in the two norms?
If you want the algebra · 2 proofs, step by step
Prove it · the SVD hands you the components
Claim. If the centred X=UΣV⊤ (U⊤U=I, V⊤V=I, Σ diagonal), then C=V(Σ2/N)V⊤: the columns of V are the principal directions and λd=σd2/N. The scores are Z=XV=UΣ.
1
Substitute and simplify:
C=N1(UΣV⊤)⊤(UΣV⊤)=N1VΣ⊤(U⊤U)ΣV⊤=VNΣ2V⊤.U⊤U=I because U's columns are orthonormal; Σ⊤=Σ because it is diagonal.
2
Multiply on the right by V: CV=V(Σ2/N). Column d of this says Cvd=(σd2/N)vd. So vd is a unit eigenvector with eigenvalue σd2/N. And XV=UΣV⊤V=UΣ.
∎In the slides' layout (points as columns), S=N1XX⊤=U(ΣΣ⊤/N)U⊤, so there the directions are the columns of U. Pick the factor with D rows.
Prove it · the error of the truncated SVD
Claim. With X~M=∑d≤Mσdudvd⊤: ∥X−X~M∥2=σM+1 and ∥X−X~M∥F2=∑d>Mσd2. (Eckart–Young adds that no rank-M matrix does better; that part is stated, not proved here.)
1
The SVD is a sum of layers, X=∑dσdudvd⊤. So the leftover is itself an SVD, made only of the dropped layers:
X−X~M=d>M∑σdudvd⊤.Its singular values are exactly σM+1,σM+2,….
2
The spectral norm of any matrix is its largest singular value, so ∥X−X~M∥2=σM+1. The squared Frobenius norm is the sum of its squared singular values (it is tr(E⊤E), and the trace is the sum of the eigenvalues σd2), so ∥X−X~M∥F=σM+12+σM+22+⋯.
∎Singular values 20,10,5,1, M=2: errors 5 and 26≈5.10. And ∥X−X~M∥F2/N=∑d>Mσd2/N=∑d>Mλd — the rebuild error of §9 again.
In one sentence: substituting X=UΣV⊤ into C gives W=V and λ=σ2/N, and cutting the SVD after M layers is the best rank-M copy of the data, with an error made of the dropped singular values.
12
Finding the top direction by just multiplying
Imagine this
At the school function, the microphone gets too close to the speaker. Any small sound goes round the loop — mic, amplifier, speaker, mic — and every trip makes one pitch a little louder than all the others.
A few seconds later that one pitch is all you can hear: the howl. Power iteration is that loop, used on purpose.
By hand, you find eigenvalues by solving det(C−λI)=0. For a 2×2 matrix that is a quadratic. For 3×3 it is a cubic, and 4×4 a quartic — there are formulas, though nobody enjoys them.
At 5×5 the method dies, and not because nobody has been clever enough. The Abel–Ruffini theorem proves that a general polynomial of degree 5 or more has no formula for its roots using +,−,×,÷ and roots. Not "none is known" — none can exist. So every real eigenvalue program iterates: start with a guess, improve it, stop when it stops changing.
There is a second reason to iterate. A full eigen-split of a D×D matrix costs about D3 steps and returns all D directions. PCA usually wants two, or ten. Paying for hundreds and binning most of them is waste.
The simplest iteration goes straight for the top direction. Start with any arrow x0 and repeat:
xk+1=∥Cxk∥Cxk.
Multiply by C, shrink back to length 1, repeat. That is the whole method.
Try it on C=[5445] from x0=(1,0). First pass: Cx0=(5,4), whose length is 41, so x1≈(0.781,0.625). Second pass: C(5,4)=(41,40), so x2≈(0.716,0.698). It is closing in on the answer 21(1,1)≈(0.707,0.707) fast.
Why it works. Write the start in terms of the eigenvectors: x0=c1w1+c2w2. Each multiplication by C stretches the w1 part by λ1 and the w2 part by λ2. After k passes:
The ratio λ2/λ1 is less than 1, so the wrong part fades away pass after pass. Here λ2/λ1=1/9: each pass shrinks the wrong part nine times.
When it crawls
If the top two eigenvalues are close — say 5.0 and 4.9 — the ratio is 0.98, and each pass shrinks the wrong part by only 2 %. Progress is very slow. But then the top two directions carry almost the same spread anyway, so "which one comes first" hardly matters. Real libraries use smarter versions of this loop for that case.
The howl: power iterationMultiply by C, shrink back to length 1, repeat. Left: the arrow swings toward the top direction pass by pass, leaving a faint trail. Right: its remaining angle on a log scale — a straight line whose slope is set by λ2/λ1.
Try: at λ2/λ1=1/9 press ▶: the arrow lands in two or three passes. Drag the ratio to 0.98 and press ▶ again — it crawls, and the line on the right barely slopes. The 3-D tab runs the same loop on a 3×3 matrix, hopping across a sphere.
drag the picture to orbit
Here C has eigenvalues 6,3,1, so each pass shrinks the part along w2 to half and the part along w3 to a sixth.
The realization
xk+1=∥Cxk∥Cxk
No formula can find the eigenvalues of a big matrix, so software multiplies instead. Each multiplication by C favours the direction C stretches most: the wrong part shrinks by λ2/λ1 every pass, until only the top direction is left.
Pause & predict
Power iteration on C=[5445] from x0=(1,0). After one pass, where is the arrow, and by how much has the wrong part shrunk?
If you want the algebra · 1 proof, step by step
Prove it · power iteration closes in by λ₂/λ₁
Claim. If λ1>∣λ2∣≥… and x0 has a non-zero part c1 along w1, the direction of Ckx0 tends to ±w1, and in two dimensions the tangent of the angle to w1 is multiplied by exactly λ2/λ1 each pass.
1
The rescaling in xk+1=Cxk/∥Cxk∥ only changes the length, never the direction, so xk points the same way as Ckx0.
The division by the length only stops the numbers overflowing.
2
Expand x0=∑dcdwd. Each multiplication scales the d-th part by λd:
Ckx0=d∑cdλdkwd=λ1k(c1w1+d≥2∑cdrdkwd),
where rd=λd/λ1.
Every ratio λd/λ1 is less than 1 in size, so every term but the first fades geometrically.
3
In two dimensions the angle θk to w1 has tanθk=∣c1∣λ1k∣c2∣λ2k=tanθ0(λ1λ2)k.
∎For C=[5445] from (1,0): θ0=45∘, then tanθ1=1/9 (6.34∘), tanθ2=1/81 (0.71∘). On a log scale, a straight line with slope log(λ2/λ1).
In one sentence: no formula finds the eigenvalues of a big matrix, so software multiplies by C and rescales, and each pass shrinks everything except the top direction by the factor λ2/λ1.
13
When columns outnumber rows — the Gram trick
Imagine this
A hospital lab has tissue from 40 patients. For each one, a machine reads 12,000 genes. The spreadsheet is 40 rows tall and 12,000 columns wide — a class register with 40 students and twelve thousand subjects.
Most data is long: many rows, few columns. This data is wide. And the usual recipe falls over on it.
The covariance matrix is always (number of columns) × (number of columns), no matter how few rows you have. Here that is 12,000×12,000=1.44×108 numbers. At 8 bytes each, that is about 1.152 GB — for a dataset that is only a few megabytes. Worse, an eigen-split costs about D3≈1.7×1012 steps. Hours of work, to learn from 40 patients.
The tempting wrong fix
"X⊤X is huge, so use XX⊤ instead — it is only 40×40!" Right instinct, wrong statement. XX⊤ is not the covariance matrix. Its rows and columns are indexed by patients, not genes, and its eigenvectors have 40 entries, when we need 12,000. We can still use it — as a stepping stone.
The trick is one multiplication. Start from the eigen-equation we want, N1X⊤Xw=λw, and multiply both sides on the left by X:
N1XX⊤(Xw)=λ(Xw).
Give the two pieces names. K=N1XX⊤ is the small N×N table, called the Gram matrix. And u=Xw has N entries. Then
Ku=λu.
An eigen-problem on a 40×40 table. And the λ is the sameλ.
Getting back. Solving the small problem gives u. To get w, multiply by X⊤: then C(X⊤u)=λ(X⊤u), so X⊤u is an eigenvector of C with that same λ. It points the right way but has the wrong length, so finish with
w=∥X⊤u∥X⊤u.
Forgetting this last step is the most common slip, and it quietly breaks "spread =λ".
Nothing is lost
C has 12,000 eigenvalues. But 40 points can only span a flat piece of space of at most 40 dimensions — and centring (making the rows add to zero) takes away one more. So at most N−1=39 eigenvalues can be non-zero. The other 11,961 are exactly zero and carry no spread at all.
The small table K already holds every non-zero eigenvalue there was. The Gram trick is not an approximation. It is the whole answer, bought cheaply.
Long data, wide dataTop: the memory needed to store C (D×D) and K (N×N), on a log scale, against a 16 GB laptop. Bottom: a tiny wide dataset, solved both ways.
Try: press gene study: C needs over a gigabyte, K a few kilobytes. Push D to 100,000 and C will not fit in the laptop at all. Then press new random data below: the non-zero eigenvalues of the 5×5 and 3×3 matrices always agree, and the recovered direction always matches.
A wide dataset you can hold in your hand N = 3 points, D = 5 columns, centred
The realization
K=N1XX⊤,Ku=λuw=∥X⊤u∥X⊤u
When columns outnumber rows, solve the small N×N problem instead. The non-zero eigenvalues are identical, and one multiplication by X⊤ — then a rescale — turns each small eigenvector into a principal direction.
Pause & predict
12,000 genes, 40 patients, centred. How much memory does C need in 8-byte numbers, and how many of its eigenvalues can be non-zero?
If you want the algebra · 1 proof, step by step
Prove it · the Gram trick, both ways
Claim. With C=N1X⊤X (D×D) and K=N1XX⊤ (N×N): (a) if Cw=λw with λ=0, then u=Xw satisfies Ku=λu and u=0; (b) if Ku=λu with λ=0, then C(X⊤u)=λ(X⊤u), and for a unit u, ∥X⊤u∥=Nλ.
1
(a) Multiply N1X⊤Xw=λw on the left by X and regroup:
N1XX⊤(Xw)that isKu=λ(Xw),=λu.u is not zero: ∥Xw∥2=Nw⊤Cw=Nλ>0.
So every non-zero eigenvalue of C is also an eigenvalue of K.
2
(b) Multiply N1XX⊤u=λu on the left by X⊤:
N1X⊤X(X⊤u)that isC(X⊤u)=λ(X⊤u),=λ(X⊤u).And every non-zero eigenvalue of K is one of C. The two lists of non-zero eigenvalues are identical.
3
Its length: ∥X⊤u∥2=u⊤XX⊤u=Nu⊤Ku=Nλu⊤u=Nλ. So w=X⊤u/Nλ is the unit direction.
∎Not normalising leaves a vector of length Nλ, and its "spread" comes out Nλ times too big. Rank: X has N rows adding to 0, so rankX≤N−1 and at most N−1 eigenvalues are non-zero.
In one sentence: when D≫N, eigen-split the small N×N Gram matrix instead — same non-zero eigenvalues — and turn each u into a direction with w=X⊤u/∥X⊤u∥.
14
The recipe, and the traps
Imagine this
Dosa batter has a recipe: soak, grind, ferment, cook. Skip a step and you still get something on the tawa — just not a dosa.
PCA has a recipe too. Each step is there for a reason, and each skipped step has a way of going quietly wrong.
Everything so far fits in four steps, plus an optional fifth:
Centre. Subtract each column's mean μd. Now every column averages to zero.
Standardise. Divide each column by its standard deviation σd (the square root of its spread). Now every column has spread 1 and no units.
Eigen-split. Build C=N1X⊤X, find its eigenvalues and eigenvectors, make each eigenvector length 1, and sort biggest first. Keep the top M as the columns of W.
Project.Z=XW. You started with D columns and now have M. That one multiplication is the dimension reduction.
(optional)Undo. To see a rebuilt point in the original units, undo steps 2 and 1 in reverse order: x=x~σd+μd.
A new point (a fresh customer, a test row) goes through the same steps with the training μ, σ and W. Never its own — one point has no spread — and never the test set's, which quietly leaks the test data into the model.
Try it. Training means μ=(4,10), standard deviations σ=(2,5), kept direction w1=(0.6,0.8), dropped direction w2=(−0.8,0.6). A new point (6,20) arrives.
Error: (1−1.32)2+(2−1.76)2=0.1024+0.0576=0.16. And along the dropped direction, z2=−0.8+1.2=0.4, so z22=0.16. The same, as §9 promised.
The traps
1 · Units decide the answer. PCA chases spread, and spread depends on units. Measure height in metres and weight in kilograms: weight's numbers are simply bigger, so its spread is about 8,600 times larger. The raw PC1 then puts a loading of 1.00 on weight and 0.01 on height — it is just the weight column. After standardising, both columns compete fairly and the loadings come out 0.71 and 0.71. (If all columns share one unit and their spreads are real information, centre only. Decide on purpose.)
2 · PCA is blind to y. It ranks directions by spread in x, and it has no idea whether that spread has anything to do with what you want to predict. It can rank them exactly backwards. In photos, the biggest spread is often the lighting, not the face. In gene data it is often which machine or batch ran the test. If you need the target kept, use a method that looks at y (such as partial least squares or linear discriminant analysis) instead of, or alongside, PCA.
3 · Outliers pull the components. Spread adds up squared distances, so one far-away point counts enormously. One mistyped value can swing PC1 toward itself. Look at the data first.
4 · Signs are arbitrary.−w is as good as w. Read patterns, not signs.
5 · Straight lines only. Every component is a straight mix of the columns. Data on a curve or a spiral needs several components to describe one curved direction. (Curved cousins exist — kernel PCA, t-SNE, UMAP — but that is another story.)
The recipe, step by step — and two trapsOne cloud of points, taken through the recipe with an animated move between every step. Then the unit trap and the target PCA cannot see.
Try: step through (a) to (f). Then on the unit trap, switch standardising off and on: PC1 swings from "all weight" to an equal mix. On blind to y, compare the two small plots — the component PCA would keep says nothing about y.
The realization
centre→standardise→eigen-split→project
Fit μ, σ and W once, on training data, and reuse them for everything new. And remember what PCA cannot see: units nobody told it about, the target y, and curves.
Pause & predict
A second new point (8,5) arrives for the same fitted PCA (μ=(4,10), σ=(2,5), w1=(0.6,0.8)). What is its score z?
In one sentence: centre, standardise, eigen-split and project with numbers fitted once on training data — and never forget that PCA is blind to units you did not fix, to the target, and to curves.
15
One example, start to finish
Imagine this
You have seen every part of the engine on its own. Now take the car out for a full drive — from the five raw points to their one-number summary, with every check along the way.
The data:(1,2),(4,5),(7,8),(8,4),(10,6). Reduce it from two numbers per point to one.
Step 1 · Centre. The mean is (6,5). Subtract it:
X=−5−2124−303−11(each column adds to 0✓)
We skip standardising: both columns are in the same units with similar spreads.
Two instant checks: 12+2=14=tr(C) ✓ and 12×2=24=detC ✓. Shares: 12/14=85.71% and 2/14=14.29%.
Step 4 · Eigenvectors, then length 1. For λ1=12: −2a+4b=0, so a=2b: the direction (2,1), length 5. For λ2=2: 8a+4b=0, so b=−2a: the direction (1,−2).
w1=51[21]≈[0.8940.447],w2=51[1−2].
Check: w1⊤w2=51(2−2)=0 ✓, and both have length 1 ✓.
Step 5 · Project. One dot product per row, zi=w1⊤xi:
Their spread is λ1: 51⋅5169+16+25+9+81=25300=12 ✓.
The dropped direction holds the rest: scores 51(1,−2,−5,4,2), spread 2550=2=λ2, and 12+2=14 ✓. Nothing went missing.
Now run it yourself — on these points, on the four points of Practice Problem 1, on the nine-point example from the slides, or on any points you drag around.
A PCA calculator that shows its workPick a dataset, drag any point, or type your own. Every step of §15 is redone live, with its checks.
Try: start with the five points and check every card against the page above. Then load the slides' nine points: λ1≈10.103 and w1≈(0.088,0.996). Then drag one point far away and watch one outlier drag PC1 toward itself.
drag the points
The realization
Mean → centre → C=N1X⊤X → det(C−λI)=0 → eigenvectors of length 1 → scores. And three free checks at the end: ∑λ=trC, ∏λ=detC, and "spread of the scores =λ1".
Pause & predict
A classmate gets eigenvalues 13 and 1 for C=[10444]. Which quick check catches the mistake?
In one sentence: centre, build C, solve the quadratic, make the eigenvectors length 1, project — and let the trace, the determinant and the spread of the scores check your work for free.
16
What to carry forward
One question ran through this whole unit: from which direction does the data look most spread out? It turned into a matrix, then a leash, then an eigenvector — and then it showed up three more times, wearing different clothes. Here is the whole unit on one card.
Part
What to remember
The problem
maxww⊤Cw subject to w⊤w=1 — only the direction matters, never the length
The derivation, in six lines
① z=Xw ② N1z⊤z=w⊤Cw ③ L=w⊤Cw−λ(w⊤w−1) ④ 2Cw−2λw=0 ⑤ Cw=λw ⑥ w⊤Cw=λ
The five facts
directions are eigenvectors, Cwd=λdwd · spread along each is λd · trC=∑λd · Cov(Z)=W⊤CW=Λ · λd=σd2/N
The recipe
centre · standardise · C=N1X⊤X, eigen-split, length 1, sort · keep M for your target share · Z=XW; new points use the training μ,σ,W
The six traps
dividing by N−1 · not making eigenvectors length 1 · not centring · standardising new data with its own μ,σ · expecting WW⊤=I (only W⊤W=I) · assuming the top component predicts y
When things get big
D≥5: no formula exists, so iterate · only the top one: xk+1=Cxk/∥Cxk∥ · D≫N: use K=N1XX⊤, then w=X⊤u/∥X⊤u∥ · best rank-M copy: UMΣMVM⊤
Three views, one answer
most spread kept · least rebuild error · best truncated SVD — all the top eigenvectors of C
The one thing to remember
Ask a geometric wish, put it on a leash, and the answer is an eigenvector.
"Most spread" became w⊤Cw. The leash w⊤w=1 became a fine. The fine became the eigenvalue, and the eigenvalue became the spread. Everything else — the budget, the rebuild error, the uncorrelated scores, the SVD, the Gram trick — is that one idea seen from another side.
Where this goes next. Unit 13 is about support vector machines. It makes the same move you just made: it takes a geometric wish — the widest possible street between two groups of points — and turns it into a constrained optimisation with fines. You already met a two-point version at the end of Unit 11. And when Unit 13 solves the problem from the fines' side, the data shows up only through dot products between points: a Gram matrix, just like the K of §13.
In one sentence: PCA turns "which way does the data spread most?" into "which eigenvector of C has the biggest eigenvalue?", and every other view of it — budget, rebuild error, uncorrelated scores, SVD — lands on the same answer.
17
Practice arena — twelve problems, solved in full
Twelve problems, each a different shape: raw data all the way to scores, a derivation with three faults to find, a new point pushed through a fitted model, a 3×3 matrix read by its pattern of zeros, data far wider than it is tall, a spread budget, singular values turned into components — then the nine-point example from the slides, two passes of power iteration, a question asked backwards, a loadings audit, and the Gram trick on real numbers. Every number is machine-verified.
Many books write Σ for the covariance matrix and α for a direction, and call the first score Y1=α⊤X. They are exactly our C, w and z1. Three habits do most of the work. Check as you go: centred columns add to zero, ∑λ=trC, ∏λ=detC. Always make eigenvectors length 1 before you use them. And divide by N.
Problem 1easy
Four observations on two variables: (2,3),(4,7),(6,5),(8,9). (a) Find the mean, write the centred data matrix, and build the covariance matrix (divide by N). (b) Find its eigenvalues and unit eigenvectors. (c) Find the first principal component score of each observation, check that their spread equals λ1, and give the share of the total spread that the first component keeps.
What this tests. The full computation from raw numbers to scores. How to attack it. Always the same five moves: mean → centre → N1X⊤X → characteristic polynomial → length 1. Check the centred columns add to zero before going on; check the eigenvalues with the trace and the determinant.
Show the full solution
(a) Mean and centring.μ1=42+4+6+8=5, μ2=43+7+5+9=6. Subtract (5,6) from every row:
X=−3−113−31−13columns add to 0✓
(a) Covariance.∑x12=9+1+1+9=20, ∑x22=20, ∑x1x2=9−1−1+9=16. Divide by N=4:
C=41[20161620]=[5445].
(b) Eigenvalues.det(C−λI)=(5−λ)2−16=0⇒5−λ=±4⇒λ1=9,λ2=1.
Checks: 9+1=10=trC ✓ and 9×1=9=25−16=detC ✓.
(b) Eigenvectors. For λ1=9: −4a+4b=0, so a=b, the direction (1,1) of length 2. For λ2=1: 4a+4b=0, so b=−a.
w1=21[11],w2=21[1−1],w1⊤w2=21(1−1)=0✓
(c) Scores.z=21(x1+x2) on each centred row:
2−6=−32≈−4.243,20=0,0,26=32≈4.243.
They add to zero, so their spread is the mean of their squares: 418+0+0+18=9=λ1 ✓. Share: 9+19=90%.
answers at a glance: μ=(5,6); C=[5445]; λ=9,1; w1=21(1,1), w2=21(1,−1); scores −4.243,0,0,4.243; spread 9; share 90%.
Problem 2medium
A student finds the first principal component of C=[5228] with a Lagrange multiplier. Their complete attempt:
Maximise w⊤Cw subject to w⊤w=1.
L(w,λ)=w⊤Cw−λ(w⊤w−1).
∂L/∂w=2Cw−λw=0, so Cw=21λw.
det(C−λI)=λ2−13λ+36=0, so λ=9 and λ=4.
For the larger root, (C−9I)w=0 gives w=(1,2), so z1=x1+2x2.
The spread of z1 is 9, because the maximum spread is the largest eigenvalue.
Exactly three lines are faulty. (a) Name them and say in one sentence each what is wrong. (b) Redo the derivation correctly from the first faulty line, and give the correct z1 and its spread. (c) Compute the spread of the student's x1+2x2 directly from C, and state the general rule for an eigenvector that was not made length 1.
What this tests. Knowing the six-line derivation well enough to mark someone else's. How to attack it. At each line ask three questions: is the rule written as "something =0"? is every derivative right? does the final vector have length 1? A line that survives all three is almost certainly fine.
Show the full solution
(a) The three faults. Lines 1, 2 and 4 are correct.
Line 3: the derivative of w⊤w is 2w, not w. The second term must be −2λw. As written, the multiplier would be twice the eigenvalue.
Line 5:(1,2) is the right direction but has length 5; the derivation assumed length 1.
Line 6: with the w of line 5, the spread is not 9. "Spread =λ" holds only for a unit vector.
(b) Corrected. Both terms of L are quadratic forms:
∂w∂L=2Cw−2λw=0⇒Cw=λw.
Line 4 stands: (5−λ)(8−λ)−4=λ2−13λ+36=0, so λ=213±5: λ1=9, λ2=4. Checks: 9+4=13=trC ✓, 9×4=36=40−4=detC ✓.
(b) The direction. For λ1=9: −4w1+2w2=0, so w2=2w1: direction (1,2), length 5.
w1=51[12],z1=5x1+2x2,spread=λ1=9.
For completeness, λ2=4 gives w2=51(−2,1), and w1⊤w2=51(−2+2)=0 ✓. The first component keeps 9/13≈69.2%.
(c) The student's spread.Var(x1+2x2)=Var(x1)+4Var(x2)+4Cov(x1,x2)=5+32+8=45.
Five times the claimed 9. In general, if Cw=λw then w⊤Cw=λ∥w∥2. Here ∥w∥2=5, and 5×9=45.
answers at a glance: faulty lines 3, 5, 6; Cw=λw; λ=9,4; w1=51(1,2); z1=(x1+2x2)/5 with spread 9 (69.2%); Var(x1+2x2)=45=λ∥w∥2.
Problem 3easy
A PCA is fitted on a two-variable training set with means μ=(4,10) and standard deviations σ=(2,5). On the standardised data the kept direction is w1=(3/5,4/5) and the dropped one is w2=(−4/5,3/5). A new observation x∗=(6,20) arrives. (a) Standardise it, saying which mean and standard deviation you use and why. (b) Find its score z∗ and its rebuild x~∗=z∗w1 (standardised scale). (c) Find the squared rebuild error and check that it equals z22. (d) Undo the standardising to give the rebuilt point in the original units, and its squared error there. Is it still z22?
What this tests. Using a fitted PCA on new data, and where the error goes. How to attack it. The only idea is that μ, σ and W come from training. After that it is arithmetic. Get the error once by subtraction and confirm it with z22.
Show the full solution
(a) Standardise with the training numbers. One point has no mean or spread of its own, and using test statistics would leak the test data into the model:
xstd∗=(26−4,520−10)=(1,2).
(b) Score and rebuild.z∗x~∗=53(1)+54(2)=511=2.2,=2.2(0.6,0.8)=(1.32,1.76).
Close to (1,2), but not equal: we kept one of two directions.
(c) The error.r∥r∥2=(1−1.32,2−1.76)=(−0.32,0.24),=0.1024+0.0576=0.16.
Along the dropped direction: z2=−54(1)+53(2)=52=0.4, and z22=0.16 ✓. Pythagoras in the basis {w1,w2}, which is orthonormal: −2512+2512=0, and both lengths are 1.
(d) Back to original units. Undo in reverse order — multiply by σ, then add μ:
x~orig∗=(1.32×2+4,1.76×5+10)=(6.64,18.8).
The error there is (6−6.64)2+(20−18.8)2=0.4096+1.44=1.8496. That is not0.16: undoing the standardising stretches the two axes by different amounts (2 and 5), so Pythagoras in the standardised basis no longer gives the raw error. The clean "error =z22" lives on the scale where the PCA was fitted.
answers at a glance: (a) (1,2), using the training μ,σ; (b) z∗=2.2, x~∗=(1.32,1.76); (c) error 0.16=z22 with z2=0.4; (d) (6.64,18.8), squared error 1.8496 — not z22.
Problem 4medium
Three variables have covariance matrix C=420240003. (a) Without expanding the full cubic, say what the zeros tell you about x3, and write down all three eigenvalues. Check them against trC and detC. (b) Find the three unit eigenvectors and confirm they meet at right angles. (c) Write z1 and its spread. Then show that keeping z1 and z2 rebuilds x3 exactly but not x1,x2; name what is lost and check that its spread is λ3.
What this tests. Reading structure before grinding. How to attack it. A variable uncorrelated with all the others splits off: its variance is an eigenvalue, and its axis is an eigenvector. That turns a cubic into a quadratic plus a freebie.
Show the full solution
(a) The pattern of zeros.Cov(x3,x1)=Cov(x3,x2)=0: x3 moves independently of the other two. So C splits into blocks, A=[4224] and [3], and its eigenvalues are the blocks' eigenvalues pooled. The 1×1 block gives 3. For A: (4−λ)2−4=0⇒4−λ=±2⇒λ=6,2.
λ1=6,λ2=3,λ3=2.
Checks: 6+3+2=11=4+4+3 ✓; 6×3×2=36=3×(16−4)=detC ✓.
(b) Eigenvectors. For 6: −2a+2b=0⇒a=b. For 3: the x3 axis itself. For 2: 2a+2b=0⇒b=−a.
w1=21110,w2=001,w3=211−10.w1⊤w3=21(1−1)=0, and w2 has zeros where the others do not, so all three pairs meet at right angles. Spot check: Cw1=21(6,6,0)=6w1 ✓.
(c) Keep two.z1=2x1+x2 with spread λ1=6. With W=[w1w2], the flattener is
WW⊤=w1w1⊤+w2w2⊤=2121021210001,x~=(2x1+x2,2x1+x2,x3).
So x3 comes back exactly, while x1 and x2 are both replaced by their average.
(c) What is lost.x−x~=2x1−x2(1,−1,0), which lies along w3. The lost quantity is the difference x1−x2, with score z3=2x1−x2:
Var(z3)=2Varx1+Varx2−2Cov(x1,x2)=24+4−4=2=λ3✓
PCA kept the sum of the correlated pair and dropped their difference — the small, quiet part of how they move together. And z2 is simply x3: PCA only mixes variables that actually move together.
answers at a glance: x3 is uncorrelated with the others, so C is block-diagonal; λ=6,3,2; w1=21(1,1,0), w2=(0,0,1), w3=21(1,−1,0); z1=(x1+x2)/2, spread 6; keeping two loses x1−x2, spread 2=λ3.
Problem 5medium
A gene study records D=12,000 genes on N=40 tissue samples. The centred X is 40×12,000 and C=N1X⊤X. (a) Give the size of C and the memory it needs in 8-byte numbers, and explain why a direct eigen-split is impractical. (b) Show that if Cw=λw, then u=Xw satisfies Ku=λu with K=N1XX⊤. Give the size of K. (c) From an eigenvector u of K, recover the eigenvector of C, with the rescaling it needs. What is the largest possible number of non-zero eigenvalues of C?
What this tests. What changes when there are more columns than rows. How to attack it. Sizes first: the covariance matrix is always (features) × (features). The derivation is one move: multiply the eigen-equation on the left by X and regroup. A proportionality is not an answer until you rescale, and centring costs one dimension.
Show the full solution
(a) Size.C is 12,000×12,000=1.44×108 entries.
1.44×108×8=1.152×109bytes≈1.152GB.
Storage is the smaller problem. An eigen-split costs about D3=1.728×1012 operations — hours of work to find structure in only 40 samples.
(b) The small problem. Multiply N1X⊤Xw=λw on the left by X:
N1XX⊤(Xw)=λ(Xw)⟹Ku=λu,u=Xw.K is N×N=40×40: 1,600 entries instead of 1.44×108, and the eigenvalue λ is the same.
(c) Back to genes. Multiply Ku=λu on the left by X⊤:
N1X⊤X(X⊤u)=λ(X⊤u)⟹C(X⊤u)=λ(X⊤u),w=∥X⊤u∥X⊤u.
Count: rankX≤min(N,D)=40, and centring makes the 40 rows add to zero, so rankC≤N−1=39. At most 39 of the 12,000 eigenvalues are non-zero, and K holds all of them.
answers at a glance: C is 12,000×12,000, ≈1.152 GB, eigen-split ∼1.7×1012 operations; K=N1XX⊤ is 40×40 with the same λ; w=X⊤u/∥X⊤u∥; at most 39 non-zero eigenvalues.
Problem 6easy
The covariance matrix of a five-variable dataset has eigenvalues 4.5,2.1,0.9,0.4,0.1. (a) Give the total spread and trC. (b) Find the share kept by the first two components, and the smallest number of components that keeps at least 90%. (c) With W holding all five unit eigenvectors and Z=XW, show that Cov(Z) is diagonal and name its diagonal. What does that say about the components?
What this tests. Eigenvalues as a spread budget, and why components never repeat each other. How to attack it. (a) is the trace identity — one line. In (b) build the running total once and read both answers off it. (c) is three lines using CW=WΛ and W⊤W=I.
Show the full solution
(a) The budget. Turning the axes never changes the total spread:
trC=d∑λd=4.5+2.1+0.9+0.4+0.1=8.0.
(b) Shares.
component
1
2
3
4
5
λd
4.5
2.1
0.9
0.4
0.1
share
56.25 %
26.25 %
11.25 %
5.00 %
1.25 %
running total
56.25 %
82.50 %
93.75 %
98.75 %
100 %
The first two keep 6.6/8.0=82.5%. Two fall short of 90%; three reach 93.75%. So M=3.
(c) Uncorrelated.Z is centred because X is, so
Cov(Z)=N1(XW)⊤(XW)=W⊤CW=W⊤WΛ=Λ=diag(4.5,2.1,0.9,0.4,0.1).
Every off-diagonal entry is zero: no two components move together. The diagonal says once more that the spread of component d is λd. In practice the scores can go straight into a regression with no twin-column trouble.
answers at a glance: total =trC=8.0; first two keep 82.5%; M=3 (93.75%); Cov(Z)=diag(4.5,2.1,0.9,0.4,0.1) — uncorrelated components, each with spread λd.
Problem 7medium
A centred data matrix has N=100 rows, D=4 columns and singular values 20,10,5,1. (a) Find the eigenvalues of C=N1X⊤X, and say where the principal directions sit in X=UΣV⊤. (b) Find the share kept by the first two components and the smallest number that keeps at least 95%. (c) Write the best rank-2 copy of X and its error in the spectral and the Frobenius norm.
What this tests. The SVD route and the best low-rank copy. How to attack it. One formula does (a): λ=σ2/N. The directions sit in the factor whose rows are indexed by features. (c) is Eckart–Young: cut the SVD, and the error is built from the singular values you dropped.
Show the full solution
(a) Eigenvalues.C=VNΣ2V⊤, so λd=σd2/N:
λ1=100400=4,λ2=100100=1,λ3=10025=0.25,λ4=1001=0.01.
The directions are the columns of V: with points in rows, V has D=4 rows and lives in feature space. (With points in columns, as on the slides, they would be the columns of U.)
(b) Shares. Total =4+1+0.25+0.01=5.26. The first alone keeps 4/5.26=76.05%, short of 95%. The first two keep 5/5.26=95.06%, which clears it. So M=2.
(c) Eckart–Young. Cut after two layers:
X~2=U2Σ2V2⊤=σ1u1v1⊤+σ2u2v2⊤=20u1v1⊤+10u2v2⊤.
The error is made only of the dropped layers:
∥X−X~2∥2=σ3=5,∥X−X~2∥F=52+12=26≈5.10.
No rank-2 matrix gets closer.
answers at a glance: λ=4,1,0.25,0.01; directions = columns of V; total 5.26; first two keep 95.06% (first alone 76.05%), so M=2; X~2=20u1v1⊤+10u2v2⊤; errors 5 (spectral) and 26≈5.10 (Frobenius).
Problem 8medium
The slides' nine-point example. Two variables are measured on nine items:
1
2
3
4
5
6
7
8
9
x1
1.11
1.21
1.36
1.49
1.63
1.68
1.83
1.88
1.95
x2
10
12
13
15
16
17
18
19
20
After centring, the covariance matrix (divided by N=9) is C=[0.07949880.88827160.888271610.0246914]. (a) Find the means and λ1. (b) Find the unit direction w1. (c) Find the scores of the first three items, and rebuild item 1 in the original units. (d)w1 is almost exactly the x2 axis. Is that because x2 matters more? What would standardising change?
What this tests. The recipe on unfriendly decimals, and the unit trap in a real example. How to attack it. Use the trace and determinant to get λ from the quadratic formula; build the eigenvector from one row of C−λI; keep five or six decimals until the end.
Show the full solution
(a) Means and λ1.μ1=914.14=1.571111 and μ2=9140=15.555556. For a 2×2 matrix, λ2−(trC)λ+detC=0:
trCdetCλ1=0.0794988+10.0246914=10.1041901,=0.0794988×10.0246914−0.88827162=0.0079241,=210.1041901+10.10419012−4(0.0079241)=10.103406.
The other root is λ2=10.1041901−10.103406=0.000784. The first component keeps 99.99%.
(b) The direction. The first row of (C−λ1I)w=0 reads (0.0794988−10.103406)a+0.8882716b=0, so b=11.284a. Take a=1: (1,11.2847), of length 11.3289. Divide:
w1≈(0.08827,0.99610).
(c) Scores. Centre each item, then z=0.08827x1+0.99610x2:
z1z2z3=0.08827(−0.461111)+0.99610(−5.555556)=−5.5746,=0.08827(−0.361111)+0.99610(−3.555556)=−3.5736,=0.08827(−0.211111)+0.99610(−2.555556)=−2.5642.
These match the slides' −5.57,−3.57,−2.56. Rebuild item 1: z1w1=(−0.4921,−5.5528); add the mean back: (1.0790,10.0027) — very close to the original (1.11,10).
(d) The unit trap, in the wild. No. x2's spread (10.02) is about 126 times x1's (0.0795), simply because of the units the two were written in. PCA chases spread, so it follows x2. The two columns are in fact almost perfectly related: their correlation is 0.8882716/0.0794988×10.0246914=0.9950. Standardise, and C becomes [10.99500.99501]: now w1=21(1,1), an equal mix, with λ1=1.9950 out of 2.
answers at a glance: μ=(1.571111,15.555556); λ1=10.1034 (λ2=0.000784, 99.99%); w1≈(0.0883,0.9961); scores −5.5746,−3.5736,−2.5642; item 1 rebuilt as (1.0790,10.0027); standardised: correlation 0.9950, w1=21(1,1), λ1=1.9950.
Problem 9medium
Run power iteration on C=[5228] from x0=(1,0). (a) Compute x1 and x2. (b) The true top direction is 51(1,2), at 63.43∘. Find the angle of each xk to it and show the tangent of that angle shrinks by λ2/λ1 each pass. (c) Estimate λ1 from x2 with x2⊤Cx2. (d) How many passes until the arrow is within 1∘ of the answer?
What this tests. Running the loop by hand, and the rate it closes in. How to attack it. You may skip the rescaling in the middle — it never changes the direction — and rescale only when you need an actual unit vector.
Show the full solution
(a) Two passes.Cx0=(5,2), length 29=5.3852, so x1=(0.92848,0.37139). Next, work with the unscaled vector: C(5,2)=(29,26), length 1517=38.9487, so x2=(0.74457,0.66755).
(b) The angle. The eigenvalues are 9 and 4, so λ2/λ1=4/9. The start is at 0∘, x1 at 21.80∘, x2 at 41.88∘. Measured from 63.43∘:
tan63.43∘tan(63.43∘−21.80∘)tan(63.43∘−41.88∘)=2,=tan41.63∘=0.8889=2×94,=tan21.56∘=0.3951=2×(94)2.
Exactly as the eigen-expansion predicts: the wrong part shrinks by 4/9 each pass.
(c) Estimate λ1.x2⊤Cx2=5(0.74457)2+2⋅2(0.74457)(0.66755)+8(0.66755)2=8.3250, about 7.5% below 9. Its error is (λ1−λ2)sin2θ2=5sin221.56∘=0.675, and because it goes with sin2θ it shrinks by about (4/9)2 per pass — twice as fast as the angle, on a log scale.
(d) Within 1∘. Need 2(4/9)k<tan1∘=0.017455, so k>ln(4/9)ln(0.0087275)=5.85. Six passes: the angle is then 0.88∘ (after five it is still 1.99∘).
answers at a glance: x1=(0.9285,0.3714), x2=(0.7446,0.6675); angles to w1: 63.43∘→41.63∘→21.56∘, tangents 2→0.889→0.395 (ratio 4/9); estimate λ1≈8.3250; 6 passes for 1∘.
Problem 10medium
A three-feature PCA has trC=10. Keeping only PC1, the average squared rebuild error over the training data is 4.0. Keeping PC1 and PC2, it is 1.0. (a) Recover λ1,λ2,λ3. (b) Give each component's share, and the smallest M that keeps at least 95%. (c) A new centred point has scores (z1,z2,z3)=(2,−1,0.5). Find its squared rebuild error when keeping one component, and when keeping two.
What this tests. The rebuild-error view, asked backwards. How to attack it. The average error is the sum of the dropped eigenvalues, and the trace is the sum of all of them. For a single point, the error is the sum of its squared dropped scores.
Show the full solution
(a) Read the eigenvalues off the errors. Keeping two, the error is the one dropped eigenvalue: λ3=1.0. Keeping one, it is the two dropped: λ2+λ3=4.0, so λ2=3.0. The trace gives the rest: λ1=10−4=6.0. Check the order: 6≥3≥1 ✓.
(b) Shares.6/10=60%, 3/10=30%, 1/10=10%. Running totals 60%,90%,100%. Two components keep 90%, short of 95%, so M=3 — which means keeping everything. A 95% target is too strict for this data.
(c) One point. The directions are orthonormal, so ∥x∥2=z12+z22+z32=4+1+0.25=5.25, and each kept direction keeps exactly its z2.
keep 1: z22+z32=1+0.25=1.25,keep 2: z32=0.25.
This point loses less than the average (4.0 and 1.0); a single point can land anywhere, only the average is fixed by the eigenvalues.
answers at a glance: λ=6,3,1; shares 60%,30%,10%; M=3 for 95%; the point loses 1.25 keeping one and 0.25 keeping two.
Problem 11medium
Three analysts each propose the first two loadings of a three-feature PCA:
A:a=31(2,1,2) and b=51(1,−2,0)
B:a=(0.6,0.8,0) and b=(0,0.6,0.8)
C:a=31(1,2,2) and b=(2,1,−2)
(a) Run the two checks on each pair and say which could really be principal components. (b) For the valid pair, find the third direction. (c) Repair the pair that fails only one check. (d) With the valid pair kept, find the scores and the squared rebuild error of the centred point x=(3,0,3), and confirm the error with the third direction.
What this tests. The two checks every set of loadings must pass, and using them. How to attack it. Length 1: add the squares. Right angles: the dot product must be zero. In three dimensions, the direction at right angles to two others is their cross product, rescaled.
Show the full solution
(a) The audit.
pair
∥a∥2
∥b∥2
a⊤b
verdict
A
94+1+4=1
51+4+0=1
352−2+0=0
valid
B
0.36+0.64=1
0.36+0.64=1
0+0.48+0=0.48
not at right angles
C
91+4+4=1
4+1+4=9
32+2−4=0
b has length 3
Only A passes both checks.
(b) The third direction. Cross product of (2,1,2) and (1,−2,0):
(1⋅0−2⋅(−2),2⋅1−2⋅0,2⋅(−2)−1⋅1)=(4,2,−5),length 45=35.
So c=351(4,2,−5). Check: (8+2−10)=0 and (4−4+0)=0 ✓.
(c) Repair C. Its only fault is the length of b. Divide by 3: b=31(2,1,−2), length 1, still at right angles to a. (B cannot be repaired by rescaling — the angle is wrong.)
(d) One point.z1=a⊤x=36+0+6=4 and z2=b⊤x=53−0+0=1.3416. Then
∥x∥2−z12−z22=18−16−1.8=0.2.
Along c: z3=3512+0−15=−51, and z32=0.2 ✓.
answers at a glance: only A is valid (B has a⊤b=0.48; C's b has length 3); third direction 351(4,2,−5); C repaired as 31(2,1,−2); for (3,0,3): z1=4, z2=1.3416, error 0.2=z32.
Problem 12hard
A tiny "wide" dataset: N=3 points, D=4 features, already centred:
X=10−12−1−101−11−21.
(a) Check that X is centred, and build K=N1XX⊤. (b) Find the eigenvalues of K and unit eigenvectors. (c) Recover the first principal direction w1=X⊤u1/∥X⊤u1∥ and check that ∥X⊤u1∥=Nλ1. (d) Confirm Cw1=λ1w1 directly with C=N1X⊤X, recover w2, and explain why C (4×4) has only two non-zero eigenvalues.
What this tests. The Gram trick on actual numbers. How to attack it.K's entries are dot products between rows. Its rows add to zero (because the data is centred), so (1,1,1) is always an eigenvector with eigenvalue 0. Guess the others from the pattern, then check.
Show the full solution
(a) Centred, and K. Column sums: 1+0−1=0, 2−1−1=0, 0+1−1=0, 1−2+1=0 ✓. The row dot products are r1⋅r1=6, r2⋅r2=6, r3⋅r3=4, r1⋅r2=−4, r1⋅r3=−2, r2⋅r3=−2:
K=316−4−2−46−2−2−24.
(b) Eigenvalues of K. Try the patterns. XX⊤(1,−1,0)=(10,−10,0), eigenvalue 10. XX⊤(1,1,−2)=(6,6,−12), eigenvalue 6. XX⊤(1,1,1)=(0,0,0), eigenvalue 0. Divide by N=3:
λ1=310≈3.3333,λ2=2,λ3=0,u1=21(1,−1,0),u2=61(1,1,−2).
Check: 310+2+0=316=trK ✓.
(c) Back to four features.X⊤(1,−1,0)=r1−r2=(1,3,−1,3), length 20. With the unit u1 this is 21(1,3,−1,3), length 10, and indeed Nλ1=3⋅310=10 ✓.
w1=251(1,3,−1,3)≈(0.2236,0.6708,−0.2236,0.6708).
(d) Direct check. The column dot products give
X⊤X=23103603102−303−36,X⊤X(1,3,−1,3)=(10,30,−10,30).
That is 10(1,3,−1,3), so Cw1=310w1 ✓ — the same λ1. Second direction: X⊤(1,1,−2)=r1+r2−2r3=(3,3,3,−3), length 6, so w2=21(1,1,1,−1), with λ2=2 and w1⊤w2=451(1+3−1−3)=0 ✓. Three centred points span at most N−1=2 dimensions, so the other two eigenvalues of C are 0: trC=32+6+2+6=316=310+2 ✓.
answers at a glance: K=316−4−2−46−2−2−24; λ=310,2,0; w1=251(1,3,−1,3), ∥X⊤u1∥=10=Nλ1; w2=21(1,1,1,−1); only N−1=2 non-zero eigenvalues.
PCA asked for the direction of widest spread; Unit 13 asks for the widest street between two groups of points — another geometric wish that becomes a constrained optimisation with a fine for every point. You already built a two-point version at the end of Unit 11; now it grows into a full classifier, and its dual sees the data only through a Gram matrix of dot products.