Sign in

Principal component analysis (PCA)

Principal Component Analysis

Principal component analysis: a method that finds the directions along which data varies most and describes each row by its coordinates along the first few of them.

Overview

A cloud of points in many dimensions is often nearly flat: most of its spread lies along a few directions, and the rest is small. PCA finds those directions. The first principal component is the line along which the points are most spread out. The second is the most spread-out direction at right angles to the first, and so on. Keeping only the first few coordinates gives a shorter description of each row that loses as little of the spread as possible. Nothing is being predicted, so no labels are needed.

A short history

Karl Pearson introduced the idea in 1901 as finding the lines and planes of closest fit to a cloud of points. Harold Hotelling developed it independently in 1933 and gave it the name principal components. It became routine once computers could calculate eigenvectors of large matrices, and it remains the standard first step for reducing dimensions, removing correlated features and plotting high-dimensional data.

How it works

  1. Subtract the mean of each feature so the cloud is centered on the origin.
  2. Compute the singular value decomposition of the centered data, Xc=USV⊤X_c = U S V^\top.
  3. The rows of V⊤V^\top are the principal directions, ordered from most to least variance. The template fixes each direction's sign so the largest entry is positive.
  4. Turn the singular values into variances with λj=sj2/(n−1)\lambda_j = s_j^2 / (n - 1), and divide by their total to get explained_variance_ratio_.
  5. Keep the first kk directions. The transform method projects centered rows onto them, and inverse_transform maps the coordinates back to feature space.
  6. If whiten is set, divide each coordinate by its standard deviation so every component has unit variance.

Watch out for

  • A feature measured in large units dominates the first component simply because its numbers are bigger. Standardise the features first unless their units are comparable.
  • PCA only finds straight directions. Data lying on a curve, such as a ring, is not flattened by it.
  • High variance does not mean useful. A direction with small variance can be the one that separates your classes, and dropping it loses that.
  • A component's sign is arbitrary, and components with nearly equal variance can rotate between runs or data samples, so do not read meaning into one of them alone.

Use cases

When to use it

Reducing many correlated features to a few before plotting, clustering or fitting another model, and removing noise that lives in low-variance directions.

In industry

Finance
Summarising the movement of many interest rates or stock returns with a few factors, such as level, slope and curvature of a yield curve.
Genetics
Plotting individuals by the first components of their genetic variants to reveal population structure.
Manufacturing
Process monitoring: compressing hundreds of correlated sensor readings into a few scores that are tracked for drift.

Choosing it: what must hold

  • Numeric features, centred, and scaled when they are in different units.
  • Linear correlation between the features; uncorrelated features cannot be compressed this way.
  • Acceptance that each component mixes all the original features, which makes it harder to name.

When to choose something else

IfUse instead
The structure is curved, not flatAn autoencoder, or a non-linear method such as UMAP for plotting
You want the directions that best separate known classesLinear discriminant analysis
The data is word counts and you want readable topicsLatent Dirichlet Allocation (LDA)

Math foundations

  1. Centering

    Xc=X−1μ⊤,μ=1n∑i=1nxiX_c = X - \mathbf{1}\boldsymbol{\mu}^\top, \qquad \boldsymbol{\mu} = \frac{1}{n}\sum_{i=1}^{n} \mathbf{x}_i

    Subtract the mean row from every row. Variance is measured around the mean, so this comes first.

  2. The covariance matrix

    C=1n−1Xc⊤XcC = \frac{1}{n - 1} X_c^\top X_c

    Entry (j,l)(j, l) says how features jj and ll vary together. The variance of the data along a unit direction v\mathbf{v} is v⊤Cv\mathbf{v}^\top C \mathbf{v}.

  3. The first component

    v1=arg⁡max⁡∥v∥=1v⊤C v\mathbf{v}_1 = \arg\max_{\lVert \mathbf{v} \rVert = 1} \mathbf{v}^\top C \, \mathbf{v}

    The unit direction of greatest variance. Its solution is the eigenvector of CC with the largest eigenvalue. Later components solve the same problem at right angles to the earlier ones.

  4. Through the SVD

    Xc=USV⊤  ⟹  C=V S2n−1 V⊤,λj=sj2n−1X_c = U S V^\top \;\Longrightarrow\; C = V \, \frac{S^2}{n - 1} \, V^\top, \qquad \lambda_j = \frac{s_j^2}{n - 1}

    The columns of VV are the eigenvectors of CC and λj\lambda_j are its eigenvalues. The template uses the SVD because it avoids forming CC and is more accurate.

  5. Projection and reconstruction

    z=Vk⊤(x−μ),x^=Vkz+μ\mathbf{z} = V_k^\top (\mathbf{x} - \boldsymbol{\mu}), \qquad \hat{\mathbf{x}} = V_k \mathbf{z} + \boldsymbol{\mu}

    z\mathbf{z} holds the row's kk coordinates along the kept directions. x^\hat{\mathbf{x}} is the closest point to x\mathbf{x} in the kept subspace.

  6. Explained variance ratio

    rj=λj∑lλlr_j = \frac{\lambda_j}{\sum_{l} \lambda_l}

    The share of the total variance carried by component jj. Adding up the first kk ratios tells you how much is kept. The rest is what reconstruction loses.

