AI
Dimensionality Reduction: PCA and Beyond, Explained
Dimensionality reduction turns many features into a few. Learn how PCA works, t-SNE vs UMAP, and how to choose a technique, with a worked example.
Dimensionality reduction is the process of turning a dataset with many features (columns) into one with fewer features while keeping as much of the useful information as possible. A dataset of 1,000 measurements per row might be compressed to 50, or to just 2 so you can plot it. The goal can be faster training, less noise, less storage or a picture you can look at. The best-known method is principal component analysis (PCA), and the best-known tools for visualization are t-SNE and UMAP.
This guide covers what dimensionality reduction is, why it helps, the main dimensionality reduction techniques and how they differ, how PCA works with a small example you can follow by hand, t-SNE vs UMAP and how to read their plots, how to choose between the dimensionality reduction algorithms, and the mistakes that cause bad results.
What Is Dimensionality Reduction?
What is dimensionality reduction in practice? Every feature in a dataset is a dimension. A photo of 28 by 28 pixels has 784 dimensions, a customer record with 200 attributes has 200, and a text embedding often has hundreds or thousands. Dimensionality reduction maps those points into a space with fewer dimensions so that the important structure, such as which points are close together or which directions vary most, survives.
It works because real data is rarely spread evenly through all its dimensions. Many features are correlated (height and weight, neighbouring pixels), some are noise and some carry the same information in different forms. The data sits near a lower-dimensional shape, a line, a plane or a curved sheet, inside the big space. Finding that shape lets you describe each point with a few numbers instead of hundreds.
Dimensionality reduction is a form of unsupervised learning in most cases: it looks only at the features, not at labels. If you need a refresher on that distinction, see supervised vs unsupervised learning.
Why Reduce Dimensions?
There are five common reasons:
- The curse of dimensionality. As dimensions grow, the data becomes sparse relative to the space. Distances between points start to look alike, and distance-based methods such as k-nearest neighbours and clustering lose power. Fewer dimensions make neighbourhoods meaningful again.
- Less overfitting. With more features than the data can support, models memorise noise. Removing redundant or noisy dimensions can improve generalisation.
- Speed and memory. Training time and storage often grow with the number of features. Reducing 1,000 features to 50 can cut both substantially.
- Visualization. People can see two or three dimensions. Reducing to 2D lets you spot clusters, outliers and structure.
- Denoising and compression. Keeping only the strongest directions discards small variations that are often noise, and the reduced data is cheaper to store and transmit.
There's a cost: reduction throws information away, and projected features (like principal components) are mixtures of the originals that are harder to explain. It's a trade, not a free improvement.
Feature Selection vs Feature Extraction
Dimensionality reduction techniques fall into two families:
| Feature selection | Feature extraction | |
|---|---|---|
| What it does | Keeps a subset of the original features | Builds new features from combinations of the originals |
| Examples | Dropping low-variance columns, L1 regularization, tree-based importance | PCA, LDA, t-SNE, UMAP, autoencoders |
| Interpretability | High: the columns keep their meaning | Lower: new features are blends |
| Typical use | When you need to know which inputs matter | When you want compact representations or plots |
Feature selection answers "which of my columns do I need?" and feature extraction answers "what is a compact description of each row?". Both are valid; the right one depends on whether you need to keep the original meaning.
Dimensionality Reduction Techniques Compared
These are the dimensionality reduction algorithms you'll meet most often:
| Technique | Linear? | Supervised? | Main purpose | Notes |
|---|---|---|---|---|
| PCA | Linear | No | General reduction, denoising, preprocessing | Fast, deterministic, keeps directions of maximum variance |
| Truncated SVD (LSA) | Linear | No | Sparse data such as text matrices | Does not need to centre the data |
| LDA (linear discriminant analysis) | Linear | Yes | Reducing while keeping classes apart | Uses labels; at most one fewer component than classes |
| Kernel PCA | Nonlinear | No | Curved structure PCA misses | Needs a kernel choice; slower |
| NMF | Linear, non-negative | No | Parts-based features (topics, images) | Needs non-negative data |
| ICA | Linear | No | Separating mixed signals | Mostly used to separate sources, not to reduce size |
| Random projection | Linear | No | Very fast approximate reduction | Preserves distances approximately |
| t-SNE | Nonlinear | No | 2D or 3D visualization | Local structure; not for features |
| UMAP | Nonlinear | No | Visualization, sometimes preprocessing | Faster than t-SNE; keeps more global structure |
| Autoencoder | Nonlinear | No | Learned compression for complex data | A neural network; see autoencoders |
The one-sentence version: use PCA first for reducing and cleaning, t-SNE or UMAP to look at the data, LDA if you have labels and want class separation, autoencoders when the data is complex and you have enough of it.
How Does Dimensionality Reduction Work? PCA Step by Step
How does dimensionality reduction work in PCA's case? PCA finds new axes, called principal components, ordered by how much of the data's variance each one captures. The first component points along the direction in which the data is most spread out, the second is perpendicular to it and captures the most remaining spread, and so on. You then keep only the first few and project the data onto them.
The steps are:
- Centre each feature by subtracting its mean (and scale it if features use different units).
- Compute the covariance matrix, which records how each pair of features varies together.
- Find its eigenvectors and eigenvalues. Each eigenvector is a principal component direction; its eigenvalue is the variance along it.
- Sort by eigenvalue and keep the top k components.
- Project each data point onto those components to get its new coordinates.
In practice libraries use singular value decomposition (SVD) to do the same thing more stably, which is what scikit-learn's PCA does.
Worked Example: Six Points, Two Dimensions to One
The scikit-learn documentation uses this tiny dataset, which is small enough to follow by hand:
| Point | x | y |
|---|---|---|
| 1 | -1 | -1 |
| 2 | -2 | -1 |
| 3 | -3 | -2 |
| 4 | 1 | 1 |
| 5 | 2 | 1 |
| 6 | 3 | 2 |
The means are already zero. The covariance entries are: variance of x = 28/5 = 5.6, variance of y = 12/5 = 2.4 and covariance of x and y = 18/5 = 3.6. The eigenvalues of that 2 by 2 matrix are about 7.94 and 0.06, so the variance explained is:
| Component | Eigenvalue (variance) | Share of total variance |
|---|---|---|
| 1 | 7.94 | 99.2% |
| 2 | 0.06 | 0.8% |
That matches the documented output of explained_variance_ratio_, which shows [0.9924, 0.0075]. The first component points along the direction (0.84, 0.54): the points lie almost on a single line. Projecting each point onto it replaces two numbers with one:
| Point | New coordinate (component 1) |
|---|---|
| 1 | -1.38 |
| 2 | -2.22 |
| 3 | -3.61 |
| 4 | 1.38 |
| 5 | 2.22 |
| 6 | 3.61 |
We went from 12 numbers to 6 and kept 99.2% of the variation. That's the whole idea: if one direction explains nearly everything, the other adds almost nothing.
How Many Components to Keep
Three practical rules:
- Explained variance threshold. Keep enough components to explain, for example, 95% of the variance. In scikit-learn you can pass a number between 0 and 1 as
n_componentswith the full SVD solver, and it picks the count for you. - A scree plot. Plot explained variance per component and look for the "elbow" where the curve flattens.
- The downstream task. Treat the number of components as a hyperparameter and choose it by the validation score of the model that uses it. Our hyperparameter tuning guide covers how.
PCA in scikit-learn
PCA centres the data but does not scale it, so put a scaler first when features use different units. Fit on the training data only:
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pipe = make_pipeline(
StandardScaler(),
PCA(n_components=0.95, svd_solver="full"),
)
X_train_small = pipe.fit_transform(X_train)
X_test_small = pipe.transform(X_test)
pca = pipe.named_steps["pca"]
print(pca.n_components_, pca.explained_variance_ratio_)explained_variance_ratio_ gives the share of variance for each kept component, and n_components_ is how many were needed for 95%.
t-SNE vs UMAP
For visualization, PCA is often not enough, because its straight-line projections can't unfold curved structure. Two nonlinear methods fill the gap.
t-SNE (t-distributed stochastic neighbour embedding) builds probabilities that say which points are neighbours in the high-dimensional space, then arranges points in 2D so that those neighbour relationships are preserved. UMAP (uniform manifold approximation and projection) builds a graph of neighbour relationships and lays it out in low dimensions. Its authors report it is competitive with t-SNE for visualization quality, arguably preserves more of the global structure and runs faster.
| t-SNE | UMAP | |
|---|---|---|
| Key setting | perplexity (default 30; the scikit-learn docs suggest 5 to 50) | n_neighbors (default 15) and min_dist (default 0.1) |
| What the setting controls | Roughly the number of neighbours each point considers | Local versus global balance, and how tightly points pack |
| Speed | Slower, especially on large data | Faster |
| Global structure | Weak: between-cluster distances are unreliable | Better, but still not exact |
| Deterministic? | No: different initialisations can give different results | No by default; setting a random seed makes it reproducible, at the cost of speed |
| Can transform new data | Not in scikit-learn's version | Yes, in the umap-learn library |
| Best use | Looking at clusters | Looking at clusters, and as a preprocessing step for clustering |
Two recommendations from the scikit-learn documentation are worth following. First, if the data has many features, reduce it first with PCA (or TruncatedSVD for sparse data) to something like 50 dimensions, which suppresses noise and speeds up the neighbour calculation. Second, remember that the cost function is not convex, so different random starts can give different pictures; newer scikit-learn versions initialise with PCA by default, which is more stable.
How to Read a t-SNE or UMAP Plot
The Distill article "How to Use t-SNE Effectively" lists the traps, and they apply to UMAP too:
- Settings change the picture. Run several perplexity or
n_neighborsvalues; trust only what appears in most. - Cluster sizes mean nothing. A big blob is not necessarily a big group.
- Distances between clusters may mean nothing. Two far-apart clusters are not necessarily more different than two close ones.
- Random noise can look like structure. Clumps and patterns can appear in pure noise.
- Use the plot to form a question, not to prove an answer. Confirm with a clustering metric or a downstream test.
Don't feed t-SNE coordinates into a model as features: the embedding is optimised for a picture, not for new data.
Random Projection and the Johnson-Lindenstrauss Lemma
Random projection reduces dimensions by multiplying the data by a random matrix. It sounds too simple to work, but the Johnson-Lindenstrauss lemma says that a set of points can be embedded in a much lower dimension with pairwise distances nearly preserved. How low depends on the number of points and how much distortion (eps) you accept. scikit-learn's documentation gives these examples for one million samples:
| Allowed distortion (eps) | Minimum dimensions |
|---|---|
| 0.5 | 663 |
| 0.1 | 11,841 |
| 0.01 | 1,112,658 |
Two lessons: the bound barely depends on the original dimension, so it helps most for very high-dimensional data, and tight accuracy is expensive. Random projection is cheap and good enough for distance-based tasks like nearest-neighbour search; PCA keeps more structure per dimension if you can afford it.
How to Choose a Dimensionality Reduction Technique
| Your goal | Start with | Why |
|---|---|---|
| Speed up training or reduce noise before a model | PCA | Fast, deterministic, easy to validate |
| See clusters in 2D | PCA to about 50 dimensions, then UMAP or t-SNE | Linear step cleans, nonlinear step unfolds |
| Reduce a sparse text matrix | Truncated SVD | Works on sparse data without centring |
| Separate classes using labels | LDA | Uses labels to maximise class separation |
| Know which original columns matter | Feature selection (L1, tree importances) | Keeps interpretable features |
| Compress images or complex signals | Autoencoder | Learns nonlinear compression |
| Embed millions of points cheaply | Random projection | No fitting needed, distances roughly preserved |
| Work with learned embeddings | PCA or UMAP | See embeddings for what the vectors mean |
Common Mistakes
- Fitting the reducer on all the data. If PCA sees the test set during fitting, information leaks. Fit on training data, then transform the rest.
- Forgetting to scale. PCA follows variance, so a feature measured in thousands dominates one measured in fractions. Standardise first.
- Reading t-SNE and UMAP plots as maps. Distances, sizes and positions between clusters aren't reliable.
- Using t-SNE output as model input. It is for looking, not for training.
- Choosing the number of components by eye only. Check the effect on the model you care about.
- Applying PCA to categorical data. PCA assumes numeric, roughly linear relationships. Use methods built for categories.
- Reducing when you don't need to. Tree-based models handle many features well, and a good model on the full data may beat a worse one on compressed data.
- Assuming components are interpretable. A principal component is a blend of many features; look at its loadings before naming it.
FAQ
What does dimensionality reduction reduce?
It reduces the number of features (columns or dimensions) in a dataset, while keeping as much of the useful structure as possible. Rows stay the same; each row is described with fewer numbers.
What is the difference between PCA and t-SNE?
PCA is a linear method that finds the directions of greatest variance and is fast and deterministic, good for preprocessing. t-SNE is nonlinear, preserves local neighbourhoods and is used only for 2D or 3D visualization, because its distances and cluster sizes aren't reliable.
What is the best dimensionality reduction technique?
There isn't one. PCA is the best first try for general reduction, UMAP or t-SNE for visualization, LDA when you have labels, and autoencoders for complex data. Pick by your goal, and check the result on your task.
Does dimensionality reduction improve model accuracy?
Sometimes. It can help when there are many noisy or redundant features, or when data is scarce, because it reduces overfitting. It can also hurt by removing useful signal, so compare accuracy with and without it.
Is UMAP deterministic?
Not by default. Like t-SNE it uses random initialisation and sampling, so results vary between runs. Setting a random seed makes the output reproducible, usually at the cost of running more slowly.