Build a t-SNE and UMAP Visualization Pipeline for Embedding Analysis


classical-ml nlp feature-engineering model-evaluation
View full code for this problem

ML Problem & Solution

Embedding Maps with t-SNE and UMAP

A 2D map is a lossy compression of 384 dimensions, and the question is which of your claims survives it.

⏱ 26 min read 📐 Intermediate 🧩 Classical ML

A support organisation has 1.4 million tickets from the last 14 months, each routed into one of 62 queues by a rules engine that nobody fully understands any more, and a director who wants two things. She wants to see an emerging issue before the weekly volume report shows it, and she wants to consolidate 62 queues down to roughly 30 by merging the ones that are really the same problem. Both requests are asking for the same artifact: a picture of the ticket space.

The embeddings already exist. Every ticket’s first customer message runs through all-MiniLM-L6-v2 and lands as a 384-dimensional unit vector, because the same vectors feed the semantic search over resolved tickets. So the problem reduces to putting 1.4 million points from a 384-dimensional sphere onto a screen, which is two dimensions, which means throwing away 382 of them.

The naive approach is a PCA scatter plot, and it fails in a way that is at least honest: the first two principal components explain 9.1% of the variance and the plot is one undifferentiated blob with a faint smear toward the corner where the automated monitoring alerts live. Nothing is readable. Reach for TSNE() with its defaults instead and the failure inverts, which is much more dangerous, because now the picture is beautiful. There are fourteen crisp islands with clean gaps between them, the colours by queue look meaningfully organised, and everyone in the room starts reading conclusions off it. Three of those conclusions went into a roadmap document:

  1. Billing-Disputes and Refunds sit at opposite ends of the map, so they are genuinely different problems and should stay separate queues. In the 384-dimensional space, those two queue centroids are the third-closest of the 1,891 queue pairs.
  2. The Password-Reset island is small, so it is low volume and can be deprioritised. It is 11% of all ticket volume. It is small on the map because its tickets are nearly identical to each other, and a t-SNE island’s area reflects local density, not population.
  3. API-Errors visibly contains four sub-clusters, so the queue should be split four ways. Re-running with ten different random seeds, three of those four sub-clusters appeared in zero of ten runs.

None of those three errors is a bug. Each one is a correct reading of a picture that does not encode the thing being read off it. A 2D embedding is a lossy compression, and the engineering problem is not making a prettier picture, it is knowing which class of claim survives the compression. The analogy that makes this concrete: a subway map is wildly wrong about distance and direction and completely right about adjacency, which is why nobody plans a walking route on one and everybody plans a transfer on one. t-SNE and UMAP produce subway maps. They are excellent about who is next to whom and untrustworthy about everything else, and the whole discipline is refusing to read the parts they get wrong.

There is a second constraint that turns out to decide the method choice before any of the quality metrics do. The director wants this refreshed weekly. Around 40,000 new tickets arrive each week and have to be placed on the map, and the map has to stay recognisable so that a position someone remembers from last week still means something. t-SNE has no transform method, and that is not an oversight in scikit-learn: the algorithm is defined as an optimisation over a fixed point set, so a new point has no position until you rerun the whole thing, and rerunning the whole thing moves every old point.

Given 1.4 million L2-normalised 384-dimensional ticket embeddings, produce a 2D layout whose local neighbourhoods agree with the 384-dimensional neighbourhoods, optimising trustworthiness and continuity at k = 50 plus the fraction of claims read off the map that hold in the original space, under a weekly refresh that must place new points without displacing old ones.

Framing the Problem

This is dimensionality reduction for visual inspection, and that puts it in an unusual methodological position: there is no target variable, no train/test split, no held-out score, and for t-SNE no function from input space to output space at all. Every habit from supervised modelling has to be replaced with something.

There is no label to predict. What stands in for a target is the 384-dimensional k-nearest-neighbour graph, which is the thing the map is supposed to be a picture of. Concretely, for each of the 1.4 million points we take its 50 nearest neighbours under cosine distance in the original space, and the map is good to the extent that those same 50 points are near it on the screen. The queue labels exist but they are evidence rather than ground truth: the whole reason for the project is that the routing taxonomy is suspect, so a map that reproduces the queues perfectly would be a map that has learned nothing the rules engine did not already encode.

Constraints, in the order that they eliminated options:

  • Out-of-sample placement. 40,000 new tickets a week must be placed into the existing layout. This is a hard requirement and it eliminates t-SNE from the serving path outright.
  • Layout stability across refreshes. A point whose embedding has not changed must not move appreciably between weekly runs, or the artifact is unusable as a shared reference.
  • Stability under perturbation. A feature of the picture that changes when the random seed or the input sample changes is not a feature of the data, and there has to be a mechanical way to tell those apart.
  • Fit budget. Under 2 hours on one 32-core machine for a full refit, which is generous but rules out anything with quadratic memory at N = 1.1 million.
  • No GPU. The embedding service has the GPUs. This pipeline runs on CPU, which changes the practical ranking of implementations substantially.
Metric That Matters

The success metrics are **trustworthiness at k** and **continuity at k**, and they must be reported as a pair because they measure opposite errors and the methods here trade one for the other. Trustworthiness asks: of the points that appear near each other on the map, how many are genuinely near in 384 dimensions? It penalises **false neighbours**, the pairs the map invents. Continuity asks: of the points that are genuinely near in 384 dimensions, how many stayed near on the map? It penalises **missed neighbours**, the neighbourhoods the map tore apart. t-SNE minimises an asymmetric KL divergence that punishes putting far-apart points together far more than it punishes splitting close points up, so it buys trustworthiness with continuity, and a t-SNE map can sit at 0.91 trustworthiness while having shredded a real neighbourhood into three islands that a reader will then interpret as three distinct issue types. The guardrail metric is **stability**, measured as the mean per-point Jaccard overlap of 2D k-nearest-neighbour sets across ten runs, and the operating rule is that no claim gets read off a region whose stability is below 0.6. What "ten runs" means turns out to differ by method, for a reason worth its own paragraph later.

Out of scope: clustering the embeddings, which is a different problem with different tools and its own post. The 2D coordinates are never used as features for a downstream model, and the reason is in the pitfalls table. And nothing here tries to improve the embeddings themselves; the 384-dimensional representation is a fixed input.

Data and Features

The input is 1,412,000 rows by 384 float32 columns, which is 2.15 GB in memory, plus a small metadata frame carrying ticket_id, created_at, queue_id, resolution_minutes and product_area. The embeddings come from all-MiniLM-L6-v2 over the ticket’s first customer message truncated at 256 tokens, and the vectors arrive already L2-normalised, which matters more than it sounds: on unit vectors, Euclidean distance is a monotone function of cosine distance, so metric="euclidean" and metric="cosine" produce identical neighbour orderings and the Euclidean path is roughly 3x faster in every implementation here.

“Feature engineering” for an embedding map means four things, and three of them are subtraction.

Strip the boilerplate before embedding, not after. Support emails carry signature blocks, legal footers, and quoted reply chains. Before stripping, a PCA of the raw embeddings had a component explaining 22% of variance that turned out to be a signature-block direction, and the dominant axis of the first t-SNE map was, functionally, which email client the customer used. This is the single highest-leverage preprocessing step and it happens upstream of everything in this post.

Collapse duplicates and near-duplicates, and understand why they break the map specifically. 19% of tickets are templated: automated monitoring alerts, bot-filed forms, and a self-service flow that submits a fixed body with one variable field. After normalisation, 41,000 tickets are byte-identical to at least one other ticket. Both t-SNE and UMAP build a neighbourhood graph and then optimise an attraction-repulsion objective on it, and a group of 900 identical points is pathological for that construction: at perplexity 30, every one of those 900 points has its entire neighbourhood at distance zero, the conditional probabilities become degenerate, and the group’s mutual attraction dominates the layout in its region. Measured on this data, removing exact duplicates and collapsing near-duplicates at cosine similarity above 0.98 into a single representative with a weight moved trustworthiness at 50 from 0.79 to 0.86, and it removed 6 of the 14 apparent islands in the original picture. Six of the fourteen “issue clusters” the team had been discussing were template groups.

