Classical ML
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 structure that matters and discards directions where the data barely varies.
Project onto the direction of greatest variance
Purple points are the original data; orange points are their projections. Follow the dashed perpendicular segments to the diagonal principal direction.
The visual loads as you reach this section.
Inspect the plotted values
x,y,series -3,-2,Original -2.5,-2.5,Projection -2,-3,Original -2.5,-2.5,Projection -1,-1,Original -1,-1,Projection 1,1,Original 1,1,Projection 2,3,Original 2.5,2.5,Projection 3,2,Original 2.5,2.5,Projection
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: standardize features first unless they're already comparable.
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, and always scale features first, because PCA listens to variance, not to importance.
| PCA | t-SNE / UMAP | |
|---|---|---|
| Structure captured | Linear (global variance) | Nonlinear (local neighborhoods) |
| Components | Orthogonal axes; variance-ranked | 2–3 embedding coordinates |
| Invertible / usable as features? | Yes (transform applies to new data | No) visualization only |
| Typical use | Compression, denoising, decorrelation, preprocessing | Exploratory visualization |
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: Why must you scale features before PCA? (PCA is variance-driven, so a feature on a larger scale dominates the components regardless of importance: standardize first.)
- 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.
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.