---
title: Principal component analysis
heading: Finding the directions of greatest variance as eigenvectors of the covariance, the variance each component explains, reconstruction error from discarded eigenvalues, the 2 × 2 case in closed form, whitening, choosing how many components to keep, and compression
eyebrow: S14 · Lesson 40 · Principal component analysis
xp: 50
---

::: hook
Sensor arrays, images and spectra often have hundreds of numbers per sample that move together: neighboring pixels, adjacent wavelengths, strain gauges on the same beam. Principal component analysis finds the few directions along which the data actually vary and describes each sample by its coordinates along them. It compresses, denoises, makes data visible in two dimensions, and decorrelates inputs before other methods see them. Underneath it's an eigenvalue problem on the covariance matrix, the same mathematics as the normal modes of A7 and the singular value decomposition.
:::

::: play
- The 2σ contour of a two-dimensional Gaussian with variances a and b and covariance c, with its two principal axes drawn at ±2 standard deviations.
- The long axis is the first principal component: the direction of greatest variance. Its eigenvalue is the variance along it.
- With c = 0 the axes line up with the coordinates; as c grows they rotate toward 45°, and when a = b any c puts them exactly at 45°.
:::

```sim plot
view: complex
range: 5
slider: a = 1.6..5 step 0.1 = 3
slider: b = 1.6..5 step 0.1 = 2
slider: c = 0.1..1.5 step 0.05 = 1
curve: 2*(sqrt(a)*cos(u) + j*(c/sqrt(a)*cos(u) + sqrt(b - c^2/a)*sin(u))) | over: u = 0..6.2832
curve: 2*sqrt((a + b)/2 + sqrt((a - b)^2/4 + c^2))*u*(c + j*((b - a)/2 + sqrt((a - b)^2/4 + c^2)))/abs(c + j*((b - a)/2 + sqrt((a - b)^2/4 + c^2))) | over: u = -1..1 | color: ch3
curve: 2*sqrt((a + b)/2 - sqrt((a - b)^2/4 + c^2))*u*j*(c + j*((b - a)/2 + sqrt((a - b)^2/4 + c^2)))/abs(c + j*((b - a)/2 + sqrt((a - b)^2/4 + c^2))) | over: u = -1..1 | dashed | color: ch4
readout: first eigenvalue = (a + b)/2 + sqrt((a - b)^2/4 + c^2) | digits: 4
readout: second eigenvalue = (a + b)/2 - sqrt((a - b)^2/4 + c^2) | digits: 4
readout: fraction explained by the first = ((a + b)/2 + sqrt((a - b)^2/4 + c^2))/(a + b) | digits: 4
readout: angle of the first, ° = atan(((b - a)/2 + sqrt((a - b)^2/4 + c^2))/c)*180/pi | digits: 4
```

::: predict
## Two measurements have variances 3 and 2 and covariance 1. What fraction of the total variance does the first principal component capture?

- [ ] 50%
- [ ] 60%
- [x] About 72%
- [ ] 100%

::: reveal
The covariance matrix [[3, 1], [1, 2]] has eigenvalues $(5 \pm \sqrt{5})/2$ = 3.618 and 1.382, and the total variance is its trace, 5. The first component captures 3.618/5 = 72.4%, more than the larger single coordinate's 60% because it leans into the correlation, at 31.7° from the first axis.
:::
:::

::: nameit
## The principal components

For centered data with covariance S, the variance along a unit vector **u** is $\mathbf{u}^TS\mathbf{u}$. It's largest along the eigenvector of S with the largest eigenvalue, and the variance there equals that eigenvalue. The next component is the best direction perpendicular to the first, and so on: the **principal components** are the eigenvectors $\mathbf{u}_i$ of S in order of eigenvalue $\lambda_1 \ge \lambda_2 \ge \ldots$, and each sample's coordinates are its projections $\mathbf{u}_i^T(\mathbf{x} - \bar{\mathbf{x}})$.

## Explained variance and reconstruction

The total variance is the trace, $\sum_i\lambda_i$. Keeping M components captures the fraction $\sum_{i \le M}\lambda_i/\sum_i\lambda_i$, and reconstructing from them leaves a mean squared error equal to the sum of the discarded eigenvalues. Equivalently, PCA is the best rank-M approximation, which is why it's computed from the singular value decomposition of the centered data matrix.

## The 2 × 2 case

For S = [[a, c], [c, b]]:

$$\lambda_\pm = \frac{a + b}{2} \pm\sqrt{\left(\frac{a - b}{2}\right)^2 + c^2}, \qquad \tan 2\theta = \frac{2c}{a - b}$$

## Whitening and choosing M

Dividing each projection by $\sqrt{\lambda_i}$ gives uncorrelated coordinates of unit variance (**whitening**). M is chosen from a target fraction of explained variance or from the "elbow" where eigenvalues level off into noise. Storing N samples of dimension D with M components takes NM coordinates plus MD for the components and D for the mean.
:::

::: example
## Work through the predict question's covariance: eigenvalues, the first component's direction, and the error of a one-component reconstruction.