Reduce to 50 dimensions with PCA before the nonlinear step. This is standard advice and the reasons are worth separating. It denoises, since the tail components of a sentence-embedding PCA are dominated by tokenisation artifacts. It makes the neighbour search dramatically cheaper, which is most of the wall-clock saving. And it barely costs anything in neighbourhood structure: trustworthiness at 50 of the 50-dimensional PCA projection against the full 384 dimensions is 0.981, so the neighbour graph the nonlinear method sees is almost the one it would have seen anyway.

# The preprocessing that decides the map before any method is chosen: strip,
# deduplicate with weights, then PCA to 50. Each step is subtraction, and each
# one moved the quality metrics more than any parameter later in this post.
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.neighbors import NearestNeighbors

def collapse_near_duplicates(X: np.ndarray, threshold: float = 0.98,
                             n_probe: int = 12) -> tuple[np.ndarray, np.ndarray]:
    """Group points at cosine similarity above threshold, keep one per group.

    Returns (representative_index, weight). The weight matters: a template
    group of 900 tickets is one point on the map and 900 tickets in the
    volume report, and conflating those two facts is exactly how the
    Password-Reset island got read as low volume.
    """
    nn = NearestNeighbors(n_neighbors=n_probe, metric="euclidean").fit(X)
    dist, idx = nn.kneighbors(X)
    # On unit vectors, cosine similarity 0.98 is Euclidean distance sqrt(0.04).
    radius = np.sqrt(2.0 * (1.0 - threshold))
    parent = np.arange(len(X))

    def find(a: int) -> int:
        while parent[a] != a:
            parent[a] = parent[parent[a]]
            a = parent[a]
        return a

    for i in range(len(X)):
        for d, j in zip(dist[i, 1:], idx[i, 1:]):
            if d <= radius:
                ri, rj = find(i), find(int(j))
                if ri != rj:
                    parent[max(ri, rj)] = min(ri, rj)
    groups = np.array([find(i) for i in range(len(X))])
    reps, weights = np.unique(groups, return_counts=True)
    return reps, weights

def prepare(X: np.ndarray, n_components: int = 50,
            seed: int = 17) -> tuple[np.ndarray, np.ndarray, PCA]:
    """Deduplicate, then PCA. Fit the PCA on the deduplicated set so that a
    template group of 900 identical vectors does not get 900 votes in the
    covariance estimate."""
    reps, weights = collapse_near_duplicates(X)
    Xd = X[reps]
    pca = PCA(n_components=n_components, svd_solver="randomized",
              random_state=seed).fit(Xd)
    return pca.transform(Xd), weights, pca

The leakage that applies when there is no train/test split

The usual leakage framing does not transfer, because every point is in the fit set by construction. Three things still leak, and all three have produced a wrong conclusion on this project.

Label leakage into the layout. The tempting move, when the map looks unstructured, is to append the queue one-hot or a normalised resolution_minutes to the feature vector before reducing. Do that and the map will show clean queue separation, because you put the queue in the input. Every claim read off it about whether the queues are well-separated is then circular. We did this once with a 0.3-weighted queue one-hot, got a gorgeous map, and caught it only when the queue-consolidation recommendation came back saying all 62 queues were well-separated and should be kept, which was the opposite of every other piece of evidence.

Evaluation-set leakage through the deduplication boundary. Trustworthiness compares 2D neighbourhoods against reference 384-dimensional neighbourhoods, and the two have to be computed on the same point set. Computing the reference neighbours on the deduplicated set while laying out the full set, or the reverse, inflates the number: our first trustworthiness figure was 0.93 and dropped to 0.86 when the sets were reconciled. The duplicate groups are trivially easy neighbourhoods to preserve, so whichever side has more of them looks better.

Temporal leakage through the anchor set. For the weekly refresh, UMAP is fitted once on an anchor sample and new tickets are transformed into that layout. If the anchor sample is drawn from the whole 14 months including the most recent week, the evaluation of “how well does transform place new tickets” is measured on tickets whose neighbours were in the fit. Draw the anchor from the first 13 months and evaluate placement on the last, and out-of-sample trustworthiness at 50 falls from 0.88 to 0.81. The 0.81 is the honest number and it is the one that predicts what happens in week 15.

# The split that a visualisation pipeline does need, which is not train/test
# but anchor/arrival. The anchor defines the coordinate system; arrivals are
# placed into it and are the only honest estimate of next week's quality.
import numpy as np
import pandas as pd

