Search

Search papers and lessons

Principal Component Analysis

Level 2 · 9 min read

Principal component analysis finds the directions in which data varies most, so you can keep the few that matter and drop the rest with the least loss of information.

On this page

  • Colour = topic mix
  • Linear algebra
  • Probability
  • Learning basics
  • Discrete math
  • Sign in to see your progress

TL;DR

Principal component analysis (PCA) rotates a cloud of data points so that its axes line up with the directions of greatest spread. The first axis captures the most variance, the second the most of what remains, and so on. Keeping only the first few axes gives a compact description of the data with the least possible squared error.

Where you'll see it: shrinking many correlated measurements to a few summary numbers, plotting high-dimensional data in two dimensions, and removing noise before a model is trained.

Intuition

A cloud with a long axis

Picture a scatter of points shaped like a cigar on a tilt. Each point has two coordinates, but most of the information lies along the cigar's length. The width is small, and it mostly records noise or small variations. If you could describe every point by its position along the cigar and ignore the width, you would lose little and gain a great deal of simplicity.

PCA finds that long axis automatically. It does not know what the data means. It only asks: in which direction does the data spread out the most? That direction becomes the first principal component. The second component is the direction of most remaining spread, constrained to be at a right angle to the first, and so on.

Why right angles

The components are forced to be perpendicular. This is what makes them useful: each one carries information the others do not, so their contributions add up without double counting. If you kept two components that pointed the same way, you would describe the same variation twice.

What PCA does not do

PCA finds directions of large variance, not directions of importance for a particular task. A feature with large variance that is pure noise will be kept, and a small-variance feature that predicts the label will be dropped. It is also a linear method: it can only rotate and squash the cloud, so a curved structure is not captured. Those limits matter, and they come up again in the tradeoffs section.

The math

Start with nn data points, each a vector in Rd\mathbb{R}^d. Stack them as rows of a matrix XX of size n×dn \times d.

First centre the data. Subtract the mean of each column so that every feature has mean zero. Call the centred matrix XX again. Centring means the directions we find are about spread around the average, not about the origin.

Next compute the Covariance Matrix of the centred data:

C=1n−1X⊤X.C = \frac{1}{n-1} X^\top X.

Here X⊤X^\top is the transpose of XX, so CC is a d×dd \times d matrix. Entry CjkC_{jk} is the covariance between feature jj and feature kk, and the diagonal holds each feature's variance.

Definition: Principal components

Let C=VΛV⊤C = V \Lambda V^\top be the eigendecomposition of CC (see Eigenvalues and Eigenvectors), with eigenvalues sorted from largest to smallest, λ1≥λ2≥⋯≥λd\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d, and the matching unit eigenvectors as the columns of VV. The jj-th principal component is the unit vector vj\mathbf{v}_j, the jj-th column of VV. The score of data point xi\mathbf{x}_i on component jj is zij=xi⋅vjz_{ij} = \mathbf{x}_i \cdot \mathbf{v}_j, the Dot Product of the point with the component.

Here xi\mathbf{x}_i is the ii-th row of XX, a point in the original coordinates. The scores are its coordinates in the new, rotated system.

Why eigenvectors

The variance of the data along a unit direction u\mathbf{u} is u⊤Cu\mathbf{u}^\top C \mathbf{u}. Maximising this over unit vectors is the same as finding the eigenvector with the largest eigenvalue, because CC is symmetric and so has orthogonal eigenvectors. The maximum value is λ1\lambda_1, so the first component carries variance λ1\lambda_1. The next component is the best direction perpendicular to the first, and so on. This is a standard fact about symmetric matrices, and it is what makes the procedure well defined.

How much is kept

The total variance is the sum of the eigenvalues, ∑jλj=tr⁡(C)\sum_j \lambda_j = \operatorname{tr}(C). The fraction of variance kept by the first kk components is

∑j=1kλj∑j=1dλj.\frac{\sum_{j=1}^{k} \lambda_j}{\sum_{j=1}^{d} \lambda_j}.

Reducing the data to kk dimensions means keeping the scores zi1,…,zikz_{i1}, \dots, z_{ik}, which is XVkX V_k with VkV_k holding the first kk columns of VV.

The reconstruction view

The same components give the best low-dimensional approximation. Projecting each point onto the first kk components and mapping back gives an approximation x^i=VkVk⊤xi\hat{\mathbf{x}}_i = V_k V_k^\top \mathbf{x}_i. Among all rank-kk linear approximations, this one has the smallest total squared error. The error left over is exactly the variance in the discarded components. So "keep the most variance" and "lose the least squared error" are the same goal.

Connection to the SVD

In practice PCA is computed with the Singular Value Decomposition (SVD) of XX rather than by forming CC. If X=UΣW⊤X = U \Sigma W^\top, then the columns of WW are the principal components, and the eigenvalues of CC are σj2/(n−1)\sigma_j^2 / (n-1). Avoiding CC is more accurate when dd is large or the data is nearly degenerate.

Worked examples

Example
Four points on a cross

