Principal Component Analysis

The chain from covariance to direction to projection.

5 lessons · 34 past questions · 99 marks in the papers collected here

Open the interactive lessons →Principal Component Analysis past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Centring and the covariance matrix
  2. Eigenvalues as variance
  3. The principal direction
  4. Projection and reconstruction error
  5. Properties of PCA and many features

1. Centring and the covariance matrix

Move the centre to zero, then measure how coordinates vary together.

how to describe the spread of a data set with one matrix

The question this lesson answers. How can one matrix describe the shape of a cloud of points?

Move the cloud to the origin

Where the cloud sits says nothing about its shape. Centre it first, then measure spread.

Mean and covariance

For points $x_1,\dots,x_n\in\mathbb R^d$, the mean is $\mu=\frac1n\sum x_i$. The covariance matrix is $$C=\frac1n\sum_{i=1}^n(x_i-\mu)(x_i-\mu)^T.$$ It is $d\times d$.

Why it works this way. Each term $(x-\mu)(x-\mu)^T$ records how pairs of coordinates move together. Averaging them gives variances on the diagonal and covariances elsewhere.

Read the entries: $C_{jj}$ is the variance of coordinate $j$. $C_{jk}$ is positive when coordinates $j$ and $k$ tend to be above their means together, negative when one is high while the other is low.

If the centred points are the rows of an $n\times d$ matrix $X$, then $C=\frac1nX^TX$. This shows at once that $C$ is symmetric and positive semidefinite: $w^TCw=\frac1n\lVert Xw\rVert^2\ge0$. So a matrix with a negative diagonal entry can never be a covariance matrix.

Divide by what? This course's questions use $\frac1n$. Statistics books often use $\frac1{n-1}$, the unbiased sample version. The two differ only by a constant factor, so the principal directions are identical; the eigenvalues are scaled. Use $\frac1n$ unless the question defines it otherwise.

Order of work: mean, centred points, then a small table with columns $a^2$, $b^2$, $ab$.

Worked example: Mean and covariance

Problem.

Points $(0,2),(2,0),(4,4)$. Find $\mu$ and $C$.

Idea.

Centre, then average products.

  1. $\mu=(2,2)$.
  2. Centred: $(-2,0),(0,-2),(2,2)$.
  3. $\sum a^2=8$, $\sum b^2=8$, $\sum ab=4$.
  4. Divide by 3.

Answer.

$C=\frac13\begin{bmatrix}8&4\\4&8\end{bmatrix}$.

Common mistake.

Using the raw points without subtracting the mean.

Worked example: Three features

Problem.

Points $(1,0,2),(3,2,0),(2,1,1)$. Find $C$ (divide by $3$).

Idea.

Centre, then average the products feature by feature.

  1. Mean $(2,1,1)$.
  2. Centred: $(-1,-1,1),;(1,1,-1),;(0,0,0)$.
  3. $C_{11}=\tfrac13(1+1+0)=\tfrac23$, and the other diagonals are $\tfrac23$ too.
  4. $C_{12}=\tfrac13(1+1)=\tfrac23$; $C_{13}=C_{23}=\tfrac13(-1-1)=-\tfrac23$.

Answer.

$C=\tfrac23\begin{bmatrix}1&1&-1\\1&1&-1\\-1&-1&1\end{bmatrix}$: rank $1$, because all centred points lie on one line.

Common mistake.

Making $C$ $3\times3$ from the three points instead of the three features.

Exam tip

The centred points must add to the zero vector. Check this before forming any products.

From the lecture notes: centring is compulsory

Skip the centring and the leading direction can point toward the mean of the data instead of along the direction of largest spread.

Worked example: Shifting the data

Problem.

Every point of a data set is moved by $(10,-7)$. What happens to the covariance matrix?

Idea.

The mean moves by the same amount.

  1. Each centred point is unchanged.
  2. So every product in $C$ is unchanged.

Answer.

It does not change.

Common mistake.

Adding the shift to the entries of $C$.

Memory line

Centre first, then average the outer products.

Method for any exam question

StepDo this
1Compute the mean.
2Subtract it from every point.
3Average the outer products.
4Check symmetry and non-negative diagonal.

2. Eigenvalues as variance

Each eigenvalue is the spread along its own axis.

what the eigenvalues of $C$ mean

