Principal Component Analysis

Minimising reconstruction error over unit directions is the same as maximising the variance of the projections, and both are solved by the top eigenvector of the covariance matrix. Repeating on the residuals gives an orthonormal basis of eigenvectors; the eigenvalues measure how much variance each direction keeps, which tells you how many to retain.

Machine Learning Techniques

The previous chapter ended with a precise goal: on centred data, find the unit vector ww whose line loses the least when every point is replaced by its projection. This chapter solves it, then follows the "repeat on the residuals" procedure to its end. The result is principal component analysis (PCA), one of the most widely used algorithms in data science.

From least error to a matrix problem

For a unit vector ww, the squared error of point xix_i is the squared length of its residual. Averaging over the data set,

f(w)=1n∑i=1n∥xi−(xi⊤w) w∥2.f(w) = \frac{1}{n}\sum_{i=1}^{n} \big\lVert x_i - (x_i^\top w)\,w \big\rVert^2 .

Expand one term, using w⊤w=1w^\top w = 1:

∥xi−(xi⊤w)w∥2=xi⊤xi−2(xi⊤w)2+(xi⊤w)2 w⊤w=∥xi∥2−(xi⊤w)2.\big\lVert x_i - (x_i^\top w)w \big\rVert^2 = x_i^\top x_i - 2(x_i^\top w)^2 + (x_i^\top w)^2\, w^\top w = \lVert x_i \rVert^2 - (x_i^\top w)^2 .

The first term does not depend on ww, so minimising ff is the same as maximising the other term:

max⁡∥w∥=1  1n∑i=1n(xi⊤w)2.\max_{\lVert w \rVert = 1} \; \frac{1}{n}\sum_{i=1}^{n} (x_i^\top w)^2 .

Now rewrite (xi⊤w)2(x_i^\top w)^2 as w⊤xi xi⊤ww^\top x_i\, x_i^\top w. Since ww does not depend on ii, it moves outside the sum:

1n∑i=1nw⊤xixi⊤w  =  w⊤(1n∑i=1nxixi⊤)w  =  w⊤C w.\frac{1}{n}\sum_{i=1}^{n} w^\top x_i x_i^\top w \;=\; w^\top \Big(\frac{1}{n}\sum_{i=1}^{n} x_i x_i^\top\Big) w \;=\; w^\top C\, w .

The d×dd \times d matrix

C=1n∑i=1nxixi⊤C = \frac{1}{n}\sum_{i=1}^{n} x_i x_i^\top

is the covariance matrix of the centred data. Entry (j,k)(j, k) is the average of feature jj times feature kk: the variances of the features on the diagonal and their covariances off it. So the best line is the solution of

max⁡∥w∥=1  w⊤C w.\max_{\lVert w \rVert = 1} \; w^\top C\, w .

A standard result of linear algebra (the Rayleigh quotient, a case of the Courant–Fischer min-max theorem) answers this immediately: the maximum is the largest eigenvalue λ1\lambda_1 of CC, reached when ww is the corresponding eigenvector. To see why, note that CC is symmetric, so it has an orthonormal basis of eigenvectors v1,…,vdv_1, \dots, v_d with eigenvalues λ1≥⋯≥λd\lambda_1 \ge \dots \ge \lambda_d. Write w=∑jajvjw = \sum_j a_j v_j with ∑jaj2=1\sum_j a_j^2 = 1; then w⊤Cw=∑jλjaj2w^\top C w = \sum_j \lambda_j a_j^2, a weighted average of the eigenvalues that is largest when all the weight sits on λ1\lambda_1.

The same line maximises variance

The quantity we maximise has a plain meaning. Project every centred point onto ww and collect the numbers x1⊤w,…,xn⊤wx_1^\top w, \dots, x_n^\top w. Their average is (1n∑ixi)⊤w=0\big(\tfrac{1}{n}\sum_i x_i\big)^\top w = 0, because the data is centred. Their variance is therefore just the average square:

Var⁡(x⊤w)=1n∑i=1n(xi⊤w)2=w⊤C w.\operatorname{Var}\big(x^\top w\big) = \frac{1}{n}\sum_{i=1}^{n} (x_i^\top w)^2 = w^\top C\, w .

So on centred data,

minimising reconstruction error = maximising the variance of the projections.

The two always add up to the same total, the average squared length of the points, 1n∑i∥xi∥2\tfrac{1}{n}\sum_i \lVert x_i \rVert^2, which is fixed by the data. Whatever variance the line keeps, it does not lose as error, and vice versa.

Why should we want the projections spread out? Because a compressed representation is only useful if it still tells points apart. Project onto a direction across a long thin cloud and every point lands near the origin: the coefficients crowd together and the points become indistinguishable. Project along the cloud and the coefficients stay spread out, preserving the differences between points. Variance is our measure of how much distinguishing information survives.

Try it yourself
Machine Learning Lab: PCA →
Turn the line and read the two numbers: variance kept and error lost always sum to the same total. Snap to the first principal component and see both extremes reached at once.

Repeating on the residuals

Take the residuals after the first line: xi′=xi−(xi⊤w1) w1x_i' = x_i - (x_i^\top w_1)\,w_1. Every residual is perpendicular to w1w_1 (we checked this in the last chapter), so all of them live in the subspace orthogonal to w1w_1. The best line for the residuals therefore also lies in that subspace: any component along w1w_1 would only add error. Hence w2⊥w1w_2 \perp w_1.

