Sub topic 5
Neighbour embedding: keep neighbours close
This chapter assumes you know basic Python and NumPy, the scikit-learn fit/transform interface, Euclidean distance, and the idea of a feature vector. You should also have seen PCA as a linear baseline and the idea that real data often lies near a low-dimensional manifold.
The core idea
A neighbour embedding is a map from high-dimensional points to two or three dimensions that tries to keep each point's neighbours close. It does not try to preserve every pairwise distance. PCA preserves global variance. A neighbour embedding preserves local structure: if point a sits among points b, c and d in the original space, it should sit among them in the plot.
This follows from the manifold hypothesis. On a curved surface, nearby points are well described by straight-line distance, but far-apart points are not. Neighbour embeddings trust short distances and give up on long ones.
The general recipe
Both t-SNE and UMAP follow the same three steps.
- Measure how strongly each pair of points is related in the original space. Close pairs get a high score. Distant pairs get a score near zero.
- Place the points at random or PCA-based positions in 2-D and measure the same kind of score there.
- Move the 2-D points to reduce the mismatch between the two sets of scores, using gradient descent.
The methods differ in how they define the scores and what mismatch they minimise. Later chapters cover those details.
Attraction and repulsion
The optimiser balances two forces. Pairs that are neighbours in the original space pull each other together. Pairs that are not neighbours push each other apart. Without repulsion, all points would collapse into one spot. Without attraction, the layout would be arbitrary.
You can check the neighbour idea directly. This code finds each point's 10 nearest neighbours in the original space and in a PCA map, then reports how many neighbours survive on average.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors
X, y = load_digits(return_X_y=True)
Z = PCA(n_components=2, random_state=0).fit_transform(X)
def neighbour_sets(data, k=10):
nn = NearestNeighbors(n_neighbors=k + 1).fit(data)
idx = nn.kneighbors(data, return_distance=False)
return idx[:, 1:] # drop each point itself
high = neighbour_sets(X)
low = neighbour_sets(Z)
overlap = np.mean([len(set(h) & set(l)) / 10 for h, l in zip(high, low)])
print(f"Average neighbour overlap for PCA: {overlap:.2f}")A low overlap shows that a linear 2-D projection scrambles local neighbourhoods. A good neighbour embedding raises this number.
What you give up
Because only local structure is targeted, distances between far-apart clusters and the sizes of clusters carry little meaning. You will see this in the chapter on reading plots.
Exercise
Why does a neighbour embedding need a repulsive force as well as an attractive one?
Show answer
Attraction alone pulls neighbouring points together, and through chains of neighbours it would pull everything into a single clump. Repulsion between non-neighbours keeps distinct groups apart and spreads the points out so the layout is readable.