Symbols

X,XcX, X_c
data matrix (n rows, d features) and its centered version
μ\boldsymbol{\mu}
vector of feature means
1\mathbf{1}
column of n ones
CC
covariance matrix of the features, d by d
U,S,VU, S, V
factors of the singular value decomposition
sjs_j
j-th singular value
vj\mathbf{v}_j
j-th principal direction, a unit vector
λj\lambda_j
variance of the data along direction j
VkV_k
matrix whose columns are the first k directions
z\mathbf{z}
coordinates of a row along the kept directions
x^\hat{\mathbf{x}}
reconstruction of a row from its k coordinates

Worked by hand

Two features whose centered data has the covariance matrix with 2 on the diagonal and 1 off the diagonal. Find the principal directions and how much variance each explains.

C=(2112),det⁡(C−λI)=(2−λ)2−1=0C = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}, \qquad \det(C - \lambda I) = (2 - \lambda)^2 - 1 = 0
λ1=3,λ2=1\lambda_1 = 3, \qquad \lambda_2 = 1
v1=12(1,  1),v2=12(1,  −1)\mathbf{v}_1 = \tfrac{1}{\sqrt{2}}(1,\; 1), \qquad \mathbf{v}_2 = \tfrac{1}{\sqrt{2}}(1,\; -1)
r1=33+1=0.75,r2=0.25r_1 = \frac{3}{3 + 1} = 0.75, \qquad r_2 = 0.25

The first direction is the diagonal along which both features rise together, and it carries 75 percent of the variance. Keeping only that one coordinate loses the remaining 25 percent.

Visual example

Loading the example.

Try this

  • Raise the correlation: the first axis explains almost everything.
  • Turn projection on: every point drops onto the first axis.

Code sample

import numpy as np
from impl import PCA
from config import PCAConfig

rng = np.random.default_rng(0)
latent = rng.normal(size=(200, 2))
X = latent @ rng.normal(size=(2, 5)) + 0.01 * rng.normal(size=(200, 5))   # 5 features, 2 real dimensions