The question this lesson answers. What do the eigenvalues of the covariance matrix measure?

Shadows of a cloud

Shine light on a cloud of points so that each point casts a shadow on a line. Turn the line. The shadows spread out most along the first principal direction, and that spread is $\lambda_1$.

Variance along a direction

$$\operatorname{Var}(w)=\frac1n\sum_i\big(w^T(x_i-\mu)\big)^2=w^TCw,\qquad\lVert w\rVert=1$$ Condition: $w$ must be a unit vector. If $w=v_j$ is a unit eigenvector, the variance is $\lambda_j$.

Why variance along $w$ equals $w^TCw$, on three points. Take the centred points $(2,0),(-1,1),(-1,-1)$, so $C=\begin{bmatrix}2&0\\0&2/3\end{bmatrix}$, and $w=(0.6,0.8)$. The projections $w^Tx_i$ are $1.2,\;0.2,\;-1.4$; their mean square is $(1.44+0.04+1.96)/3\approx1.147$. The matrix gives $0.36\cdot2+0.64\cdot\tfrac23\approx1.147$. The reason: $(w^Tx_i)^2=w^T(x_ix_i^T)w$, and averaging the middle matrices gives $C$. For a unit eigenvector, $w^TCw$ is its eigenvalue.

Because $C$ is symmetric, it has orthonormal eigenvectors $v_1,\dots,v_d$ with $\lambda_1\ge\lambda_2\ge\dots\ge\lambda_d\ge0$. For any unit $w$, $$\lambda_d\le w^TCw\le\lambda_1.$$ So the largest possible projected variance is $\lambda_1$.

The total variance is the trace: $\sum C_{jj}=\sum\lambda_j$. The share explained by the first $k$ components is $\dfrac{\lambda_1+\dots+\lambda_k}{\operatorname{tr}C}$.

For a $2\times2$ matrix $\begin{bmatrix}a&b\\b&a\end{bmatrix}$ the eigenvalues are $a+b$ and $a-b$, with eigenvectors $(1,1)$ and $(1,-1)$. This one pattern solves many questions. If $C$ has all entries equal to $c$ and size $d$, the eigenvalues are $dc$ once and 0 otherwise.

Worked example: Eigenvalues by pattern

Problem.

$C=\begin{bmatrix}6&2\\2&6\end{bmatrix}$. Find the share of the first component.

Idea.

Equal diagonal pattern.

  1. Eigenvalues $8$ and $4$.
  2. Share $8/12$.

Answer.

About 66.7%.

Common mistake.

Dividing 8 by 4.

Worked example: Variance along a given line

Problem.

With the same $C$, find the variance along the direction $(1,0)$ and along $(3,4)$.

Idea.

Normalise, then $w^TCw$.

  1. Along $(1,0)$: $C_{11}=6$.
  2. Unit vector $(0.6,0.8)$: $w^TCw=6(0.36)+4(0.48)+6(0.64)=7.92$.

Answer.

6 and 7.92, both between 4 and 8.

Common mistake.

Using $(3,4)$ without normalising, which gives 198.

Exam tip

Any variance you compute along a unit vector must lie between the smallest and largest eigenvalue. This catches most arithmetic slips.

From the lecture notes: choosing how many components

A common rule of thumb: take the smallest $k$ with $\dfrac{\lambda_1+\dots+\lambda_k}{\lambda_1+\dots+\lambda_d}\ge0.90$. Use the threshold the question gives if it gives one.

The recipe

StepDo thisCheck before moving on
1Make sure the direction has length 1.Divide by its length if needed.
2Compute $w^TCw$, or read $\lambda_j$ if $w$ is an eigenvector.The result is never negative.
3For a share, divide by the trace of $C$.All shares add to 1.
4For a number of components, add eigenvalues from the largest until the threshold is reached.Equal to the threshold counts as reaching it.

Why is the trace the total? The diagonal of $C$ holds the variance of each coordinate. The trace of a matrix equals the sum of its eigenvalues, so rotating to the principal directions moves variance between axes but never creates or destroys it.

Worked example: Two traps in one

Problem.

$C=\mathrm{diag}(4,1)$. Find the variance along $(3,4)$. Then, for eigenvalues $5,3,1,1$, find the fewest components that keep at least $90\%$.

Idea.

