Principal component analysis

core 12 mindecompositionspcadimensionality-reduction

Builds on:Singular value decomposition

The idea

A centered cloud of points in dd dimensions usually does not fill all dd dimensions equally — it is elongated some ways, thin others. PCA finds the cloud's natural axes: the first principal component is the direction of maximal variance, the second is the most-variance direction perpendicular to the first, and so on. Keeping the top kk axes and dropping the rest is the best linear compression of the data in a sense made precise below.

The objective, and why eigenvectors appear. Project centered data onto a unit direction ww; the projected variance is w⊤Σww^\top \Sigma w where Σ\Sigma is the covariance matrix. Maximize it subject to ∥w∥=1\lVert w \rVert = 1 with a Lagrange multiplier:

max⁡w  w⊤Σw−λ(w⊤w−1)⟹Σw=λw\max_{w} \; w^\top \Sigma w - \lambda (w^\top w - 1) \quad \Longrightarrow \quad \Sigma w = \lambda w

The stationary points are eigenvectors of Σ\Sigma, and the variance achieved at an eigenvector is its eigenvalue (w⊤Σw=λw^\top \Sigma w = \lambda). So the top eigenvector wins, the second component is the next eigenvector, and orthogonality is not an extra assumption — it is delivered free by the spectral theorem, since Σ\Sigma is symmetric.

Why "maximize variance" is not arbitrary. Total variance ∑iλi\sum_i \lambda_i is fixed by the data. Each point splits, by Pythagoras, into its projection onto the kept subspace plus a perpendicular residual:

∑i≤kλi⏟variance kept  +  ∑i>kλi⏟mean squared reconstruction error  =  total variance\underbrace{\textstyle\sum_{i \le k} \lambda_i}_{\text{variance kept}} \; + \; \underbrace{\textstyle\sum_{i > k} \lambda_i}_{\text{mean squared reconstruction error}} \; = \; \text{total variance}

Maximizing kept variance and minimizing squared reconstruction error are the same optimization. PCA is exactly the kk-dimensional linear view that loses the least of the data — which is also why it coincides with the truncated SVD of the centered data matrix.

The recipe (and where each classic mistake hides):

  1. Center features with training-set means (without centering, PCA decomposes the second moment and the leading component may be dominated by the mean offset rather than variation around the mean).
  2. Standardize if features have incomparable units (skip → big-unit features hijack the components).
  3. Decompose: SVD of XcX_c in practice, Xc=USV⊤X_c = U S V^\top. Directions = columns of VV; variances λi=si2/(n−1)\lambda_i = s_i^2/(n-1); scores = USUS.
  4. Pick kk from the explained-variance ratio λi/∑jλj\lambda_i / \sum_j \lambda_j, an elbow, or downstream cross-validation.
  5. Transform new data with the same means, scales, and VV — refitting on test data is leakage.

See it happen in three dimensions — the plane below is fit live from the cloud's own covariance matrix, then every point collapses onto it:

Loading the interactive 3D PCA-projection visualization…

Worked example

Four points, already centered (mean is the origin): (3,3),  (−3,−3),  (1,−1),  (−1,1)(3,3), \; (-3,-3), \; (1,-1), \; (-1,1).

Covariance (divisor n−1=3n - 1 = 3):

Σ=13[20161620],e.g. Σ11=9+9+1+13=203\Sigma = \frac{1}{3}\begin{bmatrix} 20 & 16 \\ 16 & 20 \end{bmatrix}, \qquad \text{e.g. } \Sigma_{11} = \tfrac{9 + 9 + 1 + 1}{3} = \tfrac{20}{3}

Eigenpairs. By symmetry the eigenvectors are the diagonals:

w1=(1,1)2,λ1=20+163=12,w2=(1,−1)2,λ2=20−163=43.\begin{aligned} w_1 &= \frac{(1,1)}{\sqrt{2}}, & \lambda_1 &= \frac{20+16}{3} = 12, \\ w_2 &= \frac{(1,-1)}{\sqrt{2}}, & \lambda_2 &= \frac{20-16}{3} = \frac{4}{3}. \end{aligned}

The explained-variance ratio of PC1 is

1212+4/3=0.90.\frac{12}{12+4/3} = 0.90.

Scores on PC1 (z=x⋅w1z=x\cdot w_1):

z=(32, −32, 0, 0)≈(4.24,−4.24,0,0).z = \left(3\sqrt{2},\,-3\sqrt{2},\,0,\,0\right) \approx (4.24,-4.24,0,0).

The score variance checks the eigenvalue directly:

Var⁡(z)=18+18+0+03=12=λ1.\operatorname{Var}(z) = \frac{18+18+0+0}{3} = 12 = \lambda_1.

Reconstruction with k=1k = 1. Rebuild each point as z w1z \, w_1: (3,3)(3,3) and (−3,−3)(-3,-3) lie exactly on the PC1 line, so they reconstruct perfectly. (1,−1)(1,-1) and (−1,1)(-1,1) are perpendicular to PC1, so both collapse to the origin, each with squared error 22. Average the squared errors with the same n−1n - 1 divisor as the covariance: (0+0+2+2)/3=4/3=λ2(0 + 0 + 2 + 2)/3 = 4/3 = \lambda_2 — exactly the discarded eigenvalue, confirming kept variance (1212) plus reconstruction error (4/34/3) equals total variance (40/340/3).

The scaling trap in one line. Rescale the second feature by 100 (say, meters to centimeters) and redo this: the top component snaps to nearly (0,1)(0, 1) regardless of the correlation structure — units, not signal, chose the axes. That is why you standardize mixed-scale data first.

Cheat sheet

Formulas

Symptom-to-cause table

SymptomLikely causeFix
PC1 points at the data meanforgot to centercenter with train-set means
PC1 = the feature with biggest unitsno standardizationstandardize (correlation PCA)
Components flip sign between runsinherent sign ambiguityfix a sign convention; not a bug
Great explained variance, worse classifiervariance is not class signalsweep kk by CV; try LDA; consider no PCA
Test metrics too good pre-deployPCA fitted on all datafit on train split only
One weird componentoutliers steering squared errorrobust scaling / investigate outliers first

Gotchas