0510510maths →↑ physicsABCDEFA3, 4B5, 4C6, 5D6, 7E7, 7F9, 9anglevariancekept1Xc = X - X.mean(axis=0)2C = np.cov(Xc.T)3vals, vecs = np.linalg.eigh(C)4w = vecs[:, -1] # PC15z = Xc @ w6kept = vals[-1] / vals.sum()
Board: maths score (left to right) against physics score (up)Khaki pegs: the six students · cells in front: their numbersRose line and beads: PC1 and where each student lands · dashed blue: PC2The chart board holds six students: maths score across, physics score up. Their points lie along a slanted band, so the two numbers mostly say the same thing. PCA centres the data on the mean, turns a line through it and keeps the angle where the landing spots are most spread out: 45°, variance 7.6 of 8.0. That direction is PC1. Each student is replaced by one number, where they land on PC1; 95% of the variance survives. The six students are invented for the lesson. Both scores have the same variance, so PC1 lies at exactly 45° and keeps exactly 95% of the variance; real data is rarely this tidy.

Too many features

  1. Each student is a row of data with two features: a maths score and a physics score, out of 10. Two features means two dimensions, so each student is a point on a flat chart. Real data often has hundreds.

Finding PC1

In practice

What happens

;; step 1/9 · features
student  maths  physics
   A       3       4
   B       5       4
   C       6       5
   D       6       7
   E       7       7
   F       9       9

features = columns; 2 features = 2 dimensions

The six students are invented for the lesson. Both scores have the same variance, so PC1 lies at exactly 45° and keeps exactly 95% of the variance; real data is rarely this tidy. The line of greatest variance is also the line closest to the points: it makes the squared drop lines as short as possible, which is how Pearson first described it in 1901.