Normalise first; add eigenvalues in order.

  1. The unit vector is $w=(0.6,0.8)$.
  2. $w^TCw=4(0.36)+1(0.64)=2.08$.
  3. The total of $5,3,1,1$ is $10$.
  4. The running shares are $50\%$, $80\%$, $90\%$.

Answer.

Variance $2.08$; three components.

Common mistake.

Using $(3,4)$ unnormalised, which gives $52$, far above the largest eigenvalue 4.

Memory line

An eigenvalue is the variance along its eigenvector.

3. The principal direction

The top eigenvector, made into a unit vector.

choosing the axis of greatest spread

The question this lesson answers. Which single direction keeps the most information about the data?

The long axis

For a cloud shaped like a cigar, the line along its length shows the most spread.

Principal components

The first principal component is a unit eigenvector of $C$ for the largest eigenvalue. The second is a unit eigenvector for the next one, perpendicular to the first, and so on.

Why it works this way. $w^TCw$ is a weighted average of eigenvalues when $w$ has length 1, so it is largest when all the weight is on the largest one.

The sign is free. If $v$ is a principal direction, so is $-v$. The axis is the same line. An exam may offer either one. If it offers both $v$ and $-v$, both are mathematically correct.

Length matters in the strict definition: the vector should have length 1. When options include both $(1,1)$ and $(1,1)/\sqrt2$, choose the unit one.

Repeated top eigenvalue: if $\lambda_1=\lambda_2$, every unit vector in their plane is equally good. There is no single first direction.

Fast route for collinear data. If all centred points are multiples of one vector $d$, then $C$ is a multiple of $dd^T$, and the principal direction is $d/\lVert d\rVert$. You can read it from the data without forming $C$.

The first principal component line is not the regression line. PCA measures distance at right angles to the line; regression of $y$ on $x$ measures it vertically.

Worked example: From C to direction

Problem.

$C=\frac14\begin{bmatrix}10&-6\\-6&10\end{bmatrix}$. Find the first principal component.

Idea.

Equal diagonal pattern with negative $b$.

  1. Eigenvalues $4$ (for $(1,-1)$) and $1$ (for $(1,1)$).

Answer.

$(1,-1)/\sqrt2$, or its negative.

Common mistake.

Taking $(1,1)$ out of habit when $b$ is negative.

Worked example: Unequal diagonal

Problem.

$C=\begin{bmatrix}5&2\\2&2\end{bmatrix}$. Find the first principal component.

Idea.

Eigen-pairs.

  1. Trace 7, determinant 6: eigenvalues 6 and 1.
  2. $(C-6I)v=0$: $-v_1+2v_2=0$, so $v=(2,1)$.

Answer.

$(2,1)/\sqrt5$.

Common mistake.

Writing $(1,2)$, which swaps the components.

From the lecture notes: two problems, one answer

$$\min_{\lVert w\rVert=1}\frac1n\sum_i\lVert\tilde x_i-(\tilde x_i^Tw)\,w\rVert^2\quad\Longleftrightarrow\quad\max_{\lVert w\rVert=1}w^TCw$$ Here $\tilde x_i$ is the centred point $x_i-\mu$. By Pythagoras each squared error is $\lVert\tilde x_i\rVert^2-(\tilde x_i^Tw)^2$, and the first part does not depend on $w$. Both problems are solved by the top eigenvector of $C$.

Worked example: The widest direction, not the first

Problem.

Points $(\pm1,0)$ and $(0,\pm3)$. Which axis is the first principal direction?

Idea.

Compare the variances.

  1. The variance along $x$ is $0.5$.
  2. Along $y$ it is $4.5$.

Answer.

The $y$ axis.

Common mistake.

Choosing the first coordinate by habit.

Tips and tricks
  • Subtract the mean before forming the covariance matrix. Skipping this changes the direction.
  • For $\begin{bmatrix}a&b\\b&a\end{bmatrix}$ the eigenvectors are $(1,1)$ and $(1,-1)$ with eigenvalues $a+b$ and $a-b$.
  • Normalise to length 1 at the end. Either sign is correct, so compare options up to sign.
Memory line

Top eigenvalue, unit eigenvector.

Method for any exam question

StepDo this
1Find the largest eigenvalue.
2Take its eigenvector.
3Scale it to length 1.
4Remember that its negative is equally valid.

