Sub topic 4
The manifold hypothesis and local neighbourhoods
This chapter assumes you know basic Python and NumPy, Euclidean distance, and the scikit-learn fit/transform interface. It explains the assumption that makes neighbour-embedding methods such as t-SNE and UMAP reasonable. It also explains why those methods focus on local neighbourhoods.
The claim
PCA, from the previous chapter, assumes the interesting structure of the data is a flat subspace. Many real datasets do not fit that. The manifold hypothesis is a weaker assumption. It says that high-dimensional data points lie close to a surface of much lower dimension, curved and folded inside the full space.
A manifold is a space that looks flat when you zoom in far enough. The surface of the Earth is a 2-D manifold inside 3-D space. Standing on it, you see a plane. Only when you travel far do you notice the curvature.
Two numbers describe the situation:
- The ambient dimension is the number of features you measured. For the 8x8 digit images it is 64.
- The intrinsic dimension is the number of independent quantities needed to describe a point on the manifold. A handwritten digit varies by stroke thickness, slant, and style, so its intrinsic dimension is probably far below 64.
The hypothesis is an assumption, not a theorem. It tends to hold when the data come from a process with few underlying degrees of freedom. Examples are images of an object under changing pose and lighting, or cells moving through a developmental process. It holds less well for data that is mostly noise, or for data made of many unrelated measurements.
Why this matters for visualisation
If the data lie on a 2-D sheet curled up in 3-D, a good 2-D picture should unroll the sheet. PCA cannot do that. It projects along straight directions, so layers of the roll land on top of each other.
The distance problem is the key issue. On a curved manifold, straight-line (Euclidean) distance in the ambient space can be misleading for points that are far apart. Two points on adjacent layers of a rolled sheet are close in 3-D. They are far apart if you must walk along the sheet. The distance along the surface is the geodesic distance.
Zoomed in, the two distances agree. Over a tiny patch, the surface is nearly flat, so a straight line is almost the same as a path along the surface. This is the reason for the chapter's second topic. Euclidean distance is trustworthy for near neighbours, and it becomes unreliable at long range.
A local neighbourhood test on a Swiss roll
The Swiss roll is a standard test case. It is a 2-D sheet rolled up in 3-D. scikit-learn returns the 3-D coordinates X and the position t along the roll, which is one of the two intrinsic coordinates.
If the hypothesis applies, each point's nearest neighbours in 3-D should have similar t values. Random pairs should not.
import numpy as np
from sklearn.datasets import make_swiss_roll
from sklearn.neighbors import NearestNeighbors
X, t = make_swiss_roll(n_samples=1500, noise=0.05, random_state=0)
nn = NearestNeighbors(n_neighbors=11).fit(X)
_, idx = nn.kneighbors(X)
idx = idx[:, 1:] # drop column 0: each point is its own nearest neighbour
neighbour_gap = np.abs(t[idx] - t[:, None])
random_gap = np.abs(t[:, None] - t[None, :])
print(f"median |t gap|, 10 nearest neighbours: {np.median(neighbour_gap):.2f}")
print(f"median |t gap|, random pairs: {np.median(random_gap):.2f}")The neighbour gap comes out far smaller than the random gap. The 3-D nearest neighbours are also near each other along the sheet. That is the property neighbour embedding needs.
The test has limits. It works here because the sampling is dense relative to the spacing between layers. If you add more noise, or sample too few points, a neighbour can come from the adjacent layer. Then the local structure is damaged. You can check this by raising noise to 1.0 and rerunning.
Local versus global structure
Because only the local geometry is reliable, it helps to separate two kinds of structure:
| Kind | What it describes | Reliability under the manifold hypothesis |
|---|---|---|
| Local | Which points are near each other | High, for small neighbourhoods |
| Global | Distances between far-apart groups, overall shape | Low in the ambient space, since straight lines cut across curvature |
PCA preserves large-scale variance, so it keeps a rough global picture and loses local detail. t-SNE and UMAP take the opposite approach. They try to keep local neighbourhoods and make weaker guarantees about the global layout. The later chapters on reading plots will show what that means in practice.
Unrolling with a manifold method
You can see the benefit of the local view by comparing PCA with Isomap, a method that estimates geodesic distances. Isomap builds a k-nearest-neighbour graph, which only trusts local distances. It then measures distance along paths in that graph. It is a simple relative of the methods in this tutorial.
from sklearn.datasets import make_swiss_roll
from sklearn.decomposition import PCA
from sklearn.manifold import Isomap, trustworthiness
X, t = make_swiss_roll(n_samples=1500, noise=0.05, random_state=0)
Z_pca = PCA(n_components=2, random_state=0).fit_transform(X)
Z_iso = Isomap(n_neighbors=10, n_components=2).fit_transform(X)
for name, Z in [("PCA", Z_pca), ("Isomap", Z_iso)]:
score = trustworthiness(X, Z, n_neighbors=10)
print(f"{name}: trustworthiness = {score:.3f}")Trustworthiness, covered fully in a later chapter, is a score from 0 to 1. It measures whether points that are neighbours in the 2-D embedding were also neighbours in the original space. Isomap normally scores higher than PCA here, because it unrolls the sheet and PCA does not.
Where the hypothesis fails
Treat the hypothesis as a working assumption and watch for these cases:
- Several manifolds. Data often form separate pieces, such as one per digit class. Each piece is a manifold, but there is no path between them. Geodesic distance between pieces is undefined. Graph-based methods then produce disconnected components.
- Varying dimension or density. Different regions can have different intrinsic dimensions, or be sampled at very different densities. A single neighbourhood size may be too large in dense regions and too small in sparse ones.
- Noise. With enough noise in the ambient directions, the data fill a volume rather than lie near a surface. Local neighbourhoods then say less about the structure.
- Sparse sampling. Neighbourhoods are only local if you have enough points. High intrinsic dimension needs many more samples to cover the manifold.
- Curse of dimensionality. In 64 or more dimensions, distances between points tend to concentrate. The nearest and farthest neighbours become more similar in distance, so neighbour rankings are less stable.
What this sets up
The rest of the tutorial builds on one decision: use distances only where they are reliable, which means among near neighbours. The next chapter turns that into a general recipe. Describe each point by its neighbourhood in the original space, then find 2-D positions that reproduce those neighbourhoods. The neighbourhood size you choose is a parameter, and it controls how local the picture is. In t-SNE it is perplexity. In UMAP it is n_neighbors.
Exercise
In the Swiss roll example, two points on adjacent layers of the roll are close in 3-D but far apart along the sheet. Why does this not stop a k-nearest-neighbour graph from capturing the sheet's structure, as long as k is small and the sampling is dense? What goes wrong if k is made very large?
Show answer
With a small k, the nearest neighbours of a point are the points just beside it on the same layer, because those are closer than the points on the adjacent layer, so the graph's edges follow the sheet. With a very large k, the neighbourhood reaches across the gap between layers, and the graph gets "shortcut" edges between layers. Those edges make points that are far apart along the sheet look like neighbours, so the unrolled embedding folds the layers back together.