def anchor_arrival_split(meta: pd.DataFrame, anchor_end: str,
                         anchor_size: int = 400_000,
                         seed: int = 17) -> tuple[np.ndarray, np.ndarray]:
    """Anchor: a stratified sample from before anchor_end. Arrivals: everything
    after. Stratify by (month, queue_id) so a queue that only existed for the
    last quarter is not silently absent from the coordinate system."""
    rng = np.random.default_rng(seed)
    created = pd.to_datetime(meta["created_at"])
    before = np.flatnonzero(created < pd.Timestamp(anchor_end))
    after = np.flatnonzero(created >= pd.Timestamp(anchor_end))
    strata = (created.dt.to_period("M").astype(str) + "|"
              + meta["queue_id"].astype(str)).to_numpy()
    take_per = max(1, anchor_size // max(1, len(np.unique(strata[before]))))
    keep = []
    for s in np.unique(strata[before]):
        pool = before[strata[before] == s]
        keep.append(rng.choice(pool, size=min(take_per, len(pool)),
                               replace=False))
    return np.concatenate(keep), after
Key Insight

Six of the fourteen islands on the first map were template groups, and that is the general shape of the problem rather than a quirk of this dataset. Both methods optimise an objective built from a neighbourhood graph, and duplicate mass is the one input that objective cannot handle gracefully: identical points are each other's entire neighbourhood at distance zero, so they form a region of infinite density that the repulsion term has to be balanced against. A map dominated by duplicates is not a map of the semantic space, it is a map of which templates your intake forms generate. The useful reframing is that deduplication is not data cleaning here, it is the decision about what the map is a map of, and keeping the collapsed weights alongside is what lets you answer volume questions without reading them off the picture.

The Naive Baseline

Two baselines, because they fail in opposite directions and the pairing is the point.

# Both baselines. PCA is the honest failure: unreadable and it tells you so.
# Default TSNE is the dangerous one: readable, and wrong in three specific ways.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

def pca_baseline(X50: np.ndarray) -> np.ndarray:
    """Linear projection to 2D. A hard ceiling: two components of a
    sentence-embedding PCA carry about 9% of the variance."""
    return PCA(n_components=2, random_state=17).fit_transform(X50)

def tsne_default_baseline(X50: np.ndarray, seed: int = 17) -> np.ndarray:
    """What TSNE() does if you leave it alone. Note what is NOT set:
    init defaults to 'pca' in sklearn 1.2+ but to 'random' in most tutorials
    and in every other implementation, learning_rate='auto' is N/12 only
    since 1.2, and perplexity 30 is a neighbourhood size claim nobody made."""
    return TSNE(n_components=2, perplexity=30.0, init="random",
                learning_rate=200.0, max_iter=1000,
                random_state=seed).fit_transform(X50)

On a 200,000-point stratified subsample, which is what fits in a Barnes-Hut t-SNE run inside the budget:

  • PCA to 2D: trustworthiness at 50 0.61, continuity at 50 0.72, k-NN queue agreement 0.38 against a 384-dimensional ceiling of 0.71, pairwise-distance Spearman 0.81, resample stability 0.94. It preserves global geometry well and local neighbourhoods badly, which is exactly backwards for the questions being asked.
  • Default t-SNE: trustworthiness 0.79, continuity 0.68, k-NN queue agreement 0.55, pairwise-distance Spearman 0.31, seed stability 0.44, resample stability 0.41.

Read the two Spearman figures together, because they contain the whole argument. PCA’s 0.81 means that if two points are far apart on the PCA plot, they are probably far apart in 384 dimensions. t-SNE’s 0.31 means that relationship has essentially been discarded. The Billing-Disputes and Refunds error at the top of this post is not a subtle statistical artifact; it is the direct consequence of reading a distance off a layout whose distance correlation with the source space is 0.31.

The 0.44 seed stability is the other half. Less than half of a typical point’s 50 map-neighbours survive a change of random seed, which means roughly half of every local structure a reader perceives is an artifact of one particular initialisation.

Key Insight

The default t-SNE map scores worse than PCA on continuity (0.68 against 0.72) and far worse on distance correlation (0.31 against 0.81), and better only on trustworthiness (0.79 against 0.61). That is not a bad result, it is the method working as designed: t-SNE is a trustworthiness maximiser and it is willing to spend everything else to get there. The problem is that the picture does not carry that caveat. A PCA plot that looks like a blob communicates its own uncertainty, and a t-SNE plot with fourteen crisp islands communicates a confidence the underlying optimisation never claimed. Every hour spent on parameters in the next section buys less than the ten minutes spent teaching the three people who read the map that island area is density and island distance is nothing.

The Solution

Pipeline from 1.4 million 384-dimensional ticket embeddings through boilerplate stripping and near-duplicate collapsing with weights, PCA to 50 dimensions, a shared 50-nearest-neighbour graph feeding both t-SNE with PCA initialisation and learning rate N over 12 and UMAP with 50 neighbours and cosine metric, a ten-resample stability gate that marks which regions may be read, a trustworthiness and continuity quality gate, and UMAP transform placing 40,000 weekly arrivals into the frozen layout

Three sub-problems, and the order matters because the first one changes the answer to the other two.

Initialisation, which decides whether global structure exists at all

The textbook framing is that t-SNE preserves local structure and discards global structure. That framing is close to wrong, and Kobak and Berens showed why in their 2019 Nature Communications paper on t-SNE for single-cell transcriptomics: most of the global-structure loss comes from random initialisation, not from the objective. With a random start, the layout’s large-scale arrangement is determined by which points happened to land near each other in the first iteration, and the attraction-repulsion dynamics then lock that arrangement in. With a PCA initialisation, the large-scale arrangement starts out carrying the linear structure of the data, and the local optimisation refines it without destroying it.

The effect here is the single largest one in this post. Switching init="random" to init="pca" with every other parameter untouched moved pairwise-distance Spearman from 0.31 to 0.54 and resample stability from 0.41 to 0.66, and it costs nothing: it is one string and the PCA is already computed. It has a second effect that is easy to mistake for a third win: a PCA initialisation is a deterministic function of the input, and t-SNE’s optimisation is plain gradient descent, so the whole run becomes deterministic and two seeds return bit-identical layouts. That is genuinely useful for reproducibility and it quietly breaks the stability gate, which is the subject of the fourth subsection below.

# Initialisation and learning rate, which together are worth more than
# perplexity. Both defaults in older sklearn and in most tutorials are wrong
# for N above about 50,000.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE

def pca_init(X50: np.ndarray, seed: int = 17) -> np.ndarray:
    """Scale the PCA initialisation so its standard deviation is 1e-4.

    t-SNE's early phase assumes a tight initial configuration; a PCA
    initialisation at its natural scale starts the optimisation too spread out
    for the attraction term to do anything and the result keeps the linear
    projection almost unchanged.
    """
    Y = PCA(n_components=2, random_state=seed).fit_transform(X50)
    return (Y / Y[:, 0].std()) * 1e-4

def tsne_tuned(X50: np.ndarray, perplexity: float = 50.0,
               seed: int = 17) -> np.ndarray:
    """learning_rate = N / 12 is the Belkina et al 2019 result. At N = 200,000
    the historical default of 200 leaves the optimisation unconverged after
    1,000 iterations: points are still in a single dense ball because the
    gradient steps are three orders of magnitude too small for the number of
    repulsion terms each point receives."""
    n = len(X50)
    return TSNE(n_components=2, perplexity=perplexity,
                init=pca_init(X50, seed), learning_rate=max(n / 12.0, 50.0),
                early_exaggeration=12.0, max_iter=1000,
                n_iter_without_progress=300, random_state=seed,
                method="barnes_hut", angle=0.5).fit_transform(X50)

The learning rate is the second free win and it is a scale bug rather than a tuning choice. Each point’s gradient has one attraction term per neighbour and one repulsion term per other point, so the magnitude of the update needed to move a point grows with N while the historical default of 200 does not. Belkina and colleagues, also in Nature Communications in 2019, worked out that learning_rate = N / 12 reproduces the convergence behaviour that 200 gives at small N. At N = 200,000 that is 16,667, and the difference is not subtle: with learning_rate=200 the run finished 1,000 iterations with a KL divergence of 4.81 and a visibly unresolved central mass, and with 16,667 it finished at 1.94. scikit-learn 1.2 changed learning_rate="auto" to implement max(N / 12, 50), which means a pipeline pinned to an older version is silently running the broken configuration.

Perplexity is a claim about neighbourhood size, and the sweep is the deliverable

Perplexity sets the effective number of neighbours each point’s conditional distribution is spread over. Low perplexity means each point only feels a handful of neighbours, which fragments; high perplexity means each point averages over a large neighbourhood, which smooths.

The failure mode at low perplexity is the one that has caused the most damage in practice, and it is best demonstrated on data with no structure at all. Wattenberg, Viegas and Johnson made this the centrepiece of their 2016 Distill article: t-SNE will produce apparent clusters in pure noise. We reproduced it as a standing unit test, because a synthetic control is the only way to calibrate your own eye.

# The perplexity control experiment, kept as a test rather than a one-off.
# A single isotropic Gaussian has exactly one cluster. Count how many the
# method draws at each perplexity, and you have calibrated your own eye.
import numpy as np
from sklearn.manifold import TSNE
from sklearn.cluster import DBSCAN

def shatter_count(n: int = 5000, d: int = 50, perplexity: float = 5.0,
                  seed: int = 17) -> int:
    """Apparent cluster count in a 2D map of ONE Gaussian blob.

    Any answer above 1 is a structure the method invented. At perplexity 5
    this returns 7 on our runs; at perplexity 200 it returns 1.
    """
    rng = np.random.default_rng(seed)
    X = rng.normal(size=(n, d))
    Y = TSNE(n_components=2, perplexity=perplexity, init="pca",
             learning_rate=max(n / 12.0, 50.0),
             random_state=seed).fit_transform(X)
    Y = (Y - Y.mean(0)) / Y.std(0)
    labels = DBSCAN(eps=0.30, min_samples=25).fit_predict(Y)
    return int(len({int(l) for l in labels if l >= 0}))

On the ticket data we ran perplexity at 5, 15, 30, 50, 100 and 200 and adopted a rule rather than a value: no cluster is reported unless it survives a 5x range of perplexity. At perplexity 15 the map showed 4 sub-clusters inside API-Errors; at perplexity 50 there were 2; at 200 there was 1 with a visible density gradient. The two that survived from 15 to 100 turned out to be genuine, an authentication-token expiry issue and a rate-limit misconfiguration, and they became separate runbooks. The other two were noise and they had been in the roadmap document.

The value we settled on is 50, which is high by the usual advice. The reason is specific to N: perplexity is an absolute neighbourhood size, not a fraction, so perplexity 30 at N = 1.1 million means each point’s distribution covers 0.003% of the data, and the resulting map is essentially all local detail with no mid-scale structure. Kobak and Berens recommend scaling it with N for exactly this reason.

Common Pitfall

Tuning perplexity until the picture looks clean. This is the most common workflow in practice and it is a search for the parameter value that produces the most convincing artifact, which is the opposite of what you want. Low perplexity always produces crisper separation, because fragmenting the data is how the objective is minimised when each point only feels a few neighbours, so "tune until it looks good" converges reliably on the configuration that invents the most structure. Our own first pass landed on perplexity 12 for precisely this reason, and it scored 0.82 trustworthiness against 0.91 at perplexity 50, with resample stability of 0.48 against 0.71. The discipline is to fix the perplexity by a rule that does not consult the picture, scale it with N, and then treat the sweep as a filter on claims rather than a search for a value.

UMAP, and the one capability t-SNE does not have

UMAP builds a weighted k-nearest-neighbour graph using a per-point local distance scale, symmetrises it into a fuzzy simplicial set, and then optimises a cross-entropy between that graph and a similarly constructed graph in 2D, using negative sampling for the repulsion term. The mechanism analogy: t-SNE hands every point the same budget of attention to distribute among its neighbours, while UMAP lets each point set its own sense of what “near” means before any of the attention is distributed, which is why it handles regions of very different density with one parameter setting.

Two parameters and one method matter.

# UMAP. n_neighbors is the local-global dial, min_dist is purely how tightly
# points pack and changes nothing about the structure while changing a great
# deal about what a reader infers from it, and transform is the reason this
# method and not t-SNE is on the serving path.
import numpy as np
import umap

def fit_umap_anchor(X50_anchor: np.ndarray, n_neighbors: int = 50,
                    min_dist: float = 0.1, seed: int = 17) -> umap.UMAP:
    """Fit once on the anchor sample. This object IS the coordinate system and
    it is the artifact to version: reproducing a position from three weeks ago
    means reloading this, not refitting it."""
    return umap.UMAP(n_components=2, n_neighbors=n_neighbors,
                     min_dist=min_dist, metric="euclidean",
                     init="spectral", n_epochs=200, random_state=seed,
                     transform_seed=seed, verbose=False).fit(X50_anchor)

def place_arrivals(model: umap.UMAP, X50_new: np.ndarray) -> np.ndarray:
    """40,000 new tickets placed into the frozen layout. Old points do not
    move, which is the entire requirement that ruled t-SNE out."""
    return model.transform(X50_new)

n_neighbors is the local-global dial and it behaves like perplexity: 15 gives fine detail and fragmentation, 200 gives broad continents and washes out real sub-structure. At 50 the quality metrics peaked here, and unlike perplexity the cost of raising it is close to linear rather than quadratic.

min_dist deserves a warning because it is the parameter most likely to be abused. It controls only how tightly points are allowed to pack in the output, so lowering it from 0.1 to 0.01 produces dramatically tighter, more separated-looking blobs while changing trustworthiness by 0.004. It is a purely aesthetic parameter with a large effect on what a reader concludes, which makes it the most dangerous knob in the pipeline. We fixed it at 0.1 and documented that it was fixed.

transform is why UMAP is on the serving path. Because UMAP learns a fuzzy graph structure and an optimisation target rather than a set of coordinates, a new point can be placed by finding its neighbours among the anchors and optimising only its own position. The measured difference is stark: refitting t-SNE weekly gave a median point displacement of 0.63 of the layout diameter, which is to say the map is unrecognisable week to week, while UMAP transform gave 0.004. transform is also not free of caveats, and the important one is that it cannot discover new structure. A genuinely new issue type with no anchor neighbours lands in whatever gap is nearest its weak attachments, which is why the anchor set is refitted monthly and the arrivals placed weekly.

The stability gate, which is what makes the map admissible as evidence

Everything above improves the map. This is the part that makes it usable, and it is the piece missing from almost every embedding-visualisation pipeline we have seen.

The obvious implementation is to rerun with ten seeds and measure how much of each point’s 2D neighbourhood is the same every time. It is the right idea and, applied naively, it reports the wrong answer in a direction that flatters you. Once the initialisation is deterministic, the whole layout is: t-SNE with init="pca" is gradient descent from a fixed starting point, so ten seeds produce ten bit-identical layouts and the gate reports 1.000 while measuring nothing at all. UMAP is different, because its repulsion term uses stochastic negative sampling, so seed variation is real there. Mixing the two in one table produces the reading that the tuned t-SNE is the most stable configuration in the pipeline, which is exactly backwards.

The fix is to perturb the input rather than the seed. Refit on ten random 80% subsamples and compare neighbourhoods over the points present in all of them, which asks the question anyone actually has: would this structure still be here if I had collected a slightly different sample?

# The stability gate. Perturb the INPUT, not the seed: with a deterministic
# initialisation the seed gate reports 1.000 and tells you nothing.
import numpy as np
from sklearn.neighbors import NearestNeighbors

def neighbour_sets(Y: np.ndarray, k: int = 50) -> np.ndarray:
    nn = NearestNeighbors(n_neighbors=k + 1).fit(Y)
    return nn.kneighbors(Y, return_distance=False)[:, 1:]

def resample_stability(fit_fn, Z: np.ndarray, n_runs: int = 10,
                       frac: float = 0.8, k: int = 50,
                       seed: int = 17) -> np.ndarray:
    """Per-point Jaccard of the 2D k-NN set across refits on 80% subsamples.

    Neighbour sets are mapped back to global row indices so the comparison is
    well defined, and only points present in every run are scored. Procrustes
    alignment is deliberately NOT used: a rotated or mirrored map is harmless
    and aligning first would conflate that with a real change in structure.
    """
    rng = np.random.default_rng(seed)
    picks, sets = [], []
    for r in range(n_runs):
        idx = np.sort(rng.choice(len(Z), int(frac * len(Z)), replace=False))
        local = neighbour_sets(fit_fn(Z[idx], seed + r), k)
        picks.append(idx)
        sets.append({int(idx[i]): {int(idx[j]) for j in local[i]}
                     for i in range(len(idx))})
    shared = set(picks[0].tolist())
    for p in picks[1:]:
        shared &= set(p.tolist())
    out = np.full(len(Z), np.nan)
    for g in sorted(shared):
        acc, pairs = 0.0, 0
        for a in range(n_runs):
            for b in range(a + 1, n_runs):
                sa, sb = sets[a][g], sets[b][g]
                union = len(sa | sb)
                acc += len(sa & sb) / union if union else 1.0
                pairs += 1
        out[g] = acc / pairs if pairs else 1.0
    return out

Ten resamples, per-point Jaccard, and the published map shades any point below 0.6 to grey with a legend that says “not stable, do not read”. On the tuned UMAP layout, 91% of points clear the gate. On the default t-SNE layout, 38% do, and the regions that fail are not randomly distributed: they are the boundaries between islands and the interiors of the small islands, which are precisely the regions people were reading.

Key Insight

The decision that mattered most was `init="pca"`, and it is worth dwelling on because it is free and because the reason it works corrects a piece of folklore. "t-SNE destroys global structure" is treated as a property of the objective, and it is mostly a property of the initialisation: the attraction-repulsion dynamics preserve the large-scale arrangement they are handed, so handing them a random one and observing that the result is globally meaningless is a self-fulfilling experiment. One string moved pairwise-distance Spearman from 0.31 to 0.54 and resample stability from 0.41 to 0.66, which is more than the combined effect of every parameter in the rest of this section. It also changes the character of the artifact: with a random start, two runs of the same data produce two maps that cannot be compared at all, and with a PCA start the run is deterministic, so a position becomes something a team can refer to across runs. That determinism is also the trap in the stability gate, and it is worth keeping the two consequences of one string separate in your head: reproducibility went to exact, and robustness went from 0.41 to 0.66, which is better and nowhere near exact.

Evaluation and Metrics

There is no held-out score. t-SNE has no predict, UMAP’s transform is not a prediction of anything, and no likelihood is available for either. So evaluation is built from three kinds of evidence, and none of them is sufficient alone.

Neighbourhood retention. Trustworthiness and continuity, from Venna and Kaski’s work on neighbourhood-preservation measures. Both compare rank orderings rather than distances, which is the right choice: a map is allowed to be wrong about how far apart two points are and is not allowed to be wrong about which is closer. Trustworthiness at k penalises points that appear in a point’s 2D k-neighbourhood but are ranked far away in the original space, weighted by how far. Continuity is the same quantity with the roles of the two spaces exchanged.

A downstream-task ceiling check. Fit a k-NN classifier for queue_id on the 2D coordinates and compare against the same classifier on the 384-dimensional vectors. The 384-dimensional number is a ceiling, the 2D number is what survived, and the gap is the compression loss expressed in a unit people understand. Note carefully that this is a diagnostic, not a goal: driving it up by putting the queue label in the input is the circularity described earlier.

A claim audit. This is the measurement that actually changed how the artifact was used, and it is not standard practice. We collected 24 concrete claims the ops team read off the maps, each phrased so it could be checked in 384 dimensions: “queue A and queue B overlap heavily”, “this cluster is growing month over month”, “these two sub-groups are distinct”. Then we checked each one against the original space and scored the hit rate.

# The three evaluation layers. Trustworthiness and continuity are rank-based
# and come from sklearn plus a transpose; the claim audit is the one that
# changed behaviour and it needs the original space, not the map.
import numpy as np
from sklearn.manifold import trustworthiness
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
from sklearn.model_selection import cross_val_score
from scipy.stats import spearmanr

def continuity(X: np.ndarray, Y: np.ndarray, k: int = 50) -> float:
    """Continuity is trustworthiness with the two spaces exchanged.

    Reporting only trustworthiness is the standard mistake: t-SNE's KL
    divergence is asymmetric in the direction that buys trustworthiness at
    continuity's expense, so a torn neighbourhood is invisible in the
    trustworthiness number and invisible in the picture.
    """
    return float(trustworthiness(Y, X, n_neighbors=k))

def knn_label_agreement(Z: np.ndarray, labels: np.ndarray, k: int = 50,
                        seed: int = 17) -> float:
    """5-fold CV accuracy of a k-NN classifier on Z. Run on the 2D map and on
    the original space; the gap is the compression loss in a readable unit."""
    clf = KNeighborsClassifier(n_neighbors=k, n_jobs=-1)
    return float(cross_val_score(clf, Z, labels, cv=5, n_jobs=-1).mean())

def distance_correlation(X: np.ndarray, Y: np.ndarray, n_pairs: int = 200_000,
                         seed: int = 17) -> float:
    """Spearman correlation of pairwise distances on a random pair sample.

    This is the number that licenses or forbids reading distance off the map.
    Below about 0.5, any claim of the form 'these two groups are far apart' is
    unsupported, whatever the picture looks like.
    """
    rng = np.random.default_rng(seed)
    i = rng.integers(0, len(X), n_pairs)
    j = rng.integers(0, len(X), n_pairs)
    keep = i != j
    dx = np.linalg.norm(X[i[keep]] - X[j[keep]], axis=1)
    dy = np.linalg.norm(Y[i[keep]] - Y[j[keep]], axis=1)
    return float(spearmanr(dx, dy).statistic)

def cluster_size_distortion(X: np.ndarray, Y: np.ndarray,
                            group: np.ndarray) -> dict:
    """Ratio of each group's 2D spread to its original-space spread.

    If this ratio is not roughly constant across groups, group AREA on the map
    carries no information about group spread, which is the Password-Reset
    error stated as a measurement.
    """
    out = {}
    for g in np.unique(group):
        m = group == g
        if m.sum() < 20:
            continue
        sx = float(np.linalg.norm(X[m] - X[m].mean(0), axis=1).mean())
        sy = float(np.linalg.norm(Y[m] - Y[m].mean(0), axis=1).mean())
        out[str(g)] = sy / sx if sx else float("nan")
    ratios = np.array(list(out.values()))
    return {"per_group": out,
            "spread_ratio_range": float(ratios.max() / ratios.min()),
            "n_groups": int(len(ratios))}

Baseline against solution, 200,000-point stratified subsample, k = 50 throughout, 62 queue labels:

Configuration Trust@50 Cont@50 k-NN queue agreement Distance Spearman Resample stability Has transform Fit time
384-D reference 1.00 1.00 0.71 1.00 n/a n/a n/a
PCA to 2D 0.61 0.72 0.38 0.81 0.94 yes 12 s
t-SNE default, random init, lr 200 0.79 0.68 0.55 0.31 0.41 no 41 min
Plus PCA init 0.84 0.73 0.59 0.54 0.66 no 41 min
Plus lr = N/12 0.88 0.75 0.62 0.56 0.69 no 38 min
Plus perplexity 50, deduplicated 0.91 0.77 0.64 0.58 0.71 no 34 min
UMAP, 50 neighbours, min_dist 0.1 0.89 0.84 0.66 0.62 0.78 yes 7 min
densMAP 0.87 0.83 0.64 0.60 0.75 yes 19 min
PaCMAP, default 0.88 0.86 0.65 0.71 0.76 partial 9 min

The stability column is resample stability throughout, for the reason above: seed stability would read 1.00 for every row from “Plus PCA init” down except UMAP, and that 1.00 is a statement about determinism rather than about structure. PCA’s 0.94 is the useful anchor for reading the column, since a linear projection is about as stable under resampling as anything can be and it still is not 1.00.

And the claim audit, which is the number the project was actually judged on: of the 24 claims read off the default t-SNE map, 9 held in 384 dimensions. Off the tuned UMAP map, 19 held. Of the 5 that still failed, all 5 were claims about the distance between two groups, which is the one class of claim no 2D method in this table supports well enough to use. That result is worth more than the trustworthiness column, because it says where the remaining error lives and it says the fix is a rule about reading rather than a parameter.

Three readings from the table. t-SNE wins trustworthiness and loses continuity to UMAP by 0.07, which is the asymmetry of its objective showing up exactly where theory says it should. PaCMAP has the best distance correlation at 0.71 and the best continuity, which is unsurprising given that it was designed around preserving mid-range structure, and it is the method we would evaluate first on a new project. And UMAP wins the column that decided the project, transform, while giving up 0.02 of trustworthiness, which is how a capability requirement beats a quality metric.

Metric That Matters

The number that catches silent degradation is **out-of-sample trustworthiness at 50 on the week's arrivals**, computed against their own 384-dimensional neighbours among the anchors. It is the only metric here that is sensitive to the thing that actually breaks, which is the embedding distribution drifting away from the frozen anchor layout. Everything else is computed on the anchor set, where by construction nothing changes until the next monthly refit. Ours sat at 0.81 and the alert threshold is 0.72, which has fired twice: once when a product launch produced a genuinely new ticket population with no anchor neighbours, and once when the embedding service was upgraded from MiniLM-L6 to a newer checkpoint without telling us, which invalidated the anchor coordinates entirely because a different embedding model is a different space. The second one is worth naming as a general hazard: a visualisation pipeline sitting downstream of an embedding service has a dependency that can change under it without any error being raised, and the layout will keep rendering beautiful, stable, and meaningless. Pin the embedding model version into the anchor artifact and fail loudly on mismatch.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Reading distance between clusters The picture has distances in it, so the eye uses them; nothing in the UI says they are not meaningful Pairwise-distance Spearman against the original space; below about 0.5 no distance claim is supported Report the Spearman number beside the map, and check every between-group claim with a centroid distance in the original space
Reading cluster area as population Area looks like count and is actually local density; a tight template group is a small island Spread-ratio range across groups; if it exceeds about 3, area carries no information Carry the deduplication weights, size markers by group count, and put volume in a bar chart next to the map rather than in the map
Inventing clusters at low perplexity Fragmenting minimises the objective when each point feels few neighbours, so crisper always looks better Run the method on one isotropic Gaussian and count apparent clusters; any answer above 1 calibrates the eye Scale perplexity or n_neighbors with N, sweep over a 5x range, and report only structures that survive the whole range
Random initialisation discarding global structure It is the historical default and most tutorials still use it Pairwise-distance Spearman near 0.3; two runs on the same data are not comparable at all init=“pca” for t-SNE, init=“spectral” for UMAP. One string, and it is the largest single effect in this post
A seed-based stability gate reporting 1.00 A deterministic initialisation makes the whole run deterministic, so ten seeds give ten identical layouts The gate passes 100% of points, and it passes them for the configuration you just made deterministic Perturb the input instead: refit on 80% subsamples and compare neighbourhoods over the shared points
Learning rate left at 200 for large N Gradient magnitude scales with N and the default does not; the run finishes without error Final KL divergence, and a visibly unresolved dense central mass learning_rate = max(N/12, 50), which is what sklearn 1.2+ does under “auto”
Duplicate mass dominating the layout Identical points are each other’s whole neighbourhood at distance zero, which the graph construction cannot handle Count exact duplicates; compare island count before and after collapsing Collapse at cosine 0.98 into weighted representatives, and fit the PCA on the collapsed set
Using 2D coordinates as model features The map is right there and looks informative Compare a model on the 2D coordinates against one on the original vectors; the gap here is 0.66 to 0.71 accuracy Never do it. The coordinates are a non-monotone, seed-dependent, non-invertible function of the input that throws away 382 dimensions for a reason that has nothing to do with prediction
No out-of-sample path discovered late t-SNE works fine in the notebook and the serving requirement surfaces at handover Try to place a new point and find there is no method to call Decide the transform requirement first. It eliminates methods before any quality metric is computed
Tuning parameters until the picture looks clean It is the natural workflow and it optimises for convincingness Resample stability drops as the picture sharpens; ours went 0.71 to 0.48 tuning toward the nicer map Fix parameters by a rule that does not consult the picture, then use the picture only to generate claims to be checked elsewhere
Trusting a stable-looking map after an embedding upgrade The layout still renders and nothing errors Anchor artifact model-version mismatch; out-of-sample trustworthiness collapse Pin the embedding model identity into the anchor artifact and refuse to transform on mismatch
Common Pitfall

The single most common mistake on this exact problem is treating the gaps between t-SNE islands as meaningful. It is the most common because it is the least avoidable: gaps are the most visually salient feature of the output, the eye reads them as separation, and no amount of knowing better fully suppresses the reading. The mechanism is worth stating precisely. t-SNE's cost is a KL divergence between a distribution over pairs in the original space and one in the map, and the heavy-tailed Student-t kernel in the map means that once two groups are separated by more than a few units, moving them further apart costs almost nothing. So the optimisation is nearly indifferent to the size of a gap, and the gap you see is whatever the repulsion term happened to settle on given the initialisation. Our measurement of this is that the distance Spearman is 0.31 for the default configuration and 0.58 for the best t-SNE configuration, meaning even after everything in the solution section, roughly two-thirds of the variance in between-point distance is not explained by the original space. The operational fix is not a parameter. It is that the map is published with a note saying distances are not to scale and with a one-click "check this in 384 dimensions" affordance, and that 5 of the 24 audited claims failed anyway.

Four panels isolating the specific traps of embedding visualisation: cluster area reflecting local density rather than population so an 11 percent volume group appears as a small island, between-cluster gaps being nearly free under the heavy-tailed Student-t kernel so the two closest queues in 384 dimensions land at opposite ends of the map, a single isotropic Gaussian shattering into seven apparent clusters at perplexity 5 and resolving to one at perplexity 200, and t-SNE having no transform so a weekly refit displaces every point by 0.63 of the layout diameter where UMAP transform displaces them by 0.004

Scaling and Productionizing

The cost structure here is unusual: the expensive step is the neighbour graph, not the optimisation, and it is shared between the two methods, so running both costs much less than twice one.

Raw embeddings, 1.412M x 384 float32                         = 2.15 GB
After boilerplate strip and 0.98 near-duplicate collapse     1.13M rows
PCA to 50, randomized SVD, 12 oversamples                    = 2 min 40 s
Reduced matrix, 1.13M x 50 float32                           = 226 MB
Anchor sample, stratified by month and queue                 400,000 rows
50-NN graph on anchors, pynndescent, 32 threads              = 6 min 10 s
UMAP optimisation, 200 epochs, negative sampling 5           = 7 min 05 s
t-SNE, Barnes-Hut, theta 0.5, 1,000 iters, 400k points       = 2 h 51 min
t-SNE, FIt-SNE interpolation, same configuration             = 34 min
Ten-resample stability gate, UMAP, graph reused per resample = 19 min
Weekly transform, 40,000 arrivals against 400k anchors       = 11 s
Per-point transform latency, warm index                      = 0.27 ms
Anchor artifact on disk, model plus graph plus coordinates   = 512 MB

The neighbour graph is the thing to cache, and it is what makes the stability gate affordable. Ten full UMAP refits from scratch would be 70 minutes. Ten resamples that each reuse the relevant slice of one pre-computed pynndescent index come in at 19, because graph construction dominates and an 80% subsample’s neighbour lists can be derived from the full index rather than rebuilt. The same graph also feeds the t-SNE run, so the marginal cost of producing both maps is the second optimisation, not a second pipeline.

Barnes-Hut is the wrong t-SNE at this scale and the fix is an implementation swap. Barnes-Hut approximates the repulsion term with a quadtree at O(N log N), which is fine to about 100,000 points and then is not: 2 hours 51 minutes for 400,000. FIt-SNE, from Linderman and colleagues in Nature Methods in 2019, replaces the quadtree with an interpolation scheme on a grid, making the repulsion effectively O(N), and gets the same configuration to 34 minutes. openTSNE is the practical way to get it with a scikit-learn-shaped API.

The anchor model is the artifact to version, and it is the whole coordinate system. 512 MB, containing the fitted UMAP object, the PCA, the pynndescent index, the embedding model identity, and the anchor coordinates. Reproducing a position someone screenshotted six weeks ago means loading that artifact, not refitting. We keep the last 6 monthly anchors and a manifest, and a refit publishes a diff report: how many arrivals from the previous month moved more than 5% of the layout diameter under the new anchor, which is the honest measure of whether the refresh broke anyone’s mental model.

The refit cadence is set by drift in the arrival population, not by the layout. Frozen for 8 weeks, out-of-sample trustworthiness at 50 decayed 0.81, 0.81, 0.79, 0.78, 0.76, 0.74, 0.71, 0.68. It is a slow, monotone decay and it accelerates after a product launch, so the rule is monthly by default plus an immediate refit when the threshold is crossed. The cost is an hour, so the cadence is set by how much layout churn readers tolerate rather than by compute.

The monitoring signal for silent degradation is a triple: out-of-sample trustworthiness at 50 on the week’s arrivals, the fraction of arrivals whose nearest anchor is further than the 99th percentile of anchor-to-anchor nearest-neighbour distance, and the embedding model version hash. The first is the quality number. The second is the early warning, because a new ticket population shows up as arrivals landing far from every anchor a week or two before the trustworthiness number moves. The third catches the failure that no statistical monitor will, which is the upstream embedding service changing checkpoints.

Key Insight

The engineering payoff of the anchor-plus-transform design is not compute, it is that the map becomes a stable reference that people can talk about. A weekly refit produces a technically better layout every week and a socially useless one, because "the cluster in the upper left" means something different on Tuesday than it did on Friday and nobody builds a mental model of a coordinate system that keeps rotating. Freezing the coordinate system and accepting a slowly degrading fit is the right trade for an artifact whose value is that three people share a picture of it. We measured the degradation so the trade is explicit rather than accidental: 8 weeks frozen costs 0.13 of out-of-sample trustworthiness, and a monthly refit keeps it inside 0.04 while limiting layout churn to one disruption a month that can be announced.

Real World

t-SNE is van der Maaten and Hinton's 2008 JMLR paper, and the corrective literature is as important as the original. Wattenberg, Viegas and Johnson's 2016 Distill article "How to Use t-SNE Effectively" is the canonical demonstration that the method produces convincing clusters in pure noise and that cluster size and inter-cluster distance carry no reliable information, and it remains the best 20 minutes anyone can spend before shipping one of these maps. Kobak and Berens's 2019 Nature Communications paper established that PCA initialisation recovers most of the global structure people believed the objective had discarded, and Belkina and colleagues, in the same journal and year, established the learning-rate-equals-N-over-12 result that scikit-learn later adopted as its "auto" default. Linderman and colleagues' FIt-SNE in Nature Methods 2019 is what makes million-point t-SNE tractable at all. UMAP is McInnes, Healy and Melville's 2018 preprint, developed at the Tutte Institute, and it is the default in the single-cell world: 10x Genomics ships UMAP in Cell Ranger and a large fraction of published single-cell papers show a UMAP as their first figure. That dominance is also where the sharpest criticism comes from: Chari and Pachter's 2023 PLOS Computational Biology paper "The specious art of single-cell genomics" argues that 2D embeddings distort neighbourhood structure severely enough that biological conclusions drawn from them are unreliable, and demonstrates it by embedding data into a picture of an elephant while preserving respectable-looking quality scores. The honest position for a practitioner is that the criticism lands, and that the response is not to abandon the map but to demote it from evidence to hypothesis generator, which is what the claim audit in this post operationalises.

Alternative Approaches

Approach Trust@50 / Cont@50 Fit and serve cost Interpretability Best fit
UMAP, 50 neighbours 0.89 / 0.84 7 min on 400k, 0.27 ms per arrival Moderate: local structure reliable, distance and area are not Out-of-sample placement required, million-point scale, CPU only
t-SNE, PCA init, FIt-SNE 0.91 / 0.77 34 min on 400k, no transform at all Moderate: best local fidelity, worst continuity One-off exploration where no new points will arrive
PaCMAP 0.88 / 0.86 9 min on 400k, partial transform support Moderate: best mid-range distance fidelity of the nonlinear methods New projects, and any case where between-group distance matters
densMAP 0.87 / 0.83 19 min on 400k, 0.31 ms per arrival Good: point area encodes original-space density, which fixes the area trap Density itself is the question, e.g. finding tightly templated groups
PCA to 2D 0.61 / 0.72 12 s, exact linear transform Best: axes are interpretable linear combinations, distances are meaningful Global geometry matters more than local detail, or as a sanity baseline
2D autoencoder bottleneck 0.72 / 0.79 40 min training, 0.03 ms per arrival Poor: bottleneck coordinates have no interpretation Very high arrival rates where 0.03 ms per point is the binding constraint
Query the k-NN graph, no map n/a, exact by construction 6 min index, 1.4 ms per query Best: answers are in the original space, no distortion at all Most specific questions, which is more of them than anyone expects

The bottom row is the one worth arguing for. Of the 24 claims in the audit, 17 were questions that a k-NN query in 384 dimensions answers exactly and a map answers approximately: “what else looks like this ticket”, “do these two queues overlap”, “is this cluster growing”. For those, the map is a worse instrument than the index that was built to make the map. What the map is uniquely good at is the thing no query can do, which is showing you the question you did not think to ask, and that is a real and limited value.

What we shipped is UMAP, and the decision was made by the transform column rather than by any quality number. If the weekly-refresh requirement were dropped, we would ship t-SNE with PCA initialisation for its 0.02 better trustworthiness and accept the 0.07 worse continuity, because for hypothesis generation false neighbours are the more expensive error. On a new project today we would evaluate PaCMAP first, because 0.71 distance correlation against UMAP’s 0.62 addresses the single class of claim that still failed the audit. And we would switch to densMAP the moment the question became about density rather than adjacency, since it is the only method here that makes area mean something.

Key Takeaways

  • Initialisation, not the objective, is what destroys global structure. init="pca" for t-SNE moved pairwise-distance Spearman from 0.31 to 0.54 and resample stability from 0.41 to 0.66, for the cost of one string. The folklore that t-SNE discards global structure is largely a description of random initialisation.
  • The learning rate default is a scale bug at large N. Gradient magnitude grows with N and 200 does not, so a 200,000-point run at the historical default finished unconverged with KL 4.81 against 1.94 at N/12. scikit-learn 1.2+ fixes this under learning_rate="auto", which means pinning an older version silently runs the broken configuration.
  • Cluster area is density and inter-cluster distance is nothing. The Password-Reset group was 11% of volume and the smallest island on the map, because its tickets are near-identical. Billing-Disputes and Refunds were the third-closest of 1,891 queue pairs in 384 dimensions and sat at opposite ends of the picture.
  • Low perplexity invents structure, and “tune until it looks clean” reliably finds the configuration that invents the most. One isotropic Gaussian produced 7 apparent clusters at perplexity 5 and 1 at perplexity 200. The rule that replaced tuning was that no cluster is reported unless it survives a 5x perplexity range, and it killed 2 of the 4 proposed API-Errors sub-queues.
  • Duplicates are not a data-quality issue here, they are a structural one. Identical points form zero-distance neighbourhoods the graph construction cannot handle, and collapsing at cosine 0.98 moved trustworthiness from 0.79 to 0.86 while removing 6 of 14 apparent islands. Six of the team’s fourteen issue clusters were intake templates.
  • Trustworthiness without continuity hides the failure that matters. t-SNE’s asymmetric objective buys trustworthiness by tearing neighbourhoods apart, so 0.91 trustworthiness coexisted with 0.77 continuity and with genuine neighbourhoods split into islands a reader then interpreted as distinct issue types.
  • The transform requirement decides the method before any quality metric does. t-SNE has no out-of-sample path by construction, and a weekly refit displaced every point by 0.63 of the layout diameter against UMAP transform’s 0.004. A capability requirement beat a 0.02 trustworthiness advantage.
  • The stability gate is what makes the picture admissible, and it has to perturb the input rather than the seed. Ten 80% resamples, per-point 2D k-NN Jaccard, grey out anything below 0.6. A seed-based gate reports 1.00 for any deterministically initialised configuration, which is the one you just built. On the tuned UMAP layout 91% of points cleared it; on the default t-SNE layout 38% did, and the failures concentrated exactly in the boundaries and small islands people were reading.

The counter-intuitive lesson is that the whole tuning exercise did not make the map trustworthy, and was still worth doing. Trustworthiness went from 0.79 to 0.89 and distance correlation stayed at 0.62, which means the picture is still not something you can measure on. What changed is the hit rate of the hypotheses it generated, from 9 of 24 claims holding to 19 of 24, and the 5 failures that remained were all the same class of claim, which is now a written rule rather than a recurring surprise. The mature version of this pipeline is not a better picture, it is a picture with a stability mask, a distance-correlation number printed beside it, and a button that re-checks any claim in 384 dimensions. The map generates the question and the index answers it, and a team that inverts those two roles will keep putting artifacts of the initialisation into roadmap documents.

Frequently Asked Questions

Q: Why not just use UMAP and skip t-SNE entirely? A: That is close to what we shipped, and the reason both are in the pipeline is that they fail differently and the disagreement is informative. t-SNE scored 0.91 trustworthiness against UMAP’s 0.89 and UMAP scored 0.84 continuity against t-SNE’s 0.77, which is the theoretical asymmetry showing up in the measurements. A structure visible in both maps is much more likely to be real than one visible in either alone, and since the neighbour graph is shared, the marginal cost of the second map is one optimisation run rather than a second pipeline. If you have to pick one, pick UMAP, and the reason is transform rather than any quality number.

Q: Why not PCA, which is deterministic, has an exact inverse, and preserves distances? A: For global questions PCA is better and we keep it in the pipeline as a baseline for exactly that. Its distance Spearman of 0.81 beats every nonlinear method in the table, so a claim about two groups being far apart is better checked on the PCA plot than on the UMAP one. What it cannot do is the primary task: at 0.61 trustworthiness and 0.38 k-NN queue agreement against a 0.71 ceiling, local neighbourhoods are not readable, and “which tickets are like this one” is the question the director asked. Two components of a sentence-embedding PCA carry 9.1% of the variance, and that is a ceiling no parameter moves.

Q: Why trustworthiness and continuity rather than silhouette or Davies-Bouldin on the 2D coordinates? A: Because the cluster-validity indices measure the wrong object. Silhouette on 2D coordinates measures how compact and separated the blobs in the map are, and t-SNE’s entire job is to make blobs compact and separated, so the metric rewards the method for the distortion we are trying to quantify. A map that shattered one real group into four tight islands would score an excellent silhouette and a terrible continuity. Trustworthiness and continuity compare rank orderings between the two spaces, which is the only comparison that can detect a distortion, and they need to be reported together because each is blind to the error the other catches.

Q: Can I use the 2D coordinates as features in a downstream classifier? They look so separable. A: No, and the measurement is in the table: k-NN queue agreement is 0.66 on the 2D map against 0.71 on the 384-dimensional vectors, so at best you are paying 0.05 accuracy for a plot. The deeper problems are that the mapping is seed-dependent, so retraining the reduction changes your features non-monotonically; it is not defined out of sample at all for t-SNE; and for UMAP transform it is a different function from the one fit applied, so training features and serving features come from two slightly different mappings. If a low-dimensional representation genuinely helps your model, use the PCA at 50 components, which is linear, deterministic, invertible and exactly reproducible.

Q: How do I decide perplexity or n_neighbors without staring at the output? A: Set it by a rule that does not consult the picture, then use the picture only to filter claims. The rule we use is to scale with N, since both parameters are absolute neighbourhood sizes rather than fractions: perplexity 30 at N = 1.1 million covers 0.003% of the data and produces all local detail and no mid-scale structure. We land at perplexity 50 and n_neighbors 50 at this scale. Then run the 5x sweep, 15 through 100 in our case, and report only structures present throughout. And calibrate your own eye first by running the method on one isotropic Gaussian at each candidate value and counting apparent clusters, because any answer above 1 tells you how much structure that setting invents on data with none.

Q: What breaks first in production? A: The upstream embedding model, and it breaks silently in the worst possible way. The anchor layout is a coordinate system defined by one specific embedding checkpoint, so if the embedding service upgrades, arrivals are vectors from a different space being placed into a frozen layout from the old one. Nothing errors, the map renders, the points land somewhere, and every position is meaningless. We hit this and caught it through out-of-sample trustworthiness dropping from 0.81 to 0.34 in one week, which is a fast signal but not a fast enough one. Pin the embedding model identity into the anchor artifact and refuse to transform on a mismatch. Second-most-likely is ordinary population drift, which is slow and monotone: 8 weeks frozen cost 0.13 of out-of-sample trustworthiness, and the early warning is the fraction of arrivals whose nearest anchor is beyond the 99th percentile of anchor-to-anchor distance, which moves a week or two ahead of the quality metric.

Interview Questions

Q: A colleague shows you a t-SNE plot with well-separated clusters and concludes there are six distinct customer types. What do you ask? Expected depth: Work through the three claims being conflated. That six blobs exist is a claim about the map; that they correspond to real neighbourhood structure is a claim about the data; that they are the right taxonomy is a claim about the domain. Ask for the perplexity and whether the structure survives a sweep, because low perplexity fragments and a single isotropic Gaussian shatters into multiple apparent clusters at perplexity 5. Ask for the initialisation, because random initialisation makes the large-scale arrangement an artifact of iteration one. Ask for a re-run under perturbation, because per-point 2D k-NN Jaccard is often below 0.5 at default settings, and be specific about which perturbation: reseeding only works while the initialisation is random, so with a PCA initialisation the right test is refitting on resampled subsets. Ask whether duplicates were collapsed, since identical points form zero-distance neighbourhoods that dominate their region. Then name what cannot be concluded regardless of the answers: nothing about how far apart the clusters are, because the heavy-tailed output kernel makes large gaps nearly free, and nothing about their relative sizes, because area reflects local density rather than population. A strong answer ends with the verification rather than the critique: take the six candidate groups back to the original space and check separation there.

Q: Explain why t-SNE has no transform method and UMAP does. Expected depth: t-SNE is defined as an optimisation over a fixed finite point set: the objective is a KL divergence between pairwise distributions on exactly those N points, and the output is N free coordinate pairs, not a function. There is no parameterised mapping to evaluate at a new input, and adding a point changes the normalisation of every conditional distribution, so the principled response is to refit, which moves everything. UMAP’s construction is different in a way that admits an approximation: it builds a fuzzy simplicial set from local neighbourhoods and optimises a cross-entropy against a 2D counterpart, so a new point can be attached by finding its neighbours among the fitted points and optimising only its own coordinates with everything else held fixed. Then name the caveats, because they are the substance: transform cannot create new structure, so a genuinely novel population lands in whichever gap its weak attachments pull it toward; it is a different function from what fit applied, so fit and transform coordinates are not perfectly interchangeable; and it is stochastic unless transform_seed is pinned. Mention the general alternative of parametric UMAP or an autoencoder, which buy a real function at the cost of quality and training complexity.

Q: How would you evaluate a dimensionality-reduction pipeline when there is no held-out score and no label? Expected depth: Build it from three independent kinds of evidence and say why none suffices alone. First, neighbourhood retention: trustworthiness and continuity at a k matched to the scale of question being asked, reported as a pair because they penalise opposite errors, plus a pairwise-distance rank correlation to establish whether distance claims are licensed at all. Be explicit that these are rank-based on purpose, since a map is allowed to be wrong about magnitude and not about ordering. Second, a downstream-task ceiling check: the same simple classifier on the low-dimensional coordinates and on the original vectors, where the gap is the compression loss in an interpretable unit, with the warning that this is a diagnostic and optimising it invites putting the label into the input. Third, stability: refit on resampled subsets and measure per-point neighbourhood agreement, because a feature that disappears under a slightly different sample is not a feature of the data. Note here that reseeding is the wrong perturbation once the initialisation is deterministic, since the run then returns an identical layout and the gate reports perfect stability. Strong answers add a fourth that is not standard, which is auditing the claims users actually read off the artifact against the original space, and note why the obvious metrics are wrong: internal cluster-validity indices such as silhouette computed on the output measure exactly the compactness the method was designed to manufacture.

Q: Your t-SNE run on 500,000 points finishes with no errors and produces one dense ball with a few stragglers. Diagnose it. Expected depth: Start with the learning rate, because it is the highest-prior cause and it fails exactly this way. Each point’s gradient accumulates a repulsion term against every other point, so the update magnitude required scales with N while the historical default of 200 does not, and the optimisation simply does not travel far enough in the iteration budget. Check the final KL divergence rather than the picture; an unconverged run reports a much higher value. Fix with learning_rate = max(N/12, 50) or "auto" on scikit-learn 1.2+. Then check the iteration count and the early-exaggeration phase, since 250 iterations of exaggeration followed by too few refinement steps produces a similar look. Then check perplexity relative to N, since an absolute neighbourhood size of 30 out of 500,000 points gives almost no mid-scale attraction. Then the input: unstandardised or un-reduced high-dimensional input where distances have concentrated, which is diagnosable as the ratio of mean pairwise distance to mean nearest-neighbour distance approaching 1. Finally note that at 500,000 points Barnes-Hut is the wrong implementation on time grounds regardless, and an interpolation-based one is roughly five times faster.

Q: When would you not build an embedding map at all? Expected depth: When the questions are specific, which is most of the time. A k-nearest-neighbour index over the original vectors answers “what is similar to this”, “do these two groups overlap”, and “is this population growing” exactly, in the original space, with no distortion, and it is a prerequisite for building the map anyway. Enumerate what the map adds that a query cannot: it surfaces structure nobody thought to query, it communicates to an audience that will not write a query, and it makes a shared spatial reference that a team can point at. Then be precise about the cost of those benefits, which is that between-group distance and group area are not readable, roughly a third to two-thirds of between-point distance variance is unexplained even in a well-tuned map, and low-perplexity configurations manufacture apparent clusters in structureless data. A strong answer lands on the division of labour rather than on a verdict: the map is a hypothesis generator and the index is the instrument that tests the hypotheses, and the common failure is using the map as the instrument.

View full code for this problem