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
- Subtract the mean of each feature so the cloud is centered on the origin.
- Compute the singular value decomposition of the centered data, .
- The rows of are the principal directions, ordered from most to least variance. The template fixes each direction's sign so the largest entry is positive.
- Turn the singular values into variances with , and divide by their total to get explained_variance_ratio_.
- Keep the first directions. The transform method projects centered rows onto them, and inverse_transform maps the coordinates back to feature space.
- 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
| If | Use instead |
|---|---|
| The structure is curved, not flat | An autoencoder, or a non-linear method such as UMAP for plotting |
| You want the directions that best separate known classes | Linear discriminant analysis |
| The data is word counts and you want readable topics | Latent Dirichlet Allocation (LDA) |
Math foundations
Centering
Subtract the mean row from every row. Variance is measured around the mean, so this comes first.
The covariance matrix
Entry says how features and vary together. The variance of the data along a unit direction is .
The first component
The unit direction of greatest variance. Its solution is the eigenvector of with the largest eigenvalue. Later components solve the same problem at right angles to the earlier ones.
Through the SVD
The columns of are the eigenvectors of and are its eigenvalues. The template uses the SVD because it avoids forming and is more accurate.
Projection and reconstruction
holds the row's coordinates along the kept directions. is the closest point to in the kept subspace.
Explained variance ratio
The share of the total variance carried by component . Adding up the first ratios tells you how much is kept. The rest is what reconstruction loses.
Symbols
- data matrix (n rows, d features) and its centered version
- vector of feature means
- column of n ones
- covariance matrix of the features, d by d
- factors of the singular value decomposition
- j-th singular value
- j-th principal direction, a unit vector
- variance of the data along direction j
- matrix whose columns are the first k directions
- coordinates of a row along the kept directions
- 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.
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 errorRead 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
- 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 . PCA has no notion of units, so decide whether the comparison between features was meaningful to begin with.
- 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.
- 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.
- 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.