pca = PCA(PCAConfig(n_components=2)).fit(X)
Z = pca.transform(X)                              # (200, 2)
print(pca.explained_variance_ratio_.sum())        # about 0.9999
print(np.abs(pca.inverse_transform(Z) - X).max()) # small reconstruction error
Read the implementation (78 lines)
"""Principal component analysis by singular value decomposition.

NumPy only. With Xc the centered data (n, d) and Xc = U S V^T, the rows of V^T are the principal directions
and S^2 / (n - 1) are the variances along them.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import PCAConfig
except ImportError:  # run from the template's own folder
    from config import PCAConfig


class PCA:
    """PCA. After `fit`: `components_` (k, d), `explained_variance_` (k,), `explained_variance_ratio_` (k,)."""

    def __init__(self, config: PCAConfig | None = None) -> None:
        self.config = config or PCAConfig()
        self.mean_: np.ndarray | None = None
        self.components_: np.ndarray | None = None
        self.singular_values_: np.ndarray | None = None
        self.explained_variance_: np.ndarray | None = None
        self.explained_variance_ratio_: np.ndarray | None = None

    def fit(self, X: np.ndarray) -> "PCA":
        """Find the principal directions. X: shape (n, d) with n >= 2."""
        X = np.asarray(X, dtype=float)
        if X.ndim != 2 or len(X) < 2:
            raise ValueError("X must have shape (n, d) with at least two rows")
        n, d = X.shape
        k = self.config.n_components or min(n, d)
        if k > min(n, d):
            raise ValueError(f"n_components={k} is larger than min(n, d)={min(n, d)}")
        self.mean_ = X.mean(axis=0) if self.config.center else np.zeros(d)
        _, s, vt = np.linalg.svd(X - self.mean_, full_matrices=False)
        # An SVD is unique only up to the sign of each direction: make the largest entry positive.
        largest = np.abs(vt).argmax(axis=1)
        signs = np.sign(vt[np.arange(len(vt)), largest])
        signs[signs == 0] = 1.0
        vt = vt * signs[:, None]
        variance = s**2 / (n - 1)
        total = variance.sum()
        self.components_ = vt[:k]
        self.singular_values_ = s[:k]
        self.explained_variance_ = variance[:k]
        self.explained_variance_ratio_ = variance[:k] / total if total > 0 else np.zeros(k)
        return self

    def _scale(self) -> np.ndarray:
        """Per-component standard deviation used by whitening, floored to avoid dividing by zero."""
        return np.sqrt(np.maximum(self.explained_variance_, 1e-12))

    def transform(self, X: np.ndarray) -> np.ndarray:
        """Project onto the components. X: (n, d). Returns shape (n, k)."""
        if self.components_ is None:
            raise RuntimeError("call fit before transform")
        Z = (np.asarray(X, dtype=float) - self.mean_) @ self.components_.T
        return Z / self._scale() if self.config.whiten else Z

    def fit_transform(self, X: np.ndarray) -> np.ndarray:
        """`fit` then `transform` on the same data. X: (n, d). Returns shape (n, k)."""
        return self.fit(X).transform(X)

    def inverse_transform(self, Z: np.ndarray) -> np.ndarray:
        """Map component coordinates back to feature space. Z: (n, k). Returns shape (n, d)."""
        if self.components_ is None:
            raise RuntimeError("call fit before inverse_transform")
        Z = np.asarray(Z, dtype=float)
        if self.config.whiten:
            Z = Z * self._scale()
        return Z @ self.components_ + self.mean_

    def reconstruction_error(self, X: np.ndarray) -> float:
        """Mean squared distance between rows of X and their rank-k reconstruction."""
        X = np.asarray(X, dtype=float)
        return float(np.mean(np.sum((X - self.inverse_transform(self.transform(X))) ** 2, axis=1)))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Create 200 rows of three features where the third is nearly the sum of the first two plus a little noise. Fit PCA with PCAConfig n_components set to 2 and print explained_variance_ratio_ and components_. Call reconstruction_error on the data, then repeat with n_components set to 1 and compare. Multiply one feature by 100 and fit again to see how the components change.

Check on learning

  1. You multiply one feature by 1000, for example by changing metres to millimetres. Why does the first component swing toward that feature, and is the new answer wrong?
    A way to think about it

    Look at what happens to that feature's entry in CC. PCA has no notion of units, so decide whether the comparison between features was meaningful to begin with.

  2. PCA keeps directions of high variance. Describe a classification data set in which the most useful direction has the lowest variance.
    A way to think about it

    Picture two long thin parallel clouds, one per class. The long axis has the variance, and the short gap between them has the information.

  3. The reconstruction error from keeping k components equals, up to a constant factor, the sum of the variances that were dropped. Why should that be so?
    A way to think about it

    The directions are at right angles, so the squared distance between a row and its reconstruction is the sum of its squared coordinates along the discarded directions.

  4. Why must test data be transformed with the mean and components learned from the training data, not refitted on the test set?
    A way to think about it

    Refitting gives a different coordinate system, so a downstream model's weights would no longer line up with the features it sees.