Sub topic 2
Dimensionality reduction and what it costs
This chapter assumes you know basic Python and NumPy, the scikit-learn fit/transform interface, Euclidean distance, and the idea of a feature vector. It covers what dimensionality reduction does, the two main families of methods, and what you lose when you use it. Later chapters build on this cost accounting.
What dimensionality reduction does
A dataset with d features puts each sample at a point in a d-dimensional space. Dimensionality reduction is a mapping from that space to a space with fewer dimensions, usually 2 or 3 for plotting. The mapping is written f: R^d -> R^k with k < d.
The mapping cannot be perfect in general. If the data really occupies more than k dimensions, some of its structure has no room in the output. Every method decides which structure to keep and which to give up. Knowing that choice is how you avoid reading the plot wrongly.
People reduce dimensions for several reasons, and the reason affects which method fits:
- Visualisation: look at the data in 2-D or 3-D.
- Compression and speed: fewer features make later models cheaper to train.
- Noise removal: small-variance directions often hold mostly noise.
- Feature extraction: the new coordinates may be better inputs to a classifier.
This tutorial focuses on visualisation. A method that is good for visualisation can be a poor choice for the other three, and the reverse is also true.
Two families: linear and nonlinear
Linear methods compute each output coordinate as a weighted sum of the input features. In matrix form, Z = X W, where W is a d x k matrix. PCA is the standard example. Linear methods are fast, deterministic in most implementations, and easy to explain. A new point is embedded by multiplying it by W, so out-of-sample points are free.
Nonlinear methods allow any mapping. Neighbour-embedding methods such as t-SNE and UMAP do not even learn an explicit function. They place each point directly in the low-dimensional space by optimising a cost. That is why scikit-learn's TSNE has fit_transform but no transform method.
| Property | Linear (PCA) | Neighbour embedding (t-SNE, UMAP) |
|---|---|---|
| Mapping | Matrix multiplication | Positions found by optimisation |
| Structure kept | Global variance | Local neighbourhoods |
| Deterministic | Yes, up to sign | No, depends on seed and initialisation |
| New points | Cheap `transform` | Not in t-SNE; approximate in UMAP |
| Axes meaningful | Yes, as combinations of features | No |
| Typical cost | Fast | Slower, with more parameters |
What the reduction costs
Going from d to 2 dimensions always costs something. The cost shows up in four ways.
Lost variance
A linear projection discards the directions you do not keep. If the first two principal components hold 30% of the variance, 70% of the spread in the data is not in your plot. You can measure this with the explained variance ratio, as the code below shows.
Distorted distances
The distances between points in the plot differ from the distances in the original space. Two kinds of error occur:
- False neighbours: points that are far apart in the original space land next to each other in the plot.
- Torn neighbourhoods: points that are close in the original space land far apart.
Projection tends to create false neighbours. Methods that cut the data open to unfold it tend to create torn neighbourhoods. Neither error can be removed entirely. Methods differ in which one they allow.
Geometry that cannot fit
Some shapes have no faithful flat picture. A common example is the sphere: you cannot draw a world map without distorting area, distance, or angle. High-dimensional data has the same problem more severely. In 10 dimensions, a point can have 10 neighbours that are all mutually equidistant, but in 2 dimensions you cannot place more than 3 points all at the same distance from each other. This lack of room in low dimensions is a root of the crowding problem, covered in a later chapter.
Lost global layout
Methods that focus on local neighbourhoods preserve who is next to whom and give up the larger arrangement. In t-SNE and UMAP plots, the distance between two clusters, the size of a cluster, and the empty space between groups may not mean what they look like. The chapter on reading embeddings covers this in detail.
Measuring what a linear method keeps
For PCA you can quantify the loss directly. The explained variance ratio gives the share of total variance in each retained component. The reconstruction error gives the squared distance between each point and its projection back into the original space.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
pca = PCA(n_components=2, random_state=0).fit(X)
print("Explained variance ratio:", pca.explained_variance_ratio_.round(3))
print("Total kept by 2 components:", pca.explained_variance_ratio_.sum().round(3))
X_back = pca.inverse_transform(pca.transform(X))
mse = np.mean((X - X_back) ** 2)
print("Mean squared reconstruction error:", round(float(mse), 3))
full = PCA(random_state=0).fit(X)
cumulative = np.cumsum(full.explained_variance_ratio_)
needed = int(np.searchsorted(cumulative, 0.90) + 1)
print("Components needed for 90% of variance:", needed)On the 64-feature digits data, two components keep only about 29% of the variance. About 21 components are needed to reach 90%. A 2-D PCA plot of this data is therefore a heavily compressed view. This is the motivation for nonlinear methods, which can use the 2-D space to preserve a different kind of structure.
The next block draws that same PCA projection, which you will use as the baseline for the rest of the tutorial.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
Z = PCA(n_components=2, random_state=0).fit_transform(X)
plt.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=8)
plt.colorbar(label="digit")
plt.title("PCA of the 64-dimensional digits data")
plt.show()The plot shows some separation, for example digit 0 on one side, but many classes overlap heavily. Overlap in a 2-D projection does not mean the classes overlap in 64 dimensions. It may only mean the 2 directions you kept do not separate them.
A way to see the trade-off
Every method sits somewhere between two goals. One goal is to keep global structure, meaning large-scale distances and the overall shape. The other is to keep local structure, meaning each point's nearest neighbours.
This is a tendency, not a strict split. UMAP keeps somewhat more global structure than t-SNE in many settings, and PCA also preserves local structure when the data is nearly linear. Treat the two goals as ends of a scale.
Common errors
- Treating axes as meaningful. PCA axes are combinations of features with a clear meaning. The axes of a t-SNE or UMAP plot have none. Do not label them or read values off them.
- Judging a method from one run. Nonlinear methods depend on random initialisation and optimisation. Fix
random_statefor reproducibility and check a few seeds for stability. - Assuming a clean plot means clean data. A plot with clear clusters can come from method settings. A plot with no clusters can come from a poor projection. Compare against the PCA baseline and a numeric score before drawing conclusions.
- Skipping preprocessing. Features on very different scales dominate Euclidean distance. Scale features, or reduce with PCA first, before building any distance-based embedding.
Choosing how to proceed
Use this decision rule for the rest of the tutorial:
- Always start with PCA. It is cheap, it shows how much variance 2 components hold, and it gives a baseline.
- If the PCA plot hides structure you know is present, try t-SNE or UMAP.
- Compare the methods with a number, not only by eye. The chapter on quality metrics introduces trustworthiness for this.
- Report the method, its parameters, and the seed with any plot you share.
Exercise
On the digits data, 2 principal components keep about 29% of the variance. A colleague says the 2-D PCA plot shows that digits 5 and 8 are not separable in the original 64 features. Is that conclusion justified, and what would you check instead?
Show answer
No. The plot only shows that the two directions kept by PCA do not separate those classes, and 71% of the variance is missing from the plot. To test separability in the original space, train a classifier (for example logistic regression or k-nearest neighbours) on the 64 features restricted to digits 5 and 8 and check its cross-validated accuracy. You can also compare a neighbour-based score such as trustworthiness between the PCA and nonlinear embeddings.
Exercise
Name the two kinds of neighbour error a dimensionality reduction can make, and say which kind a plain linear projection tends to produce.
Show answer
False neighbours (points far apart in the original space that appear close in the plot) and torn neighbourhoods (points close in the original space that appear far apart). A linear projection collapses the discarded directions, so it tends to produce false neighbours.