---
title: Principal component analysis
heading: Finding the directions where data varies
eyebrow: A7 · Lesson 46 · Principal component analysis
xp: 40
---

::: hook
Ten sensors on a machine produce ten numbers per sample, but they rarely vary independently: a temperature rise moves all of them together, and a vibration moves a few in a fixed pattern. **Principal component analysis** finds those patterns. It rotates the data onto new axes ordered by how much the data spreads along each, so that the first few axes carry nearly all the variation and the rest are mostly noise. Underneath it's the spectral theorem applied to a covariance matrix, or equivalently, the SVD of the data.
:::

::: play
- The ellipse is the one-standard-deviation contour of two correlated readings, with spreads $s_1$, $s_2$ and correlation $r$.
- The arrows are the principal components: the ellipse's axes, each as long as the standard deviation along it.
- Raise $r$. The ellipse narrows along a diagonal and the first component's share of the variance grows: two correlated readings carry little more than one number's worth of information.
:::

```sim plot
view: complex
range: 3.5
axes: x₁, x₂
slider: sx = 0.5..3 step 0.1 = 2
slider: sy = 0.5..3 step 0.1 = 1
slider: r = 0.1..0.95 step 0.05 = 0.6
curve: sx*cos(u) + j*sy*(r*cos(u) + sqrt(1 - r^2)*sin(u)) | over: u = 0..2*pi | label: one standard deviation
arrow: sqrt(((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)))*((r*sx*sy) + j*(((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) - sx^2))/sqrt((r*sx*sy)^2 + (((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) - sx^2)^2) | label: PC 1
arrow: sqrt(((sx^2 + sy^2)/2 - sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)))*(-(((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) - sx^2) + j*(r*sx*sy))/sqrt((r*sx*sy)^2 + (((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) - sx^2)^2) | label: PC 2 | color: ch2
readout: variance along PC 1 = ((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) | digits: 4
readout: variance along PC 2 = ((sx^2 + sy^2)/2 - sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2)) | digits: 4
readout: fraction explained by PC 1 = ((sx^2 + sy^2)/2 + sqrt(((sx^2 - sy^2)/2)^2 + (r*sx*sy)^2))/(sx^2 + sy^2) | digits: 3
```

::: predict
## Two sensors read the same temperature, each with its own independent noise. Along which direction does their data spread the most?

- [x] $(1, 1)$: both readings rising and falling together
- [ ] $(1, -1)$: one up while the other goes down
- [ ] Along whichever sensor is noisier
- [ ] Equally in every direction

::: reveal
Along $(1, 1)$. The shared temperature moves both readings together, so the data stretches along the diagonal; the independent noise adds a little spread in every direction. The first principal component is the average of the two sensors, scaled by $\sqrt2$, and the second is their difference, which contains only noise.
:::
:::

::: nameit
## Covariance

Collect $N$ samples of $m$ readings as the rows of a matrix, and subtract each column's mean to get the centered data $X$ ($N \times m$). The **covariance matrix**

$$S = \frac{1}{N - 1}X^TX$$

is $m \times m$, symmetric and positive semidefinite. Its diagonal holds the variances, and $S_{ij}$ measures how readings $i$ and $j$ vary together.

## Principal components

By the spectral theorem, $S = Q\Lambda Q^T$ with orthonormal eigenvectors $\mathbf{q}_i$ and eigenvalues $\lambda_1 \ge \lambda_2 \ge \cdots \ge 0$. Then:
- $\mathbf{q}_1$ is the direction of greatest variance, and the variance along it is $\lambda_1$;
- each later $\mathbf{q}_i$ is the direction of greatest variance perpendicular to the earlier ones;
- the total variance $\text{trace}(S) = \sum\lambda_i$ is unchanged by the rotation, so $\frac{\lambda_i}{\sum\lambda_j}$ is the fraction of variance component $i$ explains.

## Through the SVD

If $X = U\Sigma V^T$, then $X^TX = V\Sigma^2V^T$, so the principal components are the right singular vectors $\mathbf{v}_i$ and $\lambda_i = \frac{\sigma_i^2}{N - 1}$. Libraries compute PCA this way, which avoids forming $X^TX$ and squaring the condition number.

## Using it

The **scores** of a sample are its coordinates along the components, $\mathbf{x}^T\mathbf{q}_i$. Keeping the first $k$ scores compresses each sample from $m$ numbers to $k$, and reconstructing from them removes the variance in the discarded directions, which is often mostly noise.
:::

::: example
## Find the principal components of the centered data $(-2, -1)$, $(-1, -1)$, $(1, 1)$, $(2, 1)$.