4. Projection and reconstruction error

Drop each point at right angles onto the line through the mean.

replacing each point by its nearest point on the principal line

The question this lesson answers. What is lost when a point is replaced by its shadow on a line?

Dropping a perpendicular

Stand at a data point and walk straight to the principal line, meeting it at a right angle. Where you land is the rebuilt point. The length of your walk is the error.

Projection onto one component

$$\tilde x_i=\mu+\big(w^T(x_i-\mu)\big)\,w,\qquad\lVert w\rVert=1$$ The number $z_i=w^T(x_i-\mu)$ is the score. The vector $\tilde x_i$ is the reconstructed point, in the original space.

Why it works this way. The kept part and the lost part are perpendicular, so their squared lengths add. Keeping more variance is the same as losing less.

Keep three objects apart, because questions use the word "projection" for any of them:

Object What it is
score $z_i$ one number, the coordinate along $w$
$z_iw$ the projection of the centred point
$\mu+z_iw$ the rebuilt point on the line through the mean

For options that list vectors near the data, the third is meant. Changing $w$ to $-w$ flips the sign of every score but leaves $z_iw$ and $\tilde x_i$ unchanged.

Reconstruction error with $k$ components, averaged over the points: $$J=\frac1n\sum_i\lVert x_i-\tilde x_i\rVert^2=\lambda_{k+1}+\dots+\lambda_d.$$ So it equals the dropped variance. If a question adds instead of averaging, the result is $n$ times larger.

A point already on the line does not move. If all data lie on one line, projection onto the first component returns the data themselves and the error is 0.

Worked example: Project and rebuild

Problem.

$\mu=(2,2)$, $w=(1,1)/\sqrt2$, $x=(4,2)$. Find $z$ and $\tilde x$.

Idea.

Centre, dot, rebuild.

  1. Centred $(2,0)$.
  2. $z=2/\sqrt2=\sqrt2$.
  3. $zw=(1,1)$, so $\tilde x=(3,3)$.

Answer.

$z=\sqrt2$, $\tilde x=(3,3)$.

Common mistake.

Forgetting to add the mean back.

Worked example: Error two ways

Problem.

Points $(0,2),(2,0),(4,4)$ with $C=\frac13\begin{bmatrix}8&4\\4&8\end{bmatrix}$. Find the average error with one component.

Idea.

It equals $\lambda_2$.

  1. Eigenvalues $4$ and $4/3$.
  2. Check: centred points $(-2,0),(0,-2),(2,2)$; distances squared from the line $y=x$ are $2,2,0$.
  3. Average $4/3$.

Answer.

$4/3$.

Common mistake.

Reporting the total 4 when the average is asked.

Exam tip

Subtract a projection from its point. The difference must be perpendicular to $w$.

The recipe

StepDo thisCheck before moving on
1Subtract the mean.You now work with $x-\mu$.
2Take the score $z=w^T(x-\mu)$ with a unit $w$.The score is one number.
3Rebuild: $\mu+zw$.Do not forget to add the mean back.
4Error: subtract the rebuilt point from $x$.The difference is perpendicular to $w$.

Why the shortcut works. The kept part $zw$ and the error are perpendicular, so by Pythagoras $\lVert x-\mu\rVert^2=z^2+\text{error}^2$. You can get a squared error without building the rebuilt point at all.

Worked example: Away from the origin

Problem.

$\mu=(1,1)$, $w=(0.6,0.8)$, $x=(6,1)$. Find the score, the rebuilt point and the squared error.

Idea.

Centre, project, add back.

  1. $x-\mu=(5,0)$.
  2. $z=0.6\cdot5+0.8\cdot0=3$.
  3. Rebuilt point $(1,1)+3(0.6,0.8)=(2.8,3.4)$.
  4. Squared error $25-9=16$.

Answer.

$z=3$, point $(2.8,3.4)$, squared error $16$.

Common mistake.

Projecting $x$ itself, which ignores the mean.

Check your answer in ten seconds

Dot your error vector with $w$. Here $(3.2,-2.4)\cdot(0.6,0.8)=0$.

Memory line

Total spread equals kept plus lost.

5. Properties of PCA and many features

New axes are perpendicular and uncorrelated; the small matrix can replace the big one.

what PCA guarantees, and the shortcut when features outnumber points