The same argument repeats. After kk rounds we have unit vectors w1,…,wkw_1, \dots, w_k that are mutually perpendicular, an orthonormal set. Working through the residuals shows that after round kk each point has had all its components along w1,…,wkw_1, \dots, w_k removed:

xi(k)=xi−∑j=1k(xi⊤wj) wj.x_i^{(k)} = x_i - \sum_{j=1}^{k} (x_i^\top w_j)\, w_j .

In dd dimensions there is room for only dd perpendicular directions, so after dd rounds every residual is zero, and each point is rebuilt exactly as

xi=∑j=1d(xi⊤wj) wj.x_i = \sum_{j=1}^{d} (x_i^\top w_j)\, w_j .

That is just a change of basis: from the standard axes to the new axes w1,…,wdw_1, \dots, w_d. Linear algebra identifies these axes for us. The direction found in round kk is the eigenvector of CC with the kk-th largest eigenvalue; the eigenvectors of a symmetric matrix are exactly an orthonormal basis. The wjw_j are called the principal components.

Where the compression happens

A change of basis on its own saves nothing. The saving comes from stopping early. If the residuals become zero after kk rounds, the data lies exactly in a kk-dimensional subspace, and each point needs only kk coefficients,

(xi⊤w1,  xi⊤w2,  …,  xi⊤wk)∈Rk,\big(x_i^\top w_1,\; x_i^\top w_2,\; \dots,\; x_i^\top w_k\big) \in \mathbb{R}^k ,

plus the kk shared directions. With n=100n = 100 points in d=100d = 100 dimensions that lie in a 3-dimensional subspace, we store 3×100+3×100=6003 \times 100 + 3 \times 100 = 600 numbers instead of 10,00010{,}000, and reconstruct everything exactly.

Real data never lies exactly in a subspace, so we also need to know when the remaining directions carry so little that we can drop them. The eigenvalues answer that. Since Cwk=λkwkC w_k = \lambda_k w_k and wk⊤wk=1w_k^\top w_k = 1,

λk=wk⊤C wk=1n∑i=1n(xi⊤wk)2,\lambda_k = w_k^\top C\, w_k = \frac{1}{n}\sum_{i=1}^{n} (x_i^\top w_k)^2 ,

the variance captured along the kk-th direction. Each eigenvalue is an average of squares, so it is never negative (the covariance matrix is positive semi-definite), and they decrease in order. A common rule of thumb keeps the smallest kk for which

λ1+λ2+⋯+λkλ1+λ2+⋯+λd  ≥  0.95,\frac{\lambda_1 + \lambda_2 + \dots + \lambda_k}{\lambda_1 + \lambda_2 + \dots + \lambda_d} \;\ge\; 0.95,

that is, the top kk directions explain 95% of the variance. Plotting the eigenvalues in order (a scree plot) often shows an elbow: a few large values (signal) followed by a long tail of small ones (mostly noise).

Left: an elongated 2D point cloud with the first principal component along its long axis and the second perpendicular to it. Right: a bar chart of decreasing eigenvalues with a cumulative line crossing 95 percent at k equals 3
PCA in one picture. The principal components are perpendicular axes ordered by the variance they capture (left); the eigenvalues, in order, show how many directions are worth keeping (right).

The algorithm

  1. Centre the data: subtract the mean μ\mu from every point.
  2. Form the covariance matrix C=1n∑ixixi⊤C = \tfrac{1}{n}\sum_i x_i x_i^\top.
  3. Compute its eigenvalues and eigenvectors, sorted from largest eigenvalue down.
  4. Choose kk, for example the smallest kk explaining 95% of the variance.
  5. Represent each point by its kk coefficients xi⊤w1,…,xi⊤wkx_i^\top w_1, \dots, x_i^\top w_k. To reconstruct, compute μ+∑j≤k(xi⊤wj) wj\mu + \sum_{j \le k} (x_i^\top w_j)\, w_j.

A worked picture: height and weight

Centre a set of heights and weights (in standard units) and suppose they rise together along the diagonal. The first principal component is then close to w1=12[1,1]⊤w_1 = \tfrac{1}{\sqrt 2}[1, 1]^\top, so each person's first coefficient is height+weight2\tfrac{\text{height} + \text{weight}}{\sqrt 2}: a measure of overall size. The second is perpendicular, w2=12[−1,1]⊤w_2 = \tfrac{1}{\sqrt 2}[-1, 1]^\top, giving weight−height2\tfrac{\text{weight} - \text{height}}{\sqrt 2}: whether someone is heavy for their height.

In the original axes, knowing a person's height tells you a lot about their weight. In the new axes, knowing someone's overall size tells you nothing about whether they are heavy for their height. The projections onto principal components are uncorrelated: in the new basis the covariance matrix is diagonal, with the eigenvalues on the diagonal. PCA has found new features, combinations of the old ones, that each carry information the others do not.

EasyPCALinear algebra

Show that the eigenvalues of a covariance matrix are never negative.

MediumPCA

Why is minimising reconstruction error equivalent to maximising projected variance, and why does centring matter for that equivalence?

MediumPCAModel selection

You run PCA on 50-dimensional sensor data and get eigenvalues 40, 25, 10, 2, 1, and then 22 equal values of 0.5 and 23 of 0. How many components would you keep, and what does the tail suggest?