Sub topic 17
Measuring embedding quality
This chapter assumes you can run t-SNE and UMAP on the digits data, as in the earlier chapters. You should also know that a scikit-learn embedding is a NumPy array with one row per point. The goal here is to replace "this plot looks good" with numbers you can compare across methods, parameters and seeds.
Why look at a number at all
A 2-D plot is easy to over-read. Two settings can both give tidy clusters while keeping very different amounts of the original neighbourhood structure. A metric does not tell you whether the plot is true. It gives you one repeatable measurement of one property. Used with the plot, it helps you choose parameters and spot a run that went wrong.
Neighbour-embedding methods promise to keep local neighbourhoods. The most useful metrics therefore ask a direct question: are the points near each other in the original space still near each other in the embedding, and the reverse?
Trustworthiness: no false neighbours
Trustworthiness checks whether the embedding invented neighbours. Fix a number k. For each point, take its k nearest neighbours in the embedding. Some of them may not be among its k nearest neighbours in the original space. Each of these false neighbours is penalised by how far down the original-space ranking it actually sits. Penalties are summed over all points and rescaled:
T(k) = 1 − 2 / (n·k·(2n − 3k − 1)) · Σᵢ Σⱼ∈Uᵢ(k) (r(i, j) − k)
Here Uᵢ(k) is the set of false neighbours of point i, and r(i, j) is the rank of point j among the neighbours of i in the original space. The score lies between 0 and 1. A value of 1 means no point has a false neighbour.
Continuity: no lost neighbours
Continuity asks the reverse question. Which true neighbours were torn apart? It uses the same formula with the two spaces swapped. scikit-learn has no separate function for it, but swapping the arguments gives the same result:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
X, y = load_digits(return_X_y=True)
rng = np.random.default_rng(0)
embeddings = {
"random": rng.normal(size=(X.shape[0], 2)),
"PCA": PCA(n_components=2, random_state=0).fit_transform(X),
"t-SNE": TSNE(init="pca", learning_rate="auto",
random_state=0).fit_transform(X),
}
for name, Z in embeddings.items():
trust = trustworthiness(X, Z, n_neighbors=10)
cont = trustworthiness(Z, X, n_neighbors=10) # swapped = continuity
print(f"{name:7s} trustworthiness={trust:.3f} continuity={cont:.3f}")The random embedding is a floor. Because it places points with no regard for the data, it scores near 0.5. PCA should land clearly above that. t-SNE should land close to 1 on this dataset. If your embedding scores near the random one, something is wrong with the preprocessing or the run.
A callout on reading the two scores together:
Using the score to compare settings
The score is most useful for comparing runs on the same data with the same k. This loop sweeps perplexity and repeats each setting over three seeds:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
X, y = load_digits(return_X_y=True)
for perp in [5, 30, 100]:
scores = []
for seed in [0, 1, 2]:
Z = TSNE(perplexity=perp, init="pca", learning_rate="auto",
random_state=seed).fit_transform(X)
scores.append(trustworthiness(X, Z, n_neighbors=10))
print(f"perplexity={perp:3d} mean={np.mean(scores):.3f} "
f"std={np.std(scores):.4f}")Look at the standard deviation as well as the mean. With init="pca" the starting layout is the same for every seed, so the spread is small. With init="random" it can be larger. If two settings differ by less than the seed-to-seed spread, the data gives you no reason to prefer either one.
The same loop works for UMAP. Vary n_neighbors and min_dist, then score each result with trustworthiness(X, Z, n_neighbors=10).
An evaluation workflow
Limits and common errors
- The metric depends on k. Trustworthiness at
k=5andk=50measure different scales. Fixkbefore you compare, and state it when you report a score. Scores from differentkvalues, or from different datasets, are not comparable. - Local only. Both scores look at neighbourhoods. They say nothing about whether the distances between clusters, or the cluster sizes, mean anything. The pitfalls from the previous chapter still apply to a plot with a perfect score.
- Cost grows with n².
trustworthinesscomputes full pairwise distances, so memory and time grow quadratically. On a large dataset, score a random subsample of points. Subsampling the data before embedding changes the neighbours, so subsample rows of the score input and the embedding together. - Use the same input in the same metric. Pass the same array that you gave the embedding method. If you standardised or ran PCA first, score against that array. If UMAP used
metric="cosine", passmetric="cosine"totrustworthinessso both sides use the same notion of distance. - Higher is not always better. A very high score at small
kcan come from a layout that fragments the data into many tiny clusters. Check continuity and the plot before choosing it. - Labels are a separate check. Checking whether classes separate in the embedding measures how well the labels fit the geometry. It does not measure whether the embedding is faithful. Keep the two ideas apart.
Choosing what to report
For a short report on an embedding, include the following:
- The method and its parameters, including
perplexityorn_neighborsandmin_dist. - The initialisation and the seeds used.
- Trustworthiness and continuity at one stated
k, with the random-embedding baseline. - The spread across at least three seeds.
A reader can then reproduce the result and see how far the scores can be trusted.
Exercise
You embed 5,000 points with UMAP using metric="cosine". You then call trustworthiness(X, Z, n_neighbors=10) and get 0.91. Name two problems with this evaluation and say how to fix each.
Show answer
First, the metric differs. UMAP built its neighbour graph with cosine distance, but trustworthiness defaults to Euclidean distance on X. Pass metric="cosine" so the original-space neighbours match the ones UMAP used. Second, there is only one number from one run. Trustworthiness alone ignores lost neighbours, and a single seed gives no estimate of spread. Also compute continuity with the arguments swapped, repeat over several seeds, and compare against a random-embedding baseline at the same k.
Exercise
Two perplexity settings give mean trustworthiness of 0.981 and 0.984 across three seeds, and the standard deviation across seeds is 0.004. What should you conclude?
Show answer
The difference of 0.003 is smaller than the seed-to-seed spread, so the data does not show that one setting is better. Choose between them using other evidence, such as continuity, the plot, or the stability of the clusters you care about.