The question this lesson answers. What stays true after changing to the principal axes, and what if there are more features than points?

A rotation of the viewpoint

PCA turns the axes to follow the cloud. The points do not change, only the coordinates used to describe them.

What PCA does and does not do

StatementVerdict
uses labelsno: it is unsupervised
principal directions are eigenvectors of $C$yes
they are mutually perpendicularyes
the new coordinates are uncorrelatedyes: their covariance matrix is diagonal
total variance is unchangedyes, if all components are kept
it reduces the number of pointsno: it reduces the number of coordinates

In the new coordinates $z=V^T(x-\mu)$ the covariance matrix is $V^TCV=\Lambda$. That single line proves that it is diagonal, that the variance of coordinate $j$ is $\lambda_j$, and that the total is $\operatorname{tr}\Lambda=\operatorname{tr}C$.

Many features. Let $A$ be a centred $n\times d$ data matrix with $d>n$. The directions we need are eigenvectors of the large $d\times d$ matrix $A^TA$. But the small $n\times n$ matrix $AA^T$ has the same non-zero eigenvalues. If $AA^Tu=\lambda u$ with $\lambda>0$ and $\lVert u\rVert=1$, then $$v=\frac{A^Tu}{\sqrt\lambda}$$ is a unit eigenvector of $A^TA$ with the same $\lambda$. Divide by $\sqrt\lambda$, not by $\lambda$, because $\lVert A^Tu\rVert^2=u^TAA^Tu=\lambda$. (If a factor $\frac1n$ is placed in the covariance, divide by the square root of the eigenvalue of $AA^T$ itself, without the $\frac1n$.)

Worked example: Uncorrelated scores

Problem.

$C=\begin{bmatrix}3&1\\1&3\end{bmatrix}$. Write the covariance of the PCA coordinates.

Idea.

It is $\Lambda$.

  1. Eigenvalues 4 and 2.

Answer.

$\operatorname{diag}(4,2)$, with total 6 as before.

Common mistake.

Expecting the off-diagonal 1 to survive.

Worked example: The small matrix

Problem.

$A=\begin{bmatrix}1&2&2\end{bmatrix}$ (one centred row, three features, taken as given). Find the non-zero eigenvalue of $A^TA$ and its unit eigenvector from $AA^T$.

Idea.

$AA^T$ is $1\times1$.

  1. $AA^T=9$ with $u=1$.
  2. $v=A^T u/\sqrt9=(1,2,2)/3$.

Answer.

$\lambda=9$, $v=\tfrac13(1,2,2)$.

Common mistake.

Dividing by 9, which gives a vector of length $1/3$.

From the lecture notes: PCA through the SVD

Let $X$ be the centred $n\times d$ data matrix and $X=U\Sigma V^T$. Then $C=\frac1nX^TX=V\,\frac{\Sigma^T\Sigma}{n}\,V^T$. So the right singular vectors $v_i$ are the principal directions, and $\lambda_i(C)=\sigma_i^2/n$.

Why it works this way. $AA^T$ and $A^TA$ share their non-zero eigenvalues, so you may solve the smaller problem and convert the eigenvectors.

From the lecture notes: three common misconceptions

PCA reduces the number of features $d$, not the number of points $n$. It does not delete chosen features; each new coordinate is a combination of the old ones. PCA is one method of dimensionality reduction, not another name for it.

Worked example: Equal eigenvalues

Problem.

$C=4I$ in two dimensions. Which direction is the first principal component?

Idea.

Compare the variance in different directions.

  1. Every unit vector gives variance 4.

Answer.

Any unit vector; there is no single one.

Common mistake.

Insisting on $(1,0)$.

Tips and tricks
  • Total variance equals the trace of the covariance matrix, so the largest eigenvalue divided by the trace is the share kept by one component.
  • With $n$ points, expect at most $n-1$ non-zero eigenvalues after centring.
  • A true or false option that mentions labels is a hint: PCA never uses them.
Memory line

Same non-zero eigenvalues, so work on the small side.

Method for any exam question

StepDo this
1Check which is smaller: points or features.
2Solve the smaller eigen-problem.
3Convert with $v=A^Tu/\sqrt\lambda$.
4Normalise the direction.

Practise this topic →

Weeks covering this topic

Other MLF topics