::: solution
1. **Eigenvalues.**
   $$\begin{aligned} \lambda &= 2.5 \pm \sqrt{0.25 + 1} \\ &= 3.618,\ 1.382 \end{aligned}$$
2. **First component.**
   $$\begin{aligned} \theta &= \tfrac12\tan^{-1}(2/1) \\ &= 31.7^\circ \end{aligned}$$
   so $\mathbf{u}_1$ = (0.851, 0.526).
3. **Reconstruction error.** A one-component reconstruction leaves a mean squared error of 1.382, the discarded eigenvalue, against 2 or 3 for dropping a raw coordinate.

**Answer:** the eigenvalues are 3.618 and 1.382, the first component is (0.851, 0.526), at 31.7°, and a one-component reconstruction has a mean squared error of 1.382.
:::
:::

::: example
## A data set's eigenvalues are 5, 2, 1, 0.5, 0.3 and 0.2. How much variance do two and three components explain? And how much do 1000 images of 784 pixels shrink with 50 components?

::: solution
1. **Explained variance.** The total is 9:
   $$\begin{aligned} (5 + 2)/9 &= 77.8\% \\ (5 + 2 + 1)/9 &= 88.9\% \end{aligned}$$
   leaving reconstruction errors of 2.0 and 1.0.
2. **Compressed images.** Raw, they take 784,000 numbers; compressed,
   $$\begin{aligned} &1000 \times 50 + 50 \times 784 \\ &\quad + 784 \\ &= 89{,}984 \end{aligned}$$
3. **Ratio.**
   $$784{,}000/89{,}984 = 8.7$$

**Answer:** two components explain 77.8% of the variance and three 88.9%; the images shrink by a factor of 8.7.
:::
:::

::: example
## Data have covariance $\begin{bmatrix}4 & 2 \\ 2 & 3\end{bmatrix}$. Find the whitening scales, and the whitened length of the point (2, 1) measured from the mean.

::: solution
1. **Eigenvalues.**
   $$\begin{aligned} \lambda &= 3.5 \pm \sqrt{0.25 + 4} \\ &= 5.562,\ 1.438 \end{aligned}$$
2. **Whitening scales.** Whitening rotates onto the principal axes and scales them by $1/\sqrt\lambda$, giving unit variance in every direction:
   $$\begin{aligned} 1/\sqrt{5.562} &= 0.424 \\ 1/\sqrt{1.438} &= 0.834 \end{aligned}$$
3. **Whitened length.** It's the Mahalanobis distance $\sqrt{\mathbf x^T\Sigma^{-1}\mathbf x}$, with
   $$\Sigma^{-1} = \frac18\begin{bmatrix}3 & -2 \\ -2 & 4\end{bmatrix}$$
4. **For the point (2, 1).**
   $$\begin{aligned} \mathbf x^T\Sigma^{-1}\mathbf x &= (12 - 8 + 4)/8 \\ &= 1 \end{aligned}$$
   One standard deviation, though its plain length is 2.24.
5. **Why.** The point lies along the direction where the data spread most.

**Answer:** the whitening scales are 0.424 and 0.834, and the point (2, 1) has a whitened length of 1.
:::
:::

::: check
given: a = 2 | 5; b = 1 | 3; c = 0.5 | 1.5
answer: (a + b)/2 + sqrt((a - b)^2/4 + c^2)
tolerance: 0.5%

## A covariance matrix has variances {a} and {b} and covariance {c}. What's the variance along the first principal component?

::: right
Right. $\frac{a + b}{2} + \sqrt{(\frac{a - b}{2})^2 + c^2}$ = {answer}.
:::

::: misses
- [a + c] That's not an eigenvalue; solve the characteristic equation.
- [any] Not yet. The larger eigenvalue.
:::
:::

::: check
given: a = 3 | 6; b = 1 | 2; c = 0.5 | 1.5
answer: atan(2*c/(a - b))/2*180/pi
unit: °
tolerance: 0.5%

## For variances {a} and {b} with covariance {c}, at what angle from the first axis does the first principal component point?

::: right
Right. $\frac{1}{2}\tan^{-1}\frac{2c}{a - b}$ = {answer}°.
:::

::: misses
- [atan(2*c/(a - b))*180/pi] That's 2θ; halve it.
- [any] Not yet. $\tan 2\theta = 2c/(a - b)$.
:::
:::

::: check
given: p = 4 | 10; q = 2 | 3; r = 1 | 1.5; s = 0.2 | 0.5; M = 1 | 2 | 3
answer: (p*step(M - 1) + q*step(M - 2) + r*step(M - 3))/(p + q + r + s)
tolerance: 0.5%

## A data set's covariance has eigenvalues {p}, {q}, {r} and {s}. What fraction of the variance do the first {M} components explain?

::: right
Right. The kept eigenvalues over the trace: {answer}.
:::

::: misses
- [M/4] Components don't carry equal shares; weight them by their eigenvalues.
- [any] Not yet. Sum of kept eigenvalues over the sum of all.
:::
:::

