Dimensionality Reduction (PCA, t-SNE, UMAP)
- Curse of dimensionality (Bellman, 1961) shows distances become meaningless in high dimensions
- PCA dates to Karl Pearson (1901) and Harold Hotelling (1933); t-SNE to van der Maaten & Hinton (2008)
- Critical preprocessing step before many classical ML algorithms
Dimensionality reduction compresses high-dimensional data into fewer dimensions while preserving as much structure as possible. PCA finds directions of maximum variance (linear). t-SNE and UMAP find non-linear low-dimensional embeddings that preserve local neighborhood structure.
- PCA is used as a preprocessing step for almost every classical ML algorithm
- Autoencoders and VAEs are the deep learning analogs of PCA
- Connects to matrix factorization, spectral methods, and representation learning in transformers
- Derive PCA from both the variance-maximization formulation and the Eckart-Young best-rank-k Frobenius approximation, and prove they are equivalent via the SVD.
- Explain whitening / sphering and probabilistic PCA, and recognize when kernel PCA is the right generalization.
- State the t-SNE objective: KL divergence between a Gaussian neighborhood in input space and a heavy-tailed Student-t neighborhood in embedding space, with perplexity as the local-neighborhood knob.
- Explain UMAP's fuzzy simplicial complex framing and why it preserves more global structure than t-SNE in practice.
- Pick a method given (linear vs non-linear, scale, need for inverse transform, downstream model vs visualization).
TL;DR
PCA [1][2] is the linear projection onto the top- eigenvectors of the centered data covariance, equivalently the best rank- approximation of in Frobenius norm by the Eckart-Young theorem [3]. The connection is the SVD : the right singular vectors are loadings, are scores, and the explained variance ratios are . Probabilistic PCA [4] recasts PCA as a Gaussian latent-variable model, enabling missing-data handling and Bayesian extensions. Kernel PCA [5] applies PCA in an RKHS implicitly through a kernel. For non-linear visualization, t-SNE [6] minimizes the KL divergence between Gaussian neighborhoods in input space and heavy-tailed Student-t neighborhoods in embedding space; perplexity controls the effective neighborhood size. UMAP [7] is built on a fuzzy simplicial complex view of the manifold and tends to preserve global structure better than t-SNE while running an order of magnitude faster. Cluster sizes and inter-cluster distances on a t-SNE plot are not interpretable [8].
Intuition
Three mechanisms reduce dimension:
- Linear projection (PCA, FA, ICA). Find a small set of orthogonal directions that capture the most variance (or the most independent signal). Output: a global linear map you can apply to new points.
- Manifold preservation (t-SNE, UMAP, LLE, Isomap). Build a graph that reflects local neighborhoods in the original space, then place points in a low-dimensional space that preserves that graph. Output: a 2-D or 3-D plot for the eye, not for a downstream model.
- Probabilistic latent variables (PPCA, factor analysis, VAE). Posit that observations are generated from low-dimensional latents through a parametric model and learn the parameters by maximum likelihood.
PCA is the rotation of the data such that the first axis has the most variance, the second axis has the most variance subject to being orthogonal to the first, and so on. The Eckart-Young theorem says this is also the unique linear projection (in ) that loses the least information when you keep only the first axes [3].
Math
PCA from variance maximization: top eigenvectors of the covariance matrix
Setup
Let have rows that have already been centered (). Define the sample covariance
We want a unit vector that maximizes the variance of the projected data .
Variance of a projection
Since is centered, , so
The optimization is
Lagrangian and the eigenvalue equation
Form . Setting gives
So critical points are eigenvectors of , with the constraint enforcing . Multiplying on the left by : , so the variance equals the eigenvalue. The maximum is the largest eigenvalue, attained at its eigenvector .
Iterating: the deflation argument
The second principal component maximizes variance subject to being orthogonal to . The same Lagrangian argument shows is the eigenvector of with the second-largest eigenvalue. Inductively, the top- principal components are the top- eigenvectors of , and the explained variance of component is .
PCA from Eckart-Young: best rank-k Frobenius approximation
Statement
Among all matrices of rank at most , the one that minimizes is given by the truncated SVD: if with singular values , then
This is the Eckart-Young theorem (also Eckart-Young-Mirsky, since Mirsky 1960 extended it to all unitarily invariant norms) [3].
Proof sketch via SVD
Any rank- matrix has , so its null space has dimension at least . Choose any orthonormal basis of and observe
By a min-max characterization of singular values (the Courant-Fischer-Weyl theorem applied to the symmetric ), the right-hand side is at least , with equality when the are right singular vectors . The truncated SVD attains this bound. ∎
Equivalence with variance maximization
The covariance is , so the eigenvectors of are exactly the right singular vectors of , and the eigenvalues of are . The two formulations therefore yield the same projection. The scores are , equivalently , so they can be computed without forming - which matters numerically when is large.
Probabilistic PCA: PCA as a Gaussian latent-variable model
The model
Probabilistic PCA [4] posits a -dimensional latent and an observed generated by
Marginalizing gives .
Maximum likelihood
Fitting by maximum likelihood (taking the gradient of the log-likelihood through the marginal Gaussian) yields the closed-form solution
where has the top- eigenvectors of the sample covariance , holds the corresponding eigenvalues , and is any orthogonal rotation. As , this recovers exact PCA.
What probabilistic PCA buys
- Missing data. EM handles missing entries naturally.
- Bayesian extensions. Bayesian PCA places priors on the columns of to determine automatically [9].
- Mixtures of PCAs. A mixture model where each component is a low-dimensional PPCA captures non-linear manifolds.
The SVD bridge: scores, loadings, whitening
For centered with :
- Loadings. The columns of are the principal directions in input space.
- Scores. gives the projection of each row onto the principal axes.
- Explained variance. Component explains fraction of the total variance.
- Whitening. produces uncorrelated components with unit variance (“sphering”). Useful as a preprocessing step before ICA or some downstream linear models.
In practice, never form when is large; compute the thin SVD of
directly. numpy.linalg.svd(X, full_matrices=False) is the right call.
Kernel PCA
Kernel PCA [5] applies PCA in an RKHS reached by a kernel . The trick: in the dual formulation of PCA, the principal directions live in the span of the (centered) data, so we need only the inner products .
The recipe:
- Form the Gram matrix .
- Center in feature space: , where is the matrix with all entries .
- Eigendecompose .
- The projection of onto the -th principal component is .
Kernel PCA can capture non-linear structure that linear PCA cannot, but it costs memory for the Gram matrix and does not scale beyond a few tens of thousands of points without approximations.
t-SNE: probability-preserving non-linear embedding
t-SNE [6] is a visualization algorithm: it places high-dimensional points in 2-D or 3-D so that local neighborhoods are preserved.
High-dimensional similarities
For each point , define a Gaussian neighborhood with point-specific bandwidth :
Symmetrize: .
The bandwidth is chosen by binary search to make the perplexity match a target value (typically 5 to 50), where is the Shannon entropy of in nats. Perplexity is the effective number of neighbors and is the only really important hyperparameter.
Low-dimensional similarities (Student-t)
For points in the embedding, use a heavy-tailed Student-t with one degree of freedom:
Loss
t-SNE minimizes the KL divergence
via gradient descent. Two design choices give t-SNE its character:
- KL is asymmetric. Putting first penalizes mapping nearby points (large ) to far-apart positions (small ) much more than the reverse, so t-SNE preserves local structure aggressively.
- Heavy-tailed . The Student-t in low dim has fatter tails than the Gaussian in high dim, which provides “repulsion” that counteracts the crowding problem: in high dim there is more volume far from any given point, and a Gaussian in low dim cannot capture that without piling distant points on top of each other.
Caveats
Three things every t-SNE consumer must internalize:
- Cluster sizes are not interpretable. A small visual cluster does not mean a tight high-dimensional one. The embedding scales the variance per cluster to be roughly equal.
- Distances between clusters are not interpretable. Two clusters that look far apart on the plot may not be far apart in the original space.
- Perplexity matters. Run t-SNE at several perplexities (5, 30, 50, 100) and at least two random seeds, and only trust patterns that are stable across runs.
When in doubt, read Wattenberg, Viégas, and Johnson 2016 in Distill - the visual examples make every pitfall obvious [8].
UMAP: fuzzy simplicial complexes
UMAP [7] takes a different theoretical route. The core idea: model each point’s local neighborhood as a fuzzy simplicial set on a Riemannian manifold, take the union of those local sets, and then optimize a low-dimensional layout whose own fuzzy simplicial set has minimum cross-entropy with the high-dimensional one.
In practice the UMAP algorithm reduces to:
- For each point , find its nearest neighbors.
- Compute a smooth weight for each edge using a local distance scaling that calibrates the effective neighborhood size (analog of t-SNE’s perplexity).
- Symmetrize using a probabilistic t-conorm: .
- Initialize the low-dimensional embedding (often via Laplacian eigenmaps).
- Optimize cross-entropy between the high-dim and low-dim fuzzy graphs using stochastic gradient descent with negative sampling.
UMAP empirically preserves more global structure than t-SNE because the loss includes a “repel” term over sampled non-edges (rather than t-SNE’s implicit repulsion via ), and because the Laplacian-eigenmap initialization already encodes global geometry. It is also typically 5x to 10x faster than t-SNE and scales to a million points routinely.
Comparison
| Method | Linear? | Preserves global structure? | Preserves local structure? | Deterministic? | Has inverse transform? | Scales to 1M points? |
|---|---|---|---|---|---|---|
| PCA | yes | yes (variance is global) | no (only via top-k summary) | yes | yes (transpose of W) | yes (randomized SVD) |
| Kernel PCA | no (linear in feature space) | yes (in RKHS) | no | yes | no (RKHS preimage is hard) | no (n^2 Gram matrix) |
| t-SNE | no | no (cluster distances are not meaningful) | yes (the design goal) | no (random init + non-convex) | no | no (typical limit ~50k) |
| UMAP | no | better than t-SNE in practice | yes | no (random init) | parametric variants exist | yes (linear in n with n_neighbors fixed) |
Explained variance
A standard PCA diagnostic is the cumulative explained-variance curve. Pick the smallest such that exceeds your tolerance (typically 0.9 to 0.99). The Plot below shows this curve on a synthetic dataset with three informative directions and seven noise directions, where the elbow at is sharp.
Implementations
The numpy version implements PCA via thin SVD in about ten lines. The sklearn version covers the production stack including kernel PCA and t-SNE. The umap-learn sketch shows the API for the most common alternative to t-SNE.
import numpy as np
def pca(X, k):
"""PCA via thin SVD. Returns (scores, loadings, explained_var_ratio)."""
Xc = X - X.mean(axis=0) # center
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
loadings = Vt[:k].T # d x k
scores = U[:, :k] * s[:k] # n x k
var = (s ** 2) / max(len(X) - 1, 1)
explained = var[:k] / var.sum()
return scores, loadings, explained
rng = np.random.default_rng(0)
# 3 informative directions in a 10-d space, plus noise.
Z = rng.normal(size=(200, 3))
W = rng.normal(size=(3, 10))
X = Z @ W + 0.05 * rng.normal(size=(200, 10))
scores, loadings, explained = pca(X, k=3)
print("explained variance ratio:", np.round(explained, 3))
print("scores[:3]:")
print(np.round(scores[:3], 3))Run a from-scratch SVD-based PCA on a 3-D synthetic dataset live and inspect the principal axes plus explained variances:
(no output yet)
Real-world uses
| Use case | Method | Why |
|---|---|---|
| Visualizing 1k-50k high-d points (embeddings, gene expression) | t-SNE or UMAP | Both preserve local structure and produce a 2-D plot. UMAP is the modern default; t-SNE remains common for legacy comparison. |
| Decorrelating features before a downstream linear model | PCA + whitening | Removes collinearity that would otherwise destabilize the closed-form / IRLS solution. |
| Compressing image features | PCA (or autoencoders for non-linear cases) | PCA is the optimal linear compression in MSE; cheap to compute and to invert at decode time. |
| Data exploration on million-point datasets | UMAP (or PCA + UMAP cascade) | UMAP scales linearly in n. t-SNE typically caps near 50k. Run PCA -> 50 dims -> UMAP -> 2 dims for the cleanest results. |
| Anomaly detection on tabular data | PCA reconstruction error | Project + reconstruct; points with high reconstruction residual lie off the principal subspace. Cheap and surprisingly effective. |
Pitfalls
If your features are on wildly different scales (years, dollars, kilograms), the largest-variance direction is “the one with the biggest unit”, not “the one with the biggest signal”. Always standardize first. PCA on raw features is one of the most common mistakes in industrial ML.
t-SNE is a visualization algorithm. The optimization is non-convex, non-deterministic, and explicitly does not preserve global distance. Two points that land close together in the embedding may be arbitrarily far apart in the original space, and the embedding changes with each random seed. Use PCA, UMAP (with care), or a learned encoder for any downstream modeling task.
UMAP’s n_neighbors plays the role of t-SNE’s perplexity: smaller values
emphasize local structure, larger values pull global structure into focus.
min_dist controls how tightly clusters pack. Defaults are reasonable but
not universal; sweep both knobs and at least two random seeds before
trusting any visual pattern.
If two singular values are equal (or numerically very close), the corresponding principal axes are determined only up to a rotation in their shared eigenspace. Sign flips in any column of are also free. Reproducing exact loadings across runs requires fixing a convention, often “make the largest-magnitude entry of each column positive”.
Pop quiz
- 1. Which statement about PCA via SVD is correct?
- 2. The Eckart-Young theorem says...
- 3. Why does t-SNE use a Student-t with 1 df in the embedding space?
- 4. What does perplexity control in t-SNE?
- 5. You have a million 50-d embeddings and want a 2-D scatter plot. Which method is most practical?
Interview Q&A
Derive PCA from the SVD.onsite
Setup. Let be centered (). Compute the thin SVD with and .
Variance angle. The covariance is , so the eigenvectors of are the columns of and the eigenvalues are . The variance-maximizing direction is , with variance .
Best-approximation angle. Eckart-Young says the best rank- approximation in Frobenius norm is , and the residual is .
Equivalence. Both formulations select the same top- right singular vectors and produce identical scores . The explained variance ratio of component is .
Practical note. Compute the thin SVD of directly. Forming squares the condition number and is memory.
Sketch the proof of the Eckart-Young theorem.research
Statement. For with SVD , the matrix minimizes over all with , with .
Lower bound. Let be any rank- matrix. Its null space has dimension at least . Pick orthonormal . Then
By a min-max characterization of singular values (the Courant-Fischer-Weyl theorem applied to ), the minimum of over -dimensional subspaces of is attained when , the bottom right singular vectors, and equals .
Upper bound. has rank exactly and by direct computation.
So attains the lower bound and the truncated SVD is optimal. ∎ [3][10]
Why are distances in a t-SNE plot not interpretable globally?onsite
t-SNE minimizes where:
- is built from Gaussian neighborhoods in the original space, with a per-point bandwidth chosen so that each point’s effective neighborhood has the target perplexity. Different points get different bandwidths.
- is built from a heavy-tailed Student-t in the low-dimensional space.
Two consequences:
- Per-point variance scaling. Because each point’s is set to a fixed perplexity, dense and sparse regions of the input space are mapped to roughly equal-sized clusters in the output. Cluster sizes therefore lose meaning.
- Asymmetric KL. Putting first heavily penalizes putting nearby high-d points far apart in low-d but barely penalizes putting far high-d points anywhere. So local structure is preserved aggressively at the cost of global structure.
The combined effect: clusters look reasonable, but distances between clusters - and even cluster sizes - are artifacts of perplexity, init, and seed. Wattenberg, Viégas, and Johnson 2016 have side-by-side examples that make this concrete [8].
Derive kernel PCA in the dual formulation.research
Setup. A feature map to an inner-product space. We want to do PCA on without computing explicitly.
Centered features. Let and define . The covariance operator is
Eigenvectors live in the span of features. Any eigenvector of with satisfies , which after expanding shows . Write .
Kernel formulation. Substituting into and taking inner products with gives
where is the centered Gram matrix, computable from the original as .
Projections. The projection of onto principal axis is
normalized by . The whole computation goes through inner products only - we never form [5].
A weekend exercise to internalize the family:
- Implement PCA from scratch in 10 lines via thin SVD (see the numpy
CodeCompareblock) and reproduce sklearn’s loadings up to sign onmake_blobs. - Verify Eckart-Young numerically: compute for = (truncated SVD) versus = (random rank- matrix matching on the trace) and confirm the SVD residual is the smaller of the two, equal to the analytical .
- Run t-SNE on MNIST at perplexities with two seeds each and observe how the cluster layout shifts; cluster sizes and inter-cluster distances are not stable.
- Compare UMAP at
n_neighborson the same data and observe how local-vs-global structure changes.
Interactive Demo
References
- Pearson, K. (1901). On lines and planes of closest fit to systems of points in space. Philosophical Magazine, Series 6, 2(11), 559-572. doi:10.1080/14786440109462720
- Hotelling, H. (1933). Analysis of a complex of statistical variables into principal components. Journal of Educational Psychology 24(6), 417-441. doi:10.1037/h0071325
- Eckart, C. and Young, G. (1936). The approximation of one matrix by another of lower rank. Psychometrika 1(3), 211-218. doi:10.1007/BF02288367
- Tipping, M. E. and Bishop, C. M. (1999). Probabilistic principal component analysis. Journal of the Royal Statistical Society, Series B, 61(3), 611-622. doi:10.1111/1467-9868.00196
- Schölkopf, B., Smola, A., and Müller, K.-R. (1998). Nonlinear component analysis as a kernel eigenvalue problem. Neural Computation 10(5), 1299-1319. doi:10.1162/089976698300017467
- van der Maaten, L. and Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research 9, 2579-2605. https://www.jmlr.org/papers/v9/vandermaaten08a.html
- McInnes, L., Healy, J., and Melville, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction. arXiv preprint. arXiv:1802.03426
- Wattenberg, M., Viégas, F., and Johnson, I. (2016). How to Use t-SNE Effectively. Distill. doi:10.23915/distill.00002
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
- Hastie, T., Tibshirani, R., and Friedman, J. (2009). The Elements of Statistical Learning, 2nd ed.. Springer. https://hastie.su.domains/ElemStatLearn/