Principal Component Analysis (PCA)
Compare centered data with its projection onto a principal direction. Understand what variance retention does and does not preserve.
Jump to a section
Why this matters
Principal component analysis finds orthogonal directions that explain the greatest variance in centered data. Keeping only the leading components gives a lower-dimensional representation.
PCA preserves variance under a linear projection. It does not automatically preserve the information most useful for a prediction task, and feature scaling can change the result. Inspect the data and the projection before deciding what to discard.
Build the mental model
Imagine a cloud of points stretched mostly along one diagonal. PCA rotates the coordinate system so the first new axis points along the direction of greatest spread, the second along the next-greatest (orthogonal to the first), and so on. Projecting onto the first few axes keeps the directions with greatest variance and discards lower-variance directions, which may still contain useful predictive information.
Keep the direction that carries the variation.
Move a three-dimensional point cloud onto its first principal component and inspect the lost directions.
The visual loads as you reach this section.
The first principal component is the single direction that, if you projected all points onto it, would preserve the most variance: equivalently, the line minimizing total squared reconstruction error.
Work through the math
Given centered data (mean subtracted), the covariance matrix is
PCA finds the orthonormal directions that maximize projected variance subject to . The solution is the eigenvectors of , ordered by eigenvalue:
Each eigenvalue is the variance captured by component , so the fraction of variance explained by the top components is : the standard way to choose . In practice PCA is computed via the SVD of : the principal components are the columns of , and the singular values relate to variance by . SVD is preferred for numerical stability (it avoids forming ). Scaling matters: PCA is variance-driven, so features on larger scales dominate: choose scaling based on units and the question. Standardization gives each feature equal marginal variance; it can also amplify low-variance noise.
Key takeaway: PCA = center, then project onto the top eigenvectors of the covariance matrix (computed stably via SVD), keeping enough components to hit your explained-variance target, with a deliberate scaling choice, because PCA listens to variance, not to predictive importance.
| PCA | t-SNE / UMAP | |
|---|---|---|
| Structure captured | Linear (global variance) | Nonlinear (local neighborhoods) |
| Components | Orthogonal axes; variance-ranked | Often 2–3 dimensions for display; higher dimensions are possible |
| New data and reconstruction | Fixed projection of new data; truncated reconstruction is approximate | UMAP supports new-data transforms; standard t-SNE does not learn a reusable transform |
| Typical use | Compression, denoising, decorrelation, preprocessing | Exploratory visualization; UMAP can also provide features |
Read the implementation
1import numpy as np
2
3rng = np.random.default_rng(0)
4X = rng.normal(size=(500, 5)) @ rng.normal(size=(5, 5)) # correlated 5-D data
5
6def pca(X, k):
7 Xc = X - X.mean(axis=0) # 1. center
8 U, S, Vt = np.linalg.svd(Xc, full_matrices=False) # 2. SVD
9 components = Vt[:k] # 3. top-k directions (k × d)
10 projected = Xc @ components.T # 4. project -> (n × k)
11 explained = (S**2) / (S**2).sum() # variance ratio per component
12 return projected, components, explained[:k]
13
14proj, comps, var = pca(X, k=2)
15print(f"shape {proj.shape}, variance explained by top 2: {var.sum():.2%}")Questions and trade-offs
- Conceptual: What does PCA maximize, and what are the principal components? (It finds orthogonal directions that maximize projected variance: the eigenvectors of the covariance matrix, ordered by eigenvalue.)
- Implementation: Why compute PCA via SVD instead of eigendecomposition of the covariance? (SVD on the centered data is more numerically stable and avoids explicitly forming XᵀX, which can lose precision.)
- Applied: How do you choose the number of components k? (By cumulative explained variance: keep enough components to reach a target, e.g. 95%, using the eigenvalue/singular-value ratios.)
- Systems-level: When should you scale features before PCA? (When differences in units should not determine the components. Standardization is a modeling choice, not a requirement; preserving natural scales can be appropriate.)
- Failure modes: When does PCA fail or mislead, e.g. vs. t-SNE? (It only captures linear structure and global variance; nonlinear manifolds or cluster structure may need t-SNE/UMAP, which preserve local neighborhoods instead.)
Check your understanding
From memory: list the four PCA steps (center, covariance/SVD, top-k, project), state what eigenvalues represent, and explain why scaling matters. Check against Stage 3.
Sources and further reading
- scikit-learn, Principal component analysis: centering, SVD, and dimensionality reduction.
- scikit-learn, Importance of feature scaling: how scaling changes principal components.
- UMAP documentation, Transforming new data: using a fitted UMAP model on new samples.
Oliver Perrin
Machine Learning Engineer · Founder, LiminalML
LiminalML brings together concept explanations, mathematical examples, and working visuals. Find more writing by Oliver on the LiminalML Substack.
Keep exploring the idea.
Ask a follow-up in a guided session, work through the self-check, or open the visual in Studio to build on it.
Related concepts
Classical ML
Bias-Variance Tradeoff
Separate systematic error from sensitivity to the training sample. Read an error decomposition without assuming every model follows a U-shaped curve.
Classical ML
Logistic Regression
Connect a linear score to a sigmoid probability, a cross-entropy loss, and a decision threshold.
Classical ML
Gradient Boosting & XGBoost
See one residual-fitting update, then connect the additive model to gradient-based boosting for other losses.