::: check
given: p = 4 | 10; q = 2 | 3; r = 1 | 1.5; s = 0.2 | 0.5; M = 1 | 2 | 3
answer: q*step(1 - M) + r*step(2 - M) + s
tolerance: 0.5%

## With eigenvalues {p}, {q}, {r} and {s}, what mean squared reconstruction error does keeping {M} components leave?

::: right
Right. The sum of the discarded eigenvalues: {answer}.
:::

::: misses
- [any] Not yet. Add up the eigenvalues you didn't keep.
:::
:::

::: check
given: r = 0.5 | 0.8 | 0.95; f = 0.9 | 0.99
answer: ceil(ln(1 - f)/ln(r))
tolerance: 0.5%

## Eigenvalues fall geometrically, $\lambda_k \propto r^k$ with r = {r}, over a long series. How many components capture a fraction {f} of the variance?

::: right
Right. The first M capture $1 - r^M$, so M = ⌈ln(1 − f)/ln r⌉ = {answer}.
:::

::: misses
- [any] Not yet. Sum the geometric series.
:::
:::

::: check
given: N = 500 | 5000; D = 100 | 1000; M = 10 | 40
answer: N*D/(N*M + M*D + D)
tolerance: 0.5%

## {N} samples of dimension {D} are stored as {M} principal-component coordinates each, plus the components and the mean. By what factor does storage shrink?

::: right
Right. $ND/(NM + MD + D)$ = {answer}.
:::

::: misses
- [D/M] Include the cost of storing the components and the mean.
- [any] Not yet. Raw size over compressed size.
:::
:::

::: check
kind: parts
given: a = 2 | 5; b = 1 | 3; c = 0.5 | 1.2

## Two features have variances {a} and {b} and covariance {c}.

::: part
answer: (a + b)/2 - sqrt(((a - b)/2)^2 + c^2)
tolerance: 0.5%

### What is the variance along the second principal component?

::: misses
- [(a + b)/2 + sqrt(((a - b)/2)^2 + c^2)] That's the first.
- [any] $\frac{a + b}2 - \sqrt{(\frac{a - b}2)^2 + c^2}$.
:::
:::

::: part
answer: ((a + b)/2 + sqrt(((a - b)/2)^2 + c^2))/((a + b)/2 - sqrt(((a - b)/2)^2 + c^2))
tolerance: 0.5%

### What is the covariance's condition number?

::: misses
- [any] $\lambda_1/\lambda_2$.
:::
:::
:::

::: check
kind: derivation
vars: a = 0.5..10, b = 0.5..10, c = -0.4..0.4

## A two-feature covariance has variances a and b and covariance c.

::: step
answer: (a + b)/2 + sqrt(((a - b)/2)^2 + c^2)

### What is its first eigenvalue?
:::

::: step
answer: (a + b)/2 - sqrt(((a - b)/2)^2 + c^2)

### Its second?
:::

::: step
answer: ((a + b)/2 + sqrt(((a - b)/2)^2 + c^2))/(a + b)

### What fraction of the variance does the first component explain?
:::

::: right
Right. The eigenvalues sum to the trace a + b, so the total variance is unchanged by the rotation.
:::
:::

::: explain
## Why are the directions of greatest variance the eigenvectors of the covariance matrix?

::: model
The variance of the data projected onto a unit vector **u** is $\mathbf{u}^TS\mathbf{u}$, a quadratic form in **u**. Maximizing it subject to $\|\mathbf{u}\| = 1$ with a Lagrange multiplier gives $S\mathbf{u} = \lambda\mathbf{u}$, so every stationary direction is an eigenvector, and the variance along it is its eigenvalue. The largest eigenvalue gives the direction of greatest spread. Because S is symmetric its eigenvectors are orthogonal, so the components form a rotated coordinate system in which the data are uncorrelated, and the variances in the new coordinates, the eigenvalues, add up to the total.
:::
:::

::: practice

::: check
given: a = 0.5 | 8; b = 0.5 | 8; c = 0.1 | 2
answer: (a + b)/2 + sqrt((a - b)^2/4 + c^2)
tolerance: 0.5%

## First eigenvalue: a = {a}, b = {b}, c = {c}?

::: misses
- [any] $\frac{a + b}{2} + \sqrt{(\frac{a - b}{2})^2 + c^2}$.
:::
:::

::: check
given: r = 0.3 | 0.99; f = 0.8 | 0.999
answer: ceil(ln(1 - f)/ln(r))
tolerance: 0.5%

## Components for fraction {f}, ratio {r}?

::: misses
- [any] ⌈ln(1 − f)/ln r⌉.
:::
:::

::: check
given: N = 100 | 1e5; D = 50 | 4000; M = 5 | 100
answer: N*D/(N*M + M*D + D)
tolerance: 0.5%

## Compression: N = {N}, D = {D}, M = {M}?

::: misses
- [any] $ND/(NM + MD + D)$.
:::
:::
:::