::: solution
1. **Covariance matrix.** $X^TX$ has entries $\sum x^2 = 10$, $\sum xy = 6$ and $\sum y^2 = 4$; dividing by $N - 1 = 3$:
   $$S = \begin{bmatrix}3.333 & 2\\2 & 1.333\end{bmatrix}$$
2. **Eigenvalues.** The trace is 4.667 and the determinant 0.444, so
   $$\begin{aligned} \lambda &= \frac{4.667 \pm \sqrt{4.667^2 - 4(0.444)}}{2} \\ &= 4.569 \text{ and } 0.097 \end{aligned}$$
3. **First component.** It's $(0.851, 0.526)$, about 32° above the $x$ axis.
4. **Variance explained.**
   $$\frac{4.569}{4.667} = 97.9\%$$
   The data is nearly one-dimensional.

**Answer:** the first principal component is $(0.851, 0.526)$, with variance 4.569 (97.9% of the total); the second has variance 0.097.
:::
:::

::: example
## Two sensors read a temperature that varies with standard deviation 2 °C, each with independent noise of 0.5 °C. Find the principal components.

::: solution
1. **Covariance matrix.** Each reading has variance $2^2 + 0.5^2 = 4.25$, and they share the temperature's variance, 4:
   $$S = \begin{bmatrix}4.25 & 4\\4 & 4.25\end{bmatrix}$$
2. **Eigenvalues.** They are $4.25 \pm 4$: 8.25 along $\frac{1}{\sqrt2}(1, 1)$ and 0.25 along $\frac{1}{\sqrt2}(1, -1)$.
3. **Variance explained.**
   $$\frac{8.25}{8.5} = 97.1\%$$
4. **Scores.** The first score is $\frac{x_1 + x_2}{\sqrt2}$, proportional to the average, which halves the noise variance; the second score is pure noise.

**Answer:** the first component is $\frac{1}{\sqrt2}(1, 1)$, with variance 8.25 (97.1%), and the second is $\frac{1}{\sqrt2}(1, -1)$, with variance 0.25, pure noise.
:::
:::

::: example
## A 10-channel recording has covariance eigenvalues 5.2, 3.1, 0.9, 0.3, 0.2, 0.1, 0.08, 0.06, 0.04 and 0.02. How many components keep 95% of the variance?

::: solution
1. **Total variance.** The eigenvalues add to 10.0.
2. **Running sums.** They are 5.2, 8.3, 9.2 and 9.5, so the first four components reach 95%.
3. **Storage.** Each sample can then be stored as 4 scores instead of 10 readings, plus the four 10-entry components once for the whole recording.
4. **What's dropped.** The other six directions together hold 0.5 of the variance.

**Answer:** four components keep 95% of the variance.
:::
:::

::: check
given: a = 3 | 5 | 8; b = 0.5 | 1
answer: a/(a + b)
tolerance: 0.5%

## A covariance matrix has eigenvalues {a} and {b}. What fraction of the variance does the first principal component explain?

::: right
Right. $\frac{\lambda_1}{\lambda_1 + \lambda_2}$ = {answer}.
:::

::: misses
- [a/b] Divide by the total variance.
- [sqrt(a)/(sqrt(a) + sqrt(b))] Variances add, standard deviations don't.
- [any] Not yet. The fraction is $\lambda_1$ over the trace.
:::
:::

::: check
given: v = 2 | 4; c = 0.5 | 1.5
answer: v + c
tolerance: 0.5%

## Two readings each have variance {v} and covariance {c}. What is the variance along the first principal component?

::: right
Right. $S = \begin{bmatrix}v & c\\c & v\end{bmatrix}$ has eigenvalues $v \pm c$; the larger is {answer}.
:::

::: misses
- [v] The correlation stretches the data along $(1, 1)$.
- [2*v + 2*c] That's the variance of the sum $x_1 + x_2$; the unit vector $\frac{1}{\sqrt2}(1, 1)$ halves it.
- [any] Not yet. Find the eigenvalues of the covariance matrix.
:::
:::

::: check
kind: parts
given: s = 1 | 2 | 3; n = 0.2 | 0.5

## Two sensors share a signal of standard deviation {s} and each add independent noise of standard deviation {n}.

::: part
answer: 2*s^2 + n^2
tolerance: 0.5%

### What is the variance along the first component?

::: misses
- [s^2 + n^2] That's one sensor's variance; the shared part adds along $(1, 1)$.
- [any] The eigenvalues of $\begin{bmatrix}s^2 + n^2 & s^2\\s^2 & s^2 + n^2\end{bmatrix}$.
:::
:::

::: part
answer: n^2
tolerance: 0.5%

### And along the second?

::: misses
- [any] The difference of the sensors cancels the signal.
:::
:::
:::

