Sub topic 16
Reading embeddings without fooling yourself
This chapter assumes you can run t-SNE and UMAP in scikit-learn and umap-learn, and that you know what perplexity, n_neighbors and min_dist control. It covers what a 2-D embedding supports as evidence and what it doesn't, using small experiments you can run.
What an embedding preserves
Both t-SNE and UMAP optimise for local neighbourhoods. A point's nearest neighbours in the original space should stay near it in the plot. Everything else is a side effect of the optimiser, not a measurement.
| Visual feature | Reliable? | Why |
|---|---|---|
| A point's immediate neighbours | Mostly | This is what the objective rewards. |
| Tight, well-separated groups | Often, but check | Can also arise from noise or low perplexity. |
| Cluster size on the page | No | Density is normalised away. |
| Distance between clusters | No | Global layout is weakly constrained. |
| Cluster shape | Weak | Depends on parameters and seed. |
| Axis values | No | The axes have no meaning. |
Cluster sizes carry no information
t-SNE picks a bandwidth for each point so that every neighbourhood has the same perplexity. A dense cluster is therefore stretched and a sparse one is shrunk. UMAP does something similar by normalising distances to each point's nearest neighbour. The result is that cluster area says almost nothing about the original spread.
This experiment makes two groups with very different spreads and measures their radii before and after embedding.
import numpy as np
from sklearn.manifold import TSNE
rng = np.random.default_rng(0)
tight = rng.normal(0.0, 1.0, size=(500, 20))
loose = rng.normal(0.0, 5.0, size=(500, 20)) + 40.0
X = np.vstack([tight, loose])
labels = np.array([0] * 500 + [1] * 500)
Z = TSNE(perplexity=30, init="pca", learning_rate="auto",
random_state=0).fit_transform(X)
for k, name in [(0, "tight"), (1, "loose")]:
r_orig = np.linalg.norm(X[labels == k] - X[labels == k].mean(0), axis=1).mean()
r_emb = np.linalg.norm(Z[labels == k] - Z[labels == k].mean(0), axis=1).mean()
print(f"{name}: original radius {r_orig:6.2f}, embedded radius {r_emb:6.2f}")The original radii differ by about a factor of five. The embedded radii will be much closer to each other. The scale of the output also depends on the optimiser, so compare ratios, not absolute numbers.
Distances between clusters are not trustworthy
Two clusters that are far apart on the page may be close in the original space, and the reverse. t-SNE's repulsion pushes groups apart until the gaps are visible, and the gap width reflects optimisation dynamics. UMAP keeps somewhat more global structure than t-SNE, especially with a PCA or spectral initialisation. That is a tendency, not a guarantee.
Two practical rules follow:
- Don't say "A is more similar to B than to C" because of plot distance. Compute the distance in the original space, for example between cluster centroids.
- If global arrangement matters, initialise from PCA, and run several seeds to see whether the arrangement changes.
Spurious clusters from noise
Neighbour embeddings can find structure in data that has none. With low perplexity, random Gaussian noise often breaks into small clumps and filaments, because each point's tiny neighbourhood is treated as meaningful.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
rng = np.random.default_rng(0)
X = rng.normal(size=(1000, 50)) # pure noise, no clusters
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for ax, perp in zip(axes, [5, 30, 100]):
Z = TSNE(perplexity=perp, init="pca", learning_rate="auto",
random_state=0).fit_transform(X)
ax.scatter(Z[:, 0], Z[:, 1], s=5)
ax.set_title(f"noise, perplexity = {perp}")
plt.show()Expect visible lumps at perplexity 5 and a smoother blob at 100. Keep this as a control. Before you believe a cluster in real data, embed a noise or shuffled version of that data with the same settings and see what the method invents by itself. Shuffling each feature column independently destroys the relationships between features but keeps each feature's distribution, which makes a good null.
UMAP shows the same behaviour with a small n_neighbors and a small min_dist. A small min_dist packs points into tight islands that look like clusters.
The opposite error: merged or split structure
Parameters can also hide real structure.
- Perplexity too high, or
n_neighborstoo large: small real groups are absorbed into bigger ones. - Perplexity too low, or
n_neighborstoo small: one real group fragments into several pieces. A continuous trajectory, such as a developmental path, can be cut into disconnected islands. - Early stopping or too few iterations: t-SNE has not converged and the layout is still dominated by the initial state.
Continuous data is especially easy to misread. A curve in the original space can turn into separate blobs, so the absence of a visible bridge isn't evidence that no bridge exists.
A decision flow for any plot
Quantify the stability
Visual comparison is subjective. Trustworthiness measures how many of a point's embedded neighbours are true neighbours in the original space, with values from 0 to 1. This code compares seeds.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
X, y = load_digits(return_X_y=True)
for seed in [0, 1, 2]:
Z = TSNE(perplexity=30, init="pca", learning_rate="auto",
random_state=seed).fit_transform(X)
t = trustworthiness(X, Z, n_neighbors=10)
print(f"seed {seed}: trustworthiness = {t:.3f}")With init="pca" the seeds differ only in optimisation noise, so the scores are close. Large differences mean the embedding is unstable. Trustworthiness only checks that embedded neighbours are real. It doesn't check that real neighbours stayed together, so it can't detect a cluster that was torn apart.
Colouring and annotation pitfalls
- Labels can mislead as evidence. If points of one class form one blob, that supports the class being separable. If one class splits into two blobs, look for a hidden variable such as a batch, a sensor or a preprocessing difference.
- Overplotting hides density. With tens of thousands of points, use a small marker size and transparency (
alpha), because overlap makes sparse regions look as important as dense ones. - Scaling affects everything. An unscaled feature with a large range dominates Euclidean distance, so the plot reflects that feature. Standardise first, then compare.
- Reuse the same fit. Don't fit separate t-SNE maps to two subsets and compare positions. The coordinate systems are unrelated.
Exercise
A colleague shows a UMAP plot with three clusters. Cluster A is large, B is small, and A is far from both B and C, which sit next to each other. They conclude that A is the most diverse group and the least similar to the others. Which parts of this conclusion are unsupported, and what would you run to test each?
Show answer
Cluster size on the page does not show diversity, and the distance of A from B and C does not show dissimilarity. Both are artefacts of density normalisation and weakly constrained global layout. To test diversity, compute the within-group spread in the original (standardised) space, such as mean distance to the centroid. To test similarity, compute distances between centroids, or between nearest-neighbour sets, in the original space. Also rerun with several seeds and several n_neighbors values to check that the three-cluster structure and the layout hold, and embed a shuffled-feature control to see whether similar clusters appear from noise.
Exercise
You embed 2,000 random Gaussian vectors with t-SNE at perplexity 5 and see about 30 small clusters. Does this indicate 30 groups? What single change to the experiment tells you more?
Show answer
No. Low perplexity makes neighbourhoods tiny, and noise forms clumps. Rerunning at higher perplexity, such as 30 and 100, shows the clumps merge into one blob, which means they were not stable groups. The cleaner comparison is to run the same settings on a noise control built from your real data, such as shuffling each column independently, and see whether it produces comparable clusters.