Sub topic 5
Neighbour embedding: keep neighbours close
This chapter assumes you can read basic NumPy and scikit-learn code and know Euclidean distance. It also assumes you have seen the PCA baseline from earlier in the tutorial. It introduces the shared idea behind t-SNE and UMAP. The details of each method come in later chapters.
The problem PCA leaves open
PCA keeps the directions of largest global variance. That is the right goal when the data lies near a flat subspace. It is the wrong goal when the data lies on a curved surface, such as a rolled-up sheet. Two points can be far apart in a straight line in the original space and still be close along the surface, or the reverse. PCA ignores that difference.
The manifold hypothesis says real data often lies near a low-dimensional curved surface. If it does, a good picture should keep the local structure, meaning who is near whom. Preserving all pairwise distances is neither possible nor needed. Neighbour embedding drops the global distance goal and keeps one promise: points that are neighbours in the original space should be neighbours in the picture.
The recipe
Every neighbour-embedding method follows the same four steps.
- Define neighbourhoods in the original space. Compute a similarity score for each pair of points. The score is large for near neighbours and close to zero for distant points.
- Initialise a layout. Give each point a 2-D position, either at random or from PCA.
- Define a layout similarity. Compute a similarity for each pair in 2-D too. It is a decreasing function of the 2-D distance.
- Optimise. Move the 2-D points until the two sets of similarities agree, using gradient descent on a loss.
The methods differ in how they compute P, how they compute Q, and which loss they use. t-SNE derives P from Gaussian probabilities and uses a Student-t kernel for Q. UMAP builds P as a weighted nearest-neighbour graph. The loop is the same in both.
Attraction and repulsion
Differentiating the loss gives a force on each point, and the force always splits into two parts.
- Attraction pulls a point toward its high-dimensional neighbours. It is strong only for pairs with large P.
- Repulsion pushes every point away from every other point. Without it, minimising the loss would collapse all points onto one spot.
The final picture is the balance of these two forces. Clusters appear because points in the same neighbourhood attract each other. Space appears between clusters because repulsion acts on all pairs. This framing helps later, because many parameters (perplexity, n_neighbors, min_dist, early exaggeration) work by changing the strength or reach of one force.
A minimal implementation
The code below builds P from a symmetrised k-nearest-neighbour graph with binary weights. It uses a heavy-tailed layout kernel and exposes the two forces as separate terms. It is a teaching sketch with a fixed schedule, not a replacement for scikit-learn. The later chapters explain the kernel and the loss it implies.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import trustworthiness
from sklearn.neighbors import NearestNeighbors
X, y = load_digits(return_X_y=True)
n, k = X.shape[0], 10
# Step 1: neighbourhoods. Binary k-NN graph, symmetrised, normalised to sum 1.
idx = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X)[1][:, 1:]
P = np.zeros((n, n))
P[np.repeat(np.arange(n), k), idx.ravel()] = 1.0
P = np.maximum(P, P.T)
P /= P.sum()
# Step 2: initial layout from PCA, scaled small.
Y = PCA(n_components=2, random_state=0).fit_transform(X)
Y = 1e-2 * Y / Y[:, 0].std()
# Steps 3 and 4: layout similarities, forces, gradient descent with momentum.
update = np.zeros_like(Y)
lr = 200.0
for it in range(400):
exaggeration = 12.0 if it < 100 else 1.0
momentum = 0.5 if it < 100 else 0.8
sq = (Y ** 2).sum(axis=1)
D = sq[:, None] + sq[None, :] - 2.0 * Y @ Y.T # squared distances
W = 1.0 / (1.0 + D) # heavy-tailed kernel
np.fill_diagonal(W, 0.0)
Q = W / W.sum()
attraction = exaggeration * P * W
repulsion = Q * W
S = attraction - repulsion
grad = 4.0 * (S.sum(axis=1)[:, None] * Y - S @ Y)
update = momentum * update - lr * grad
Y = Y + update
Y -= Y.mean(axis=0)
print("trustworthiness:", round(trustworthiness(X, Y, n_neighbors=10), 3))
plt.scatter(Y[:, 0], Y[:, 1], c=y, cmap="tab10", s=8)
plt.colorbar(label="digit")
plt.title("Toy neighbour embedding of the digits data")
plt.show()Read the loop against the recipe. attraction is nonzero only where the k-NN graph has an edge. repulsion is nonzero for every pair. The first 100 iterations multiply attraction by 12, which lets clusters form before the layout settles. Exact numbers and layout vary with library versions, so judge the result by whether the digit classes form separate groups and whether trustworthiness is high.
Design choices inside "neighbour"
Step 1 hides several decisions that change the picture.
| Choice | Options | Effect |
|---|---|---|
| Neighbourhood shape | Fixed k nearest neighbours, or a soft kernel with a width per point | Fixed k is simple. A per-point width adapts to dense and sparse regions. |
| Metric | Euclidean, cosine, correlation, and others | Decides who counts as near. Cosine suits text vectors. Euclidean suits many dense features. |
| Symmetry | Neighbour lists are not symmetric, since A may list B while B does not list A | Methods symmetrise P, for example with `max` as above or by averaging. |
| Neighbourhood size | Small or large k | Small k keeps fine local detail. Large k pulls in broader structure. |
What neighbour embedding gives up
The method keeps local structure at the expense of global structure. Three consequences follow, and the reading chapter covers them in detail.
- Distances between far-apart clusters in 2-D are not reliable, because only neighbour pairs carry attraction.
- Cluster sizes in 2-D reflect the layout dynamics, not the spread of the original cluster.
- The loss is not convex. Different seeds or initialisations can give different layouts, so one run is one sample.
Common errors
- Embedding unscaled features. One large-valued column dominates the distances, so the neighbours reflect that column.
- Treating the axes as variables. Unlike PCA, no 2-D axis corresponds to any original feature or direction.
- Judging only by eye. A plot that looks well separated may still scramble neighbourhoods. Use a score.
- Using the 2-D embedding as input to clustering without care. Clusters in the plot can be artifacts of the layout.
Exercise
In the code above, what happens if you replace repulsion with zeros and keep only the attraction term? Which of the two forces prevents the layout from collapsing?
Show answer
With no repulsion, the only force pulls neighbours together. The gradient steps shrink every connected group toward one point, and since the k-NN graph links most points into connected components, the layout collapses into a few dots or one. Repulsion acts on all pairs and is the force that prevents the collapse. It spreads the points out and leaves gaps between clusters.
Exercise
Point A lists B among its 10 nearest neighbours, but B does not list A. Why does the code take np.maximum(P, P.T), and what would (P + P.T) / 2 change?
Show answer
The loss should treat the pair as one similarity, so P must be symmetric. With np.maximum, the pair keeps full weight if either point lists the other. Averaging gives a one-way edge half weight, so those edges attract more weakly than mutual neighbours. Both choices give a symmetric P and both are used in practice. The difference matters only for the relative strength of one-sided edges.