Take four points: (2,0)(2, 0), (−2,0)(-2, 0), (0,1)(0, 1) and (0,−1)(0, -1). They are already centred, since they average to zero.

  1. Compute the sums. ∑x2=4+4+0+0=8\sum x^2 = 4 + 4 + 0 + 0 = 8, ∑y2=0+0+1+1=2\sum y^2 = 0 + 0 + 1 + 1 = 2, and ∑xy=0\sum xy = 0.
  2. Form the covariance with n−1=3n - 1 = 3: C=13(8002)C = \frac{1}{3}\begin{pmatrix} 8 & 0 \\ 0 & 2 \end{pmatrix}, so C=(8/3002/3)C = \begin{pmatrix} 8/3 & 0 \\ 0 & 2/3 \end{pmatrix}.
  3. The eigenvalues are λ1=8/3\lambda_1 = 8/3 and λ2=2/3\lambda_2 = 2/3. The eigenvectors are v1=(1,0)\mathbf{v}_1 = (1, 0) and v2=(0,1)\mathbf{v}_2 = (0, 1). The first principal component is the horizontal axis.
  4. Fraction of variance kept by the first component: 8/38/3+2/3=810=0.8\frac{8/3}{8/3 + 2/3} = \frac{8}{10} = 0.8.
  5. Scores on the first component: 2,−2,0,02, -2, 0, 0. Reduce to one dimension, and the points are 2,−2,0,02, -2, 0, 0 along that axis.
  6. Reconstruction error with one component: the residuals in the vertical direction are 0,0,1,−10, 0, 1, -1, so the squared error is 22. The total sum of squares is 1010, and 2/10=0.22 / 10 = 0.2. This is the 1−0.81 - 0.8 fraction that was discarded, which matches step 4.

Interpretation: the cross had its wide arm along the horizontal axis, so PCA chose that axis. Dropping the vertical axis kept 80 percent of the variance and lost 20 percent.

−3−2−10123−2−1012xy
  • first principal component
  • data
The four points from the example. The first principal component is the horizontal line through the centre, where the spread is largest.
Example
Two correlated features

Two features have covariance matrix C=(2112)C = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}. Each has variance 22, and they are positively correlated.

  1. Find eigenvalues by solving det⁡(C−λI)=0\det(C - \lambda I) = 0. This gives (2−λ)2−1=0(2 - \lambda)^2 - 1 = 0, so λ=3\lambda = 3 or λ=1\lambda = 1.
  2. For λ1=3\lambda_1 = 3, solve Cv=3vC\mathbf{v} = 3\mathbf{v}. The vector (1,1)(1, 1) works, since C(1,1)=(3,3)C(1,1) = (3, 3). Normalise to v1=12(1,1)\mathbf{v}_1 = \frac{1}{\sqrt{2}}(1, 1).
  3. For λ2=1\lambda_2 = 1, the vector (1,−1)(1, -1) works, since C(1,−1)=(1,−1)C(1,-1) = (1, -1). Normalise to v2=12(1,−1)\mathbf{v}_2 = \frac{1}{\sqrt{2}}(1, -1).
  4. Fraction of variance on the first component: 33+1=0.75\frac{3}{3 + 1} = 0.75.

Interpretation: the first component is the diagonal direction where both features rise together. Its score is roughly the average of the two features, and it keeps 75 percent of the total variance. The second component, the difference between the two features, carries the rest. Two correlated features are mostly one thing, and PCA finds that thing.

Tradeoffs and failure modes

PCA is fast, closed-form and easy to interpret, which makes it a default first step. It has several limits that show up in practice.

SituationWhat goes wrongBetter choice
Features on different scales (kilograms and metres)The largest-unit feature dominates the componentsStandardise each feature to unit variance first, which makes PCA work on the correlation matrix
Curved structure, such as a spiralA linear projection flattens it and loses the shapeKernel PCA, or a nonlinear autoencoder (see Autoencoder)
Task depends on low-variance directionsThose directions are discarded, and the label is lostKeep the features, or choose components by their effect on the task
OutliersA few extreme points can tilt the first componentRobust covariance estimates, or remove outliers before fitting
Very many features, few samplesThe covariance matrix is poorly estimatedCompute with the SVD of the data, or regularise the covariance

A common mistake is to choose the number of components without looking at the explained variance. Plot the cumulative fraction and keep enough components to meet a target, such as 90 percent, rather than picking a number by eye.

History

Karl Pearson introduced the idea in 1901, as a way to find the lines and planes that best fit a set of points. Harold Hotelling developed it into the component form used today in 1933, when he analysed correlated test scores and named the components. Michel Loève's work in the 1940s on expanding random processes in orthogonal functions is the same mathematics in another setting, which is why PCA is also called the Karhunen-Loève transform in signal processing. The method caught on once computers made the eigendecomposition cheap, and it is now a standard step in statistics and machine learning.

Check yourself

QuestionWhy are the principal components required to be perpendicular to each other?Show answer

So that each component carries variation the others do not. If two components pointed the same way, they would describe the same spread twice, and adding their scores would overcount it. Perpendicularity guarantees the components are uncorrelated and their variances add up to the total.

QuestionA two-feature dataset has covariance matrix diag(4, 1). What fraction of the total variance does the first principal component keep?Show answer

The eigenvalues are 4 and 1, so the total is 5. The first component keeps 4 divided by 5, which is 0.8, or 80 percent.

QuestionWhy does PCA usually standardise features with very different units before running?Show answer

PCA maximises variance, and variance depends on the units. A feature measured in millimetres has a numerically larger variance than the same quantity in metres, so it would dominate the first component for no real reason. Standardising makes each feature contribute on an equal footing.

QuestionMany points lie evenly spread around a circle. Why does one principal component describe their arrangement poorly?Show answer

PCA can only find straight directions. A circle has no preferred straight direction, so the variance is roughly the same along any axis and the first component captures little structure. A nonlinear method is needed for curved data.

QuestionFor centred data with a covariance of 3 along the first axis and 1 along the second, how much squared error does keeping only the first component leave, relative to the total variance?Show answer

The discarded variance is the second eigenvalue, 1, out of a total of 4. So the relative error is 1 divided by 4, which is 0.25. This is the same as the fraction of variance thrown away, because the reconstruction error equals the variance in the dropped components.

Sources