::: check
given: s = 10 | 25; N = 11 | 51
answer: s^2/(N - 1)
tolerance: 0.5%

## The centered data matrix of {N} samples has a largest singular value of {s}. What is the variance along the first principal component?

::: right
Right. $\lambda_1 = \frac{\sigma_1^2}{N - 1}$ = {answer}.
:::

::: misses
- [s/(N - 1)] Square the singular value.
- [s^2/N] With the sample mean removed, divide by $N - 1$.
- [any] Not yet. $X^TX = V\Sigma^2V^T$.
:::
:::

::: check
given: x = 1 | 3; y = 2 | 4
answer: (x + y)/sqrt(2)
tolerance: 0.5%

## The first principal component is $\frac{1}{\sqrt2}(1, 1)$. What is the score of the centered sample $(\given{x}, \given{y})$?

::: right
Right. The score is the dot product, {answer}.
:::

::: misses
- [x + y] Use the unit vector, with its $\frac{1}{\sqrt2}$.
- [(x + y)/2] That's the average, which is the score divided by $\sqrt2$.
- [any] Not yet. Dot the sample with $\mathbf{q}_1$.
:::
:::

::: check
kind: derivation
vars: a = 1..5, b = 0.1..1, c = -1..1

## Find the principal variances of $S = \begin{bmatrix}a & c\\c & b\end{bmatrix}$.

::: step
answer: a + b

### What is the total variance?
:::

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

### What is the larger eigenvalue?
:::

::: right
Right. $\lambda_{1,2} = \frac{a + b}{2} \pm \sqrt{\left(\frac{a - b}{2}\right)^2 + c^2}$: the covariance spreads them apart.
:::
:::

::: check
kind: python

## Two sensors record the same signal with different noise. Center the data in the starter, take its SVD, and set `lam` to the principal variances $\sigma_i^2/(N - 1)$, `frac` to the fraction the first explains and `pc1` to the first component.

```python starter
import numpy as np

t = np.linspace(0, 2 * np.pi, 200, endpoint=False)
s = 2 * np.sin(3 * t)
X = np.column_stack([s + 0.5 * np.sin(17 * t + 1), s + 0.5 * np.sin(29 * t + 2)])
lam = np.array([1.0, 1.0])
frac = 0.5
pc1 = np.array([1.0, 0.0])
print(lam, frac, pc1)
```

```python solution
import numpy as np

t = np.linspace(0, 2 * np.pi, 200, endpoint=False)
s = 2 * np.sin(3 * t)
X = np.column_stack([s + 0.5 * np.sin(17 * t + 1), s + 0.5 * np.sin(29 * t + 2)])
Xc = X - X.mean(axis=0)
u, sv, vt = np.linalg.svd(Xc, full_matrices=False)
lam = sv**2 / (len(X) - 1)
frac = lam[0] / lam.sum()
pc1 = vt[0]
print(lam, frac, pc1)
```

```python tests
import numpy as np
C = np.cov(X.T)
assert np.allclose(np.sort(lam), np.linalg.eigvalsh(C)), f"The variances should match the covariance matrix's eigenvalues; got {lam}."
assert np.allclose(np.abs(pc1), [2**-0.5, 2**-0.5], atol=0.01), f"The shared signal puts the first component along (1, 1)/sqrt(2); got {pc1}."
assert 0.96 < frac < 0.98, f"The first component should explain about 97% (4.125 of 4.25); got {frac}."
```

::: right
Right. The SVD of the centered data gives the same variances as the covariance matrix without ever forming it, and the first component is the sensors' average.
:::
:::

::: explain
## Why are the principal components perpendicular, and why does that matter for compression?

::: model
They're the eigenvectors of the covariance matrix, which is symmetric, and the spectral theorem says a symmetric matrix has perpendicular eigenvectors. In those coordinates the covariance matrix is diagonal, so the scores along different components are uncorrelated: each component carries information the others don't. That's what makes it safe to drop the last few. Since the rotation keeps lengths, the total variance is split exactly among the components, and dropping the small ones removes exactly their share, no more. Correlated readings, by contrast, can't be dropped one at a time without losing part of what the others share.
:::
:::

::: practice

::: check
given: a = 1..20; b = 0.01..1
answer: a/(a + b)
tolerance: 0.5%

## Fraction explained by the first component, with eigenvalues {a} and {b}?

::: misses
- [any] $\frac{\lambda_1}{\lambda_1 + \lambda_2}$.
:::
:::

::: check
given: v = 1..10; c = 0.1..0.9
answer: v + c
tolerance: 0.5%

## First principal variance for equal variances {v} and covariance {c}?

::: misses
- [any] $v + c$.
:::
:::
:::
