Build a Hierarchical Clustering Pipeline for Document Grouping


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

ML Problem & Solution

Hierarchical Clustering for Document Grouping

412,000 tickets, no known number of themes: the linkage choice decides more than k ever will.

⏱ 26 min read 📐 Intermediate 🧩 Classical ML

A B2B SaaS support organisation is drowning in repeat work. 412,000 tickets over 18 months, 1,840 agents, and a documentation team of four whose job is to write knowledge-base articles for whatever is being asked most. Nobody knows what is being asked most. The ticket taxonomy has 74 categories chosen in 2019, agents pick one in under two seconds, and 39% of tickets land in Other / General. The docs team’s actual question is simple and the taxonomy cannot answer it: which recurring issues, described in the customer’s own words, account for the most agent hours, and which of them nest inside a broader theme that deserves one article instead of nine.

The obvious move is to embed the tickets and run k-means. We did, with k=50 on TF-IDF vectors, and got a result that is worth describing because it is the single most common outcome of a first clustering attempt: one cluster containing 61% of all tickets, 14 clusters with fewer than 40 tickets each, and a silhouette score that peaked at k=2. The giant cluster was not a topic. It was every ticket whose text was dominated by the email footer, the “Sent from my iPhone”, and the four-paragraph legal disclaimer that one enterprise customer’s mail server appends to everything.

Even with clean text, k-means is answering the wrong question. It requires k up front, and the number of distinct recurring issues in a support corpus is not a number anyone knows; it is the thing we are trying to discover. Worse, k is not even well-defined here, because the structure is genuinely nested. “SSO login failure” is one theme at one resolution and four themes at another (SAML certificate expiry, IdP metadata mismatch, session cookie domain, MFA loop). The docs team needs both resolutions at once: one article on SSO troubleshooting, four sections inside it. A flat partition can represent one of those and destroys the other.

The third difficulty is scale, and it is the one that turns a textbook algorithm into an engineering problem. Agglomerative clustering starts from a full pairwise distance matrix. For 412,000 documents that is 84.9 billion pairs, 340 GB at float32, and the standard scipy implementations want it in memory at once. This is why hierarchical clustering has a reputation as a toy-dataset method, and it is a reputation based on an implementation detail rather than on the algorithm.

The analogy that keeps the goal straight: a flat clustering is a filing cabinet where someone has already decided the drawer labels, and every document must go in exactly one drawer. A dendrogram is a family tree. You do not ask a family tree how many families there are; you ask it who is closely related, and then you decide at what remove you stop calling people relatives. The cut is a decision about what you are doing with the answer, not a property of the data.

Formally: given 412,000 unlabelled ticket texts, produce a nested grouping such that a documentation team can select a resolution level and read out coherent, stable issue themes, optimising for bootstrap-stable theme recovery (adjusted Rand index against a 3,000-ticket human-labelled reference), subject to a full rebuild in under 45 minutes on one 32 GB machine, no fixed cluster count, and every theme being summarisable in a phrase a human will accept.

Framing the Problem

This is unsupervised structure discovery, specifically hierarchical clustering, and the framing trap is the same one k-means invites: treating “how many clusters” as the central question. It is a secondary question. The central question is what distance means between two tickets, followed closely by what it means to merge two groups of tickets, which is the linkage function. Get those two right and the cut point is a slider the docs team can move. Get them wrong and no cut is any good.

There is no target variable, so the “label” only exists in two places, both of them at evaluation time. First, a reference set: three support leads independently grouped the same 3,000 sampled tickets into issue themes, and we kept the 2,410 tickets where at least two of the three agreed, giving 68 reference themes. Second, the operational outcome: whether an article written against a discovered theme actually deflects tickets, measured as the 30-day change in inbound volume for tickets matching that theme after the article ships.

Constraints, in the order they bind:

  • No fixed cluster count. The output must be a hierarchy the docs team can cut at different heights, not a partition. This is the constraint that rules out k-means and rules in agglomerative clustering, before any accuracy argument.
  • Memory ceiling of 32 GB. A dense pairwise distance matrix over 412,000 documents is 340 GB even stored as a condensed upper triangle, and 679 GB square. Everything about the implementation follows from this.
  • Rebuild under 45 minutes, monthly, so the docs team can re-run after a product launch changes the ticket mix.
  • Stability across rebuilds. A theme that exists this month and vanishes next month without the underlying tickets changing is worse than no theme, because the docs team has already assigned the article.
  • Human-readable themes. Every cluster needs a label a support lead will accept. A cluster that can only be described as “cluster 41” is not a deliverable.

The success metric is adjusted Rand index against the human reference set, measured only on the 2,410 reference tickets and only at the cut depth the docs team actually uses. The guardrail metrics are coverage, the share of tickets in a theme of at least 25 members, which needs to stay above 70% or the output is a long tail of singletons dressed up as a taxonomy, and bootstrap stability, the mean pairwise ARI between clusterings of 10 resampled 80% subsets, which is the number that predicts whether a theme survives to next month.

Metric That Matters

Silhouette score is the default clustering metric and it is close to useless here. On 768-dimensional embeddings with cosine distance, intra-cluster and inter-cluster distances both concentrate around a narrow band, so silhouette spans 0.02 to 0.09 across every configuration we tried and ranks them in almost the reverse of the human reference. It went up when we merged themes the support leads considered distinct, because fewer, fatter clusters look better by any compactness-based criterion. The metric that actually tracks the deliverable is ARI against the reference set, and the metric that predicts next month is bootstrap ARI against yourself.

Out of scope: multilingual clustering (9% of tickets are not in English and were held out rather than handled badly), streaming or incremental assignment of new tickets to an existing hierarchy, and any attempt to predict resolution time from the theme. Each is a separate system.

Data and Features

The input is a single table: tickets(ticket_id, customer_id, created_at, subject, body, category, agent_minutes). 412,000 rows over 18 months, a median body of 94 words, a 99th percentile of 1,840 words, and a heavy right tail made almost entirely of pasted log files.

The representation decision comes first because it dominates everything downstream. TF-IDF is the cheap option and it fails on this corpus in a specific way: support tickets about the same issue share almost no vocabulary. “Can’t log in with my work account”, “SAML assertion rejected”, and “SSO broken since Tuesday” are the same theme with three disjoint token sets, and TF-IDF puts them in three different clusters while happily merging every ticket that says “urgent”. Sentence embeddings fix exactly this, and we used sentence-transformers with all-mpnet-base-v2, 768 dimensions, L2-normalised.

Key Insight

L2-normalising the embeddings is not a cosmetic preprocessing step, it is what makes Ward linkage defensible. Ward is defined only for Euclidean distance, and cosine is the right similarity for text. On unit-norm vectors the two are monotonically related, since squared Euclidean distance equals 2 minus twice the cosine similarity, so every pairwise comparison Ward makes between documents orders the same way a cosine comparison would. Ward's objective is a sum of squared distances to centroids, and centroids of unit vectors are not themselves unit-norm, so this is not literally a cosine objective (spherical k-means is); it is close enough that Ward's geometry behaves like cosine geometry, and skipping the normalisation instead lets document length drive the merges outright.

Before embedding anything, the text has to be stripped, and this is where most of the accuracy was won:

# Boilerplate stripping. This is the single highest-value 40 lines in the pipeline:
# without it, 61% of tickets cluster on email footers rather than on issues.
import re
import pandas as pd

QUOTE_MARKERS = re.compile(
    r"(?im)^(>|on .{3,60} wrote:|from:\s|-{3,}\s*original message)"
)
SIGNATURE_MARKERS = re.compile(
    r"(?im)^(sent from my |[-]{2,}\s*$|best regards|kind regards|thanks,?\s*$)"
)
DISCLAIMER = re.compile(
    r"(?is)(this (e-?mail|message) (and any attachments )?(is|are) confidential"
    r"|the information contained in this).{0,1200}$"
)
LOG_BLOCK = re.compile(r"(?m)^\s*(\[|\{|at [\w.$]+\(|\d{4}-\d{2}-\d{2}T).*$")
IDENTIFIER = re.compile(
    r"\b([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
    r"|[\w.+-]+@[\w-]+\.[\w.]{2,}|\b\d{6,}\b)"
)

def clean_body(text: str) -> str:
    """Strip reply chains, signatures, disclaimers, log dumps and identifiers."""
    text = DISCLAIMER.sub(" ", text)
    lines, kept = text.splitlines(), []
    for line in lines:
        if QUOTE_MARKERS.search(line) or SIGNATURE_MARKERS.search(line):
            break
        if LOG_BLOCK.match(line):
            continue
        kept.append(line)
    text = IDENTIFIER.sub(" ", " ".join(kept))
    return re.sub(r"\s+", " ", text).strip()

def build_documents(tickets: pd.DataFrame) -> pd.DataFrame:
    """Subject carries the issue; weight it by repeating it once."""
    body = tickets["body"].fillna("").map(clean_body)
    subject = tickets["subject"].fillna("").str.strip()
    doc = (subject + ". " + subject + ". " + body).str.slice(0, 2000)
    out = tickets.assign(document=doc, doc_words=doc.str.split().str.len())
    return out[out["doc_words"] >= 4].copy()

Repeating the subject is a blunt instrument and it works: the subject line is the one field where a human has already compressed the issue into a phrase, and giving it roughly a third of the token budget raised reference ARI by 0.06. Truncating at 2,000 characters costs nothing measurable and stops the 1,840-word log-file tickets from consuming the embedding budget.

Common Pitfall

Embedding raw ticket bodies and then wondering why the clusters look like customer accounts rather than issues. Boilerplate is not noise that averages out, it is high-consistency signal: an identical 140-word disclaimer on 8,000 tickets makes those 8,000 tickets genuinely similar to each other under any distance you choose, and a clustering algorithm is correct to group them. Before blaming the algorithm, print the 20 tickets closest to each cluster centroid and read them. The failure is visible in about 30 seconds and invisible in any metric.

The leakage specific to this problem

Clustering has no train and test labels, so people assume it cannot leak. It leaks in two ways here, and both inflate every offline number.

Near-duplicate leakage. 11.4% of tickets in this corpus are near-duplicates of another ticket: re-opens, the same user emailing twice, and automated tickets from monitoring integrations that differ only in a timestamp. A cluster built mostly out of near-duplicates looks superbly coherent by any internal metric and represents one issue reported once. Deduplicating by MinHash on 5-shingles at a Jaccard threshold of 0.85 removed 47,000 tickets and dropped internal cohesion while raising reference ARI, which is the signature of a leak being closed. Together with the burst cap below and the four-word minimum on the cleaned body, that is what takes 412,000 tickets to the 353,000 documents everything downstream is sized against.

Incident burst contamination. On 2025-03-14 an authentication outage generated 4,190 tickets in six hours, all saying the same thing. Left in, that burst becomes its own dense cluster, pulls the dendrogram’s merge heights around, and produces a “theme” that is one bad afternoon. It is not a theme; it is an event. Capping any single calendar day’s contribution is the fix. The cap has to be set against normal daily volume rather than picked round: 412,000 tickets over 547 days is 753 a day, so a cap of 2,500 is about three times a normal day and fires only on genuine bursts, removing 1,690 tickets on 2025-03-14 and nothing at all on 542 of the 547 days. It is a modelling decision rather than data cleaning, because bursts are exactly what you want to detect if the goal is incident response rather than documentation.

# Dedup and burst capping. Both are leakage controls, applied before embedding.
import numpy as np
import pandas as pd
from datasketch import MinHash, MinHashLSH

def shingles(text: str, k: int = 5) -> set[str]:
    words = text.lower().split()
    return {" ".join(words[i:i + k]) for i in range(max(len(words) - k + 1, 1))}

def drop_near_duplicates(docs: list[str], threshold: float = 0.85) -> np.ndarray:
    """Return a boolean keep mask. One survivor per near-duplicate group."""
    lsh = MinHashLSH(threshold=threshold, num_perm=96)
    keep = np.ones(len(docs), dtype=bool)
    for i, text in enumerate(docs):
        m = MinHash(num_perm=96)
        for sh in shingles(text):
            m.update(sh.encode("utf8"))
        if lsh.query(m):
            keep[i] = False
        else:
            lsh.insert(str(i), m)
    return keep

def cap_daily_burst(created_at: pd.Series, max_per_day: int = 2500,
                    seed: int = 17) -> np.ndarray:
    """Downsample any single day to max_per_day tickets. Events are not themes.

    2,500 is roughly three times the 753 tickets a normal day brings, so it
    only ever touches genuine bursts: it removed 1,690 of the 2025-03-14
    outage's 4,190 and nothing at all on 542 of the 547 days.
    """
    rng = np.random.default_rng(seed)
    keep = np.zeros(len(created_at), dtype=bool)
    days = pd.to_datetime(created_at).dt.floor("D").to_numpy()
    for day in np.unique(days):
        idx = np.flatnonzero(days == day)
        chosen = idx if len(idx) <= max_per_day else rng.choice(
            idx, size=max_per_day, replace=False)
        keep[chosen] = True
    return keep

There is no train and test split in the supervised sense, but there are two splits that matter. The reference split holds out the 2,410 human-labelled tickets from any threshold tuning, because tuning the cut depth to maximise ARI on the same tickets you then report ARI on is the clustering version of fitting on the test set, and it cost us 0.11 of apparent ARI when we stopped doing it. The temporal split fits the hierarchy on months 1 to 15 and checks on months 16 to 18 that the discovered themes still receive tickets, which is what catches themes that were real and are now obsolete.

The Naive Baseline

The defensible baseline is not k-means on TF-IDF, which we already know fails. It is k-means on the same clean embeddings the real solution uses, so that the comparison isolates the clustering algorithm rather than the text pipeline. We also need a floor below that: the existing 74-category agent taxonomy, which is what the docs team has today.

# Two baselines: the taxonomy the support org already has, and MiniBatchKMeans
# on the same embeddings the hierarchical solution uses.
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
import numpy as np

def taxonomy_baseline(reference_labels: np.ndarray,
                      agent_category: np.ndarray) -> float:
    """What the docs team has today: the agent-selected category."""
    return adjusted_rand_score(reference_labels, agent_category)

def kmeans_baseline(embeddings: np.ndarray, k: int = 68,
                    seed: int = 17) -> tuple[np.ndarray, dict]:
    """k set to the reference theme count, which is knowledge we would not have."""
    km = MiniBatchKMeans(n_clusters=k, batch_size=4096, n_init=10,
                         max_iter=300, random_state=seed)
    labels = km.fit_predict(embeddings)
    sizes = np.bincount(labels)
    return labels, {
        "k": k,
        "largest_cluster_share": float(sizes.max() / sizes.sum()),
        "clusters_under_25": int((sizes < 25).sum()),
        "silhouette": float(silhouette_score(
            embeddings[:20000], labels[:20000], metric="cosine")),
    }

Numbers on the 2,410 reference tickets, with k=68 handed to k-means as a gift it would not have in production:

  • Agent taxonomy: ARI 0.14. Not a bug, just what a 74-category dropdown chosen in 2019 and filled in under two seconds is worth.
  • k-means, k=68, clean embeddings: ARI 0.31, largest cluster 9.2% of tickets, 11 clusters under 25 members, silhouette 0.061.
  • k-means, k chosen by silhouette sweep from 10 to 200: silhouette picks k=14, giving ARI 0.19.

The middle number is the honest baseline and it is not terrible. Embeddings plus k-means more than doubles the taxonomy. It is insufficient for three reasons that map directly onto the constraints. It needs k, and the only k that worked was the one we got from the answer sheet. It produces a flat partition, so the nested SSO structure the docs team asked about cannot be represented at all. And it is unstable: mean pairwise ARI across 10 bootstrap resamples was 0.44, meaning a rebuild reshuffles nearly half the pairwise groupings, which in practice means the docs team’s assignment list changes under them every month.

Key Insight

The baseline worth measuring against is not the worst thing you can build, it is the best thing that is cheap. Comparing Ward against k-means on TF-IDF would have credited the hierarchy with 0.66 of ARI that the text pipeline earned, and we would have drawn the wrong conclusion about where to spend the next week. Hold everything constant except the one component under test, even when that makes your headline number smaller.

The Solution

Agglomerative clustering with a sparse connectivity constraint and Ward linkage on L2-normalised sentence embeddings, cut by distance threshold rather than by cluster count, with the dendrogram itself shipped as the deliverable.

The mechanism, before the code: bottom-up hierarchical clustering is a knockout tournament run in reverse. Every document starts as its own group; at each round the two closest groups merge; the record of which groups merged, and at what distance, is the tree. The only real choice is how you measure the distance between two groups rather than two points, and that choice is the linkage function. It changes the answer far more than the embedding does.

Pipeline from 412,000 raw tickets through boilerplate stripping, near-duplicate removal and burst capping to 353,000 documents, sentence embeddings, a 30-nearest-neighbour connectivity graph reducing 84.9 billion candidate pairs to 10.6 million, Ward agglomerative clustering, a distance-threshold cut to 214 themes, and evaluation against a 2,410-ticket human reference

Making it fit: the connectivity graph

The memory problem has a clean solution that most tutorials skip. sklearn.cluster.AgglomerativeClustering accepts a connectivity matrix, a sparse graph of which pairs are allowed to merge. Supply a k-nearest-neighbour graph and the algorithm only ever considers merges along graph edges. After deduplication and burst capping we have 353,000 documents, so the dense candidate set is 62.3 billion pairs and 249 GB as a condensed triangle; at n_neighbors=30 the graph holds about 10.6 million directed edges, under 20 million after symmetrisation, and 130 MB as sparse CSR. Runtime goes from impossible to 6 minutes, and the pipeline’s peak memory becomes the 4.8 GB Ward fit rather than anything to do with a distance matrix.

# The step that makes hierarchical clustering viable at 353k documents.
# Without connectivity: 62.3e9 pairs, 249 GB condensed. With it: ~10.6e6 edges,
# under 20e6 after symmetrisation, 130 MB as sparse CSR.
from sklearn.neighbors import kneighbors_graph
from sklearn.cluster import AgglomerativeClustering
import numpy as np
import scipy.sparse as sp

def build_connectivity(embeddings: np.ndarray, n_neighbors: int = 30):
    """Symmetric kNN graph. Must be connected or the tree comes out as a forest."""
    graph = kneighbors_graph(embeddings, n_neighbors=n_neighbors,
                             mode="connectivity", include_self=False,
                             n_jobs=-1)
    graph = graph.maximum(graph.T)
    n_components, comp_labels = sp.csgraph.connected_components(
        graph, directed=False)
    return graph, n_components, comp_labels

def fit_hierarchy(embeddings: np.ndarray, connectivity,
                  distance_threshold: float = 11.8):
    """Ward on unit-norm vectors: Euclidean here is monotone in cosine."""
    model = AgglomerativeClustering(
        n_clusters=None,
        distance_threshold=distance_threshold,
        metric="euclidean",
        linkage="ward",
        connectivity=connectivity,
        compute_full_tree=True,
        compute_distances=True,
    )
    return model.fit(embeddings)

This is not free. A connectivity constraint changes the answer, not just the cost: two documents that are genuinely similar but not within each other’s 30 nearest neighbours can now only merge through an intermediary, which biases the tree toward locally dense structure. At n_neighbors=10 the graph fragmented into 3,100 connected components, and what came back was not 3,100 stumps but something more misleading: reference ARI fell to 0.58. At 30 the graph was connected and reference ARI was 0.74; at 100 ARI was 0.75 and runtime tripled. 30 is where the curve flattens.

Common Pitfall

Passing a connectivity graph without checking that it is connected. What `AgglomerativeClustering` does with a fragmented graph is worse than failing: `_fix_connectivity` emits a `UserWarning` saying it is "completing" the matrix, then bridges the components with arbitrary edges so the tree does not stop early. You get one tree, a full `children_`, a sensible-looking label array, and a top few levels that are an artefact of which arbitrary edges were added rather than anything in the data. `scipy.sparse.csgraph.connected_components` takes half a second, and the warning is easy to lose in build output, so check it explicitly and treat a component count above 1 as a parameter to fix rather than a message to scroll past.

Linkage: why Ward, and why single linkage is a trap

Four linkage functions, same embeddings, same connectivity graph, cut to the same 214 clusters:

Linkage Group distance definition Reference ARI Largest cluster Failure mode
Single Closest pair between groups 0.09 84.1% Chaining: one bridging document merges two unrelated themes forever
Complete Furthest pair between groups 0.51 4.8% Splits genuinely broad themes because one outlier sets the distance
Average Mean of all cross-pairs 0.66 7.3% Reasonable, but merge heights are not comparable across the tree
Ward Increase in within-cluster variance 0.74 6.1% Forces roughly balanced sizes, so it under-splits the largest theme

Single linkage is the instructive failure. It defines the distance between two groups as the distance between their closest members, so a single ambiguous ticket that sits between “billing question” and “invoice PDF broken” fuses those two themes at a tiny merge height, and from that point on they are one cluster forever. One document decides the fate of tens of thousands. With 353,000 documents there are thousands of such bridges, and the result is the 84.1% mega-cluster in the table, which is the same failure the TF-IDF k-means run produced by a completely different route.

Ward wins because its objective is the one we actually care about. At each step it merges the pair whose union increases total within-cluster sum of squares the least, which means merge height has a consistent meaning everywhere in the tree: it is an amount of variance, comparable at the top and the bottom. That property is what makes a single global distance threshold a sensible cut, and with average linkage it is not, because average distances drift upward as clusters grow for reasons that have nothing to do with coherence.

Key Insight

Cut by distance threshold, never by cluster count. `n_clusters=214` and `distance_threshold=11.8` produce the same partition on one dataset and completely different ones next month, because a fixed count forces the algorithm to keep merging past the point where merges make sense in order to hit the number. A distance threshold says "stop when groups are this far apart", which is a statement about coherence that transfers across rebuilds. Switching from a fixed count to a fixed threshold is what took bootstrap stability from 0.52 to 0.71 without changing a single other thing.

Choosing the cut: the merge-height curve

The threshold itself comes from the merge distances, which compute_distances=True gives you. Sort them, plot them, and look for where they accelerate: merges below the knee are combining coherent things, merges above it are combining themes.

# Pick the cut from the merge-height curve, not from a cluster count.
# The largest relative jump in the top merges is the natural stopping point.
import numpy as np

def cut_candidates(distances: np.ndarray, top_k: int = 400) -> np.ndarray:
    """Return candidate thresholds at the largest gaps in the merge heights."""
    tail = np.sort(distances)[-top_k:]
    gaps = np.diff(tail)
    order = np.argsort(gaps)[::-1]
    return np.unique(np.round(tail[order[:12]] + gaps[order[:12]] / 2, 4))

def clusters_at(model, threshold: float) -> np.ndarray:
    """Relabel a fitted tree at any threshold without refitting. O(n) union-find."""
    n = model.children_.shape[0] + 1
    parent = np.arange(2 * n - 1)
    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    # Apply every merge BELOW the threshold, rather than stopping at the first
    # one above it. Constrained Ward can produce non-monotone `distances_`, so
    # a `break` here would silently drop the short merges that follow an
    # inversion. This also matches scipy's fcluster(criterion="distance").
    for step in np.flatnonzero(np.asarray(model.distances_) < threshold):
        a, b = model.children_[step]
        root = n + int(step)
        parent[find(int(a))] = root
        parent[find(int(b))] = root
    roots = np.array([find(i) for i in range(n)])
    _, labels = np.unique(roots, return_inverse=True)
    return labels

The clusters_at helper is worth more than it looks. Fitting the tree once with compute_full_tree=True and then relabelling at arbitrary thresholds in linear time means the docs team gets a slider rather than a batch job: 214 themes at 11.8, 61 at 22.1, 806 at 6.1, all from one 6 minute fit. That is the hierarchy being a deliverable rather than an intermediate artefact.

One caveat that costs people an afternoon: Ward merge heights are not bounded by the data diameter. The cost of merging clusters A and B is sqrt(2|A||B|/(|A|+|B|)) times the distance between their centroids, so heights grow with cluster size, and a threshold of 11.8 on 353,000 documents means nothing at all on 30,000. The threshold has to be derived on the corpus you have, which is exactly what the merge-height curve is for. Copying a number out of someone else’s post is the one way to use this method wrong.

Labelling the themes

A cluster with no name is not usable by the documentation team, and this step is where a good clustering gets thrown away for lack of ten lines of code. Two signals, combined: the tickets nearest the centroid, and the terms most over-represented in the cluster relative to the corpus.

# Theme labelling. c-TF-IDF over the concatenated cluster plus medoid tickets.
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np

def label_clusters(documents: list[str], labels: np.ndarray,
                   embeddings: np.ndarray, top_terms: int = 6) -> dict:
    """Distinctive terms per cluster plus the 3 tickets closest to the centroid."""
    joined, ids = [], []
    for cid in np.unique(labels):
        idx = np.flatnonzero(labels == cid)
        joined.append(" ".join(documents[i] for i in idx))
        ids.append(cid)
    vec = CountVectorizer(stop_words="english", min_df=1,
                          ngram_range=(1, 2), max_features=60000)
    counts = vec.fit_transform(joined).toarray().astype(np.float64)
    vocab = np.array(vec.get_feature_names_out())
    tf = counts / np.maximum(counts.sum(axis=1, keepdims=True), 1.0)
    idf = np.log(1.0 + counts.shape[0] / np.maximum((counts > 0).sum(axis=0), 1))
    ctfidf = tf * idf
    out = {}
    for row, cid in enumerate(ids):
        idx = np.flatnonzero(labels == cid)
        centroid = embeddings[idx].mean(axis=0)
        near = idx[np.argsort(-embeddings[idx] @ centroid)[:3]]
        out[int(cid)] = {
            "size": int(len(idx)),
            "terms": vocab[np.argsort(-ctfidf[row])[:top_terms]].tolist(),
            "medoids": [documents[i][:180] for i in near],
        }
    return out

The class-based TF-IDF weighting, in the spirit of BERTopic’s c-TF-IDF (which normalises by average words per class rather than by class count as above), is the right choice over plain TF-IDF because it treats each cluster as one long document and asks what distinguishes it from the other clusters, which is exactly the question a label needs answered. Plain TF-IDF on individual tickets surfaces the words common to the cluster, and the words common to a support cluster are “please”, “issue” and “help”.

Key Insight

The single decision that mattered most was not the linkage or the embedding model. It was the connectivity graph, because it changed the problem from one that needs 340 GB to one that runs in 6 minutes on a laptop, and only after that was it possible to try four linkages, twelve thresholds and ten bootstrap resamples in an afternoon. Ward over average linkage is worth 0.08 ARI. Being able to run the experiment at all is worth the project.

Evaluation and Metrics

Three layers, with clearly separated jobs. External agreement against the human reference set decides whether the themes are the right themes. Bootstrap stability decides whether they will still be there next month. Deflection decides whether any of it was worth doing.

Adjusted Rand index is the external metric, and the adjustment is the whole point. Plain Rand index counts the pairs of tickets that two groupings agree about, which sounds right and is badly biased: with 214 clusters, the overwhelming majority of pairs are in different clusters under both groupings, so agreement-by-accident dominates and raw Rand sits above 0.97 for essentially any clustering. ARI subtracts the expected agreement of a random grouping with the same cluster sizes, which puts a random baseline at 0 and makes the numbers comparable across different cluster counts. That last property is non-negotiable here, because we are comparing a 68-cluster k-means against a 214-cluster hierarchy.

# The three evaluation layers. Only the third one decides anything.
from sklearn.metrics import (adjusted_rand_score, adjusted_mutual_info_score,
                             normalized_mutual_info_score)
import numpy as np

def external_agreement(reference: np.ndarray, predicted: np.ndarray) -> dict:
    """Measured only on reference tickets, at the cut depth actually shipped."""
    return {
        "ari": float(adjusted_rand_score(reference, predicted)),
        "ami": float(adjusted_mutual_info_score(reference, predicted)),
        "nmi": float(normalized_mutual_info_score(reference, predicted)),
    }

def bootstrap_stability(embeddings: np.ndarray, fit_fn, n_resamples: int = 10,
                        frac: float = 0.8, seed: int = 17) -> dict:
    """Mean pairwise ARI on shared points across resampled refits."""
    rng = np.random.default_rng(seed)
    n = embeddings.shape[0]
    runs = []
    for _ in range(n_resamples):
        idx = np.sort(rng.choice(n, size=int(frac * n), replace=False))
        runs.append((idx, np.asarray(fit_fn(embeddings[idx]))))
    scores = []
    for i in range(len(runs)):
        for j in range(i + 1, len(runs)):
            (ia, la), (ib, lb) = runs[i], runs[j]
            shared = np.intersect1d(ia, ib)
            if len(shared) < 100:
                continue
            # idx is sorted, so searchsorted maps a shared id to its row in la.
            pa = la[np.searchsorted(ia, shared)]
            pb = lb[np.searchsorted(ib, shared)]
            scores.append(adjusted_rand_score(pa, pb))
    if not scores:
        return {"mean_pairwise_ari": float("nan"),
                "min_pairwise_ari": float("nan"), "n_comparisons": 0}
    return {"mean_pairwise_ari": float(np.mean(scores)),
            "min_pairwise_ari": float(np.min(scores)),
            "n_comparisons": len(scores)}

def coverage(labels: np.ndarray, min_size: int = 25) -> float:
    """Share of documents in a theme large enough to justify an article."""
    sizes = np.bincount(labels)
    return float(sizes[sizes >= min_size].sum() / sizes.sum())

Baseline against solution, all on the 2,410 held-out reference tickets:

Configuration Reference ARI Bootstrap ARI Coverage at 25 Largest cluster Fit time
Agent taxonomy, 74 categories 0.14 n/a 0.96 39.1% 0
k-means on TF-IDF, k=50 0.08 0.29 0.91 61.4% 2 min 10 s
k-means on embeddings, k=68 0.31 0.44 0.88 9.2% 3 min 40 s
HAC, average linkage, threshold cut 0.66 0.63 0.79 7.3% 5 min 50 s
HAC, Ward, fixed n_clusters=214 0.74 0.52 0.78 6.1% 6 min 05 s
HAC, Ward, threshold 11.8 0.74 0.71 0.78 6.1% 6 min 05 s

Two things in that table are worth more attention than the headline. Coverage goes down as ARI goes up, from 0.88 to 0.78, because finer, more honest themes leave more tickets in groups too small to write an article about. That is a real cost and the guardrail of 0.70 is what stops us pushing the threshold lower to chase ARI. And the two Ward rows differ only in how the cut is specified: identical tree, identical partition on this dataset, 0.19 apart on stability.

The third layer is the one the docs team is judged on. 41 articles shipped against discovered themes over four months; inbound volume for tickets matching those themes fell 18.6% in the 30 days after publication, against 1.3% for a matched set of themes with no article, and agent minutes on the treated themes fell 22.4% because the remaining tickets were resolved by linking the article. The k-means themes had produced 12 articles over the preceding four months with a 4.1% deflection, largely because eight of the twelve targeted the same over-broad cluster.

Metric That Matters

The number that catches a silent regression is **theme continuity**: for each theme in the current hierarchy, the maximum Jaccard overlap of its membership with any theme from the previous rebuild. Reference ARI will not move when this breaks, because the new themes are perfectly good themes. What breaks is that the docs team's 41 article assignments no longer point at anything. We alert when the share of themes with continuity above 0.5 falls below 0.80, and that alarm has fired twice: once for an embedding-model upgrade nobody flagged as a modelling change, and once when a mail-gateway change altered the boilerplate and the stripping rules stopped matching.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Clusters form on boilerplate Signatures and disclaimers are the most consistent text in the corpus, so they dominate any distance Print the 20 nearest tickets to each centroid and read them; look for a giant cluster above 30% Strip quote chains, signatures, disclaimers and log blocks before embedding; re-check cluster sizes
Single linkage chaining Group distance is set by the closest pair, so one bridging document fuses two themes permanently Largest cluster share above 50% with an otherwise sensible threshold Use Ward on normalised embeddings, or complete or average linkage; never single for text
Near-duplicate inflation Re-opens and monitoring tickets make a theme look coherent while representing one real issue Internal cohesion high and reference ARI low; count MinHash duplicate groups per cluster Deduplicate at Jaccard 0.85 before clustering; keep one survivor per group
Incident bursts become themes 4,190 tickets in six hours are genuinely similar, so they form a dense cluster and shift merge heights Check the calendar-day entropy of each theme; a theme concentrated in one day is an event Cap any single day’s contribution before fitting; route bursts to incident detection instead
Disconnected connectivity graph kNN with small n_neighbors fragments the graph, and sklearn bridges the components with arbitrary edges rather than failing connected_components on the graph before fitting; a UserWarning about completing the connectivity matrix Raise n_neighbors until the graph is connected, typically 25 to 40 for text embeddings
Tuning the cut on the reference set The cut depth is a hyperparameter and the reference labels are the only signal available Compare tuned ARI against ARI on a reference subset never used for tuning Split the reference labels; tune the threshold on one half, report on the other
Silhouette used to pick the threshold It is the default clustering metric and it rewards fewer, fatter clusters in high dimensions Silhouette recommends a cluster count an order of magnitude below the human reference Pick the threshold from the merge-height curve, validate against reference ARI and stability
Common Pitfall

The most common beginner mistake on this exact problem is sweeping the cluster count and picking the peak of an internal metric, then treating the result as the number of topics in the corpus. Internal metrics measure geometric compactness, which in 768 dimensions is nearly constant, and they have no access to the thing that makes two tickets the same issue. On this corpus silhouette chose 14 clusters against a human reference of 68, and it chose it confidently, with a smooth curve and a clear peak. A clean-looking optimum in an internal metric is not evidence that the metric is measuring anything you want.

Comparison of single, complete, average and Ward linkage on the same ticket embeddings, showing single linkage chaining two themes through one bridging document into an 84 percent cluster while Ward keeps them separate, alongside the merge height curve and the distance threshold cut at 11.8

Scaling and Productionizing

The pipeline is a monthly batch job and the serving side is a static artefact, which puts almost all of the operational risk in the rebuild rather than in the request path.

Nothing is served in real time. The output is a JSON tree of themes with labels, sizes, medoid tickets and merge heights: 214 themes is 480 KB, and it goes into the docs team’s internal tool as a file. There is no model server and no inference endpoint, because assigning a new ticket to an existing theme is a different problem and we solve it with a nearest-centroid lookup rather than by refitting: cosine against 214 centroids is 0.4 ms and it is honest about being an approximation of where the tree would have put the ticket.

The cost model is dominated by embedding, not by clustering, which is the opposite of what the memory scare suggests:

Raw tickets                   412,000 rows, 1.9 GB of text          = 1.9 GB
After stripping and dedup     353,000 documents, median 71 words    = 0.9 GB
Embedding, mpnet-base-v2      353,000 x 768 float32, 1 A10G GPU     = 19 min, 1.1 GB
kNN graph, n_neighbors 30     ~10.6e6 edges, sparse CSR             = 2 min 40 s, 130 MB
Ward agglomerative fit        353,000 leaves, full tree             = 6 min 05 s, 4.8 GB peak
Relabel at a new threshold    union-find over children_             = 1.4 s
c-TF-IDF labelling            214 clusters, 60k vocabulary          = 48 s
Bootstrap stability, 10 runs  0.8 subsample, refit each             = 41 min
Full monthly rebuild          embed, graph, fit, label              = 28 min 33 s
Served artifact               214 themes as JSON                    = 480 KB

Embedding is 67% of the rebuild, so the first optimisation anyone reaches for is a smaller model. all-MiniLM-L6-v2 at 384 dimensions cuts embedding to 6 minutes and costs 0.05 reference ARI, which is a trade we would take for a daily job and do not need for a monthly one. Bootstrap stability is more expensive than the model itself and runs weekly rather than monthly, on a 60,000-document subsample, because it is a diagnostic rather than a deliverable.

Above roughly 2 million documents the Ward fit stops fitting comfortably and the answer is two-stage clustering: MiniBatchKMeans to 20,000 micro-clusters, then Ward on the micro-centroids weighted by size. Reference ARI drops about 0.03 and the fit becomes minutes at any corpus size, because the hierarchy is built over 20,000 points rather than 2 million. This is the idea behind BIRCH (Zhang, Ramakrishnan and Livny, 1996), which sklearn ships as Birch: summarise the data into micro-clusters in one pass, then run the expensive hierarchical step over the summaries. It is what makes hierarchical methods usable at web scale.

Refresh cadence is set by theme drift. We rebuild monthly and the measurement that justified monthly rather than quarterly is theme continuity decay: 0.93 of themes have continuity above 0.5 after one month, 0.81 after two, 0.64 after three. A quarterly cadence would spend its final month with a third of the assignments pointing at themes that no longer describe the inbound mix.

The monitoring signal for silent degradation is the pair (theme continuity, coverage). Continuity catches the hierarchy reorganising under the docs team. Coverage catches the quieter failure: a change in the mail gateway, a new ticketing integration, or a product launch can push tickets into groups below the 25-member floor, coverage slides from 0.78 toward 0.60, and the tool shows fewer and fewer actionable themes with no error anywhere. Coverage below 0.70 pages someone; continuity below 0.80 blocks publishing the new hierarchy until a human has mapped the old assignments across.

Real World

Hierarchical clustering for document grouping has one canonical production lineage: Topic Detection and Tracking, the DARPA programme that ran from 1997 and produced the first-story-detection systems behind news aggregation. Allan, Papka and Lavrenko's 1998 SIGIR paper set the pattern still in use, single-pass incremental clustering with a similarity threshold, and Petrovic, Osborne and Lavrenko's 2010 NAACL work on Twitter replaced the exhaustive comparison with locality-sensitive hashing to make it tractable at stream rates, which is the same move as the connectivity graph here. On the tooling side, BERTopic is the current default for exactly this task and is worth reading as an engineering decision rather than a novel algorithm: it composes UMAP for dimensionality reduction, HDBSCAN for density clustering, and the class-based TF-IDF labelling used above. Its choice of HDBSCAN over agglomerative is the right one when you want outliers explicitly rejected, and the wrong one when a documentation team needs every ticket to live somewhere in a tree they can walk.

Alternative Approaches

Approach Reference ARI Fit cost at 353k docs Interpretability Best fit
HAC, Ward plus kNN connectivity 0.74 6 min, 4.8 GB, full tree reusable Excellent: a walkable tree with comparable merge heights A human consumes the structure and needs several resolutions at once
HDBSCAN on UMAP projection 0.71 11 min, 6.2 GB, outliers labelled minus one Good, but 19% of tickets rejected as noise Outliers are genuinely uninteresting and you want them excluded rather than placed
k-means on embeddings, k tuned 0.31 3 min 40 s, 0.9 GB Moderate: flat labels, no nesting, k is an input Fast flat segmentation where the cluster count is known from outside
Gaussian mixture, full covariance 0.38 14 min, 8.1 GB, soft assignments Moderate: responsibilities are informative, components are not readable Overlapping memberships matter more than a hierarchy
BERTopic, default composition 0.69 16 min end to end including labelling Excellent labels, flat topics with an optional hierarchy on top You want a maintained library and topic labels out of the box
LDA, 200 topics on cleaned text 0.28 22 min, 2.1 GB Good: topics are word distributions, tickets are mixtures Long documents with genuine multi-topic structure, not short tickets

What we would actually ship, and did, is the top row, and the reason is entirely about the consumer. The docs team does not want a partition, they want to zoom. A tree fitted once and relabelled in 1.4 seconds at any threshold gives them a slider from 61 broad areas to 806 specific issues, and no flat method can offer that without refitting. HDBSCAN is close behind on ARI and would be the better choice for a different consumer: an alerting system that needs to say “this ticket belongs to no known theme” benefits from explicit noise rejection, where our pipeline is forced to put every ticket somewhere.

We would switch to HDBSCAN on UMAP if the primary use case became novel-issue detection rather than documentation coverage, and to the two-stage pre-clustered variant the moment the corpus crossed roughly 2 million documents. LDA is on the table only for a corpus of long documents; on 71-word median tickets the multi-topic assumption it is built around is simply false, and the 0.28 reflects that rather than any implementation problem.

Key Takeaways

  • The linkage function matters more than the embedding. Same vectors, same graph, same cut depth: single linkage gave 0.09 ARI and Ward gave 0.74. A 0.65 spread from one argument is larger than any gain we got from changing the embedding model.
  • Sparse connectivity is what makes hierarchical clustering a production method. A kNN graph at n_neighbors=30 turned 62.3 billion candidate pairs into about 10.6 million edges, and a 249 GB condensed distance matrix into a 130 MB sparse graph. The reputation of HAC as a toy-data algorithm is an artefact of the dense-matrix implementation, not of the algorithm.
  • Cut by distance, not by count. Identical tree, identical partition today, bootstrap stability 0.52 against 0.71. A fixed cluster count forces merges that the data does not support in order to hit a number.
  • L2-normalise before Ward. It is what lets a Euclidean-only linkage behave like cosine geometry, since squared Euclidean on unit vectors is monotone in cosine for every pair. Skipping it quietly lets document length drive the merges.
  • Internal metrics do not measure what you want. Silhouette chose 14 clusters against a human reference of 68 and ranked configurations nearly in reverse. It rewards compactness, and in 768 dimensions compactness is close to constant.
  • Clustering leaks. Near-duplicates raised every internal cohesion number while lowering reference agreement, and a single six-hour incident burst of 4,190 tickets presented itself as a theme. Both had to be removed before fitting, not explained afterwards.
  • A cluster without a label is not a deliverable. Class-based TF-IDF plus three medoid tickets is roughly 20 lines and it is the difference between an output a support lead acts on and a label array nobody opens.
  • Stability is the metric the consumer feels. Reference ARI decides whether the themes are right; theme continuity across rebuilds decides whether last month’s 41 article assignments still mean anything, and only the second one ever produced a complaint.

The counter-intuitive lesson is that the best offline configuration and the best product were separated by a constraint nobody wrote down. Coverage fell from 0.88 to 0.78 as ARI rose from 0.31 to 0.74, because honest themes are smaller themes and a smaller theme eventually stops justifying an article. There is a threshold slightly below 11.8 with marginally higher reference ARI, and we did not ship it, because it pushed coverage under 0.70 and handed the docs team a more accurate description of a corpus they could do less about. The clustering got better and the deliverable got worse, and no internal or external clustering metric can see that trade: only the guardrail can.

Frequently Asked Questions

Q: Why not use HDBSCAN, which handles noise and needs no cluster count either? A: We use it for a different job. It scored 0.71 against Ward’s 0.74, which is close enough to be noise, and the real difference is that it labelled 19% of tickets as outliers. For novel-issue detection that is the feature you want. For documentation coverage it means 67,000 tickets belong nowhere in the deliverable, and the docs team’s first question was what happened to them. HDBSCAN also gives a condensed tree rather than a full dendrogram, so the slider from 61 to 806 themes is not available in the same way.

Q: Why not just use more clusters in k-means and get the fine-grained themes that way? A: Because the problem is not granularity, it is nesting and stability. k-means at k=214 gave 0.44 reference ARI, well below Ward at the same count, and bootstrap stability of 0.39, because k-means at high k is extremely sensitive to initialisation on data with no clear separation. The deeper issue is that the docs team needs the relationship between a broad theme and its sub-themes, and a flat partition at any k has thrown that away by construction.

Q: Is the connectivity constraint not just an approximation that damages the result? A: It is an approximation and it does change the answer, which is why the n_neighbors sweep matters: 10 fragments the graph, 30 gives 0.74, 100 gives 0.75 at three times the runtime. The approximation costs roughly 0.01 ARI against the densest setting we could measure, and it buys the ability to run the full experiment matrix. It also has a defensible interpretation: restricting merges to locally similar pairs is a prior that documents only join through genuine neighbourhoods, which is closer to how a human groups tickets than an unconstrained global search.

Q: How do I choose the distance threshold without peeking at labels? A: Take candidates from the merge-height curve, where the largest gaps in the top few hundred merge distances mark natural stopping points, then choose among those candidates using bootstrap stability, which needs no labels at all. On this corpus the merge-height curve offered 12 candidates between 5.8 and 26.4, and stability alone picked 11.8, the same threshold reference ARI preferred. Labels then confirm the choice rather than making it, which also keeps the reference set clean for reporting.

Q: Why ARI rather than NMI or V-measure? A: All three are label-invariant, but only ARI and AMI are corrected for chance: NMI and V-measure are normalised, which is a different thing, and that is exactly why they drift upward as you add clusters. NMI and V-measure both increase as you add clusters, which matters enormously here because we compare a 68-cluster k-means against a 214-cluster hierarchy: our NMI comparison favoured the hierarchy by more than ARI did, and the gap was mostly an artefact of the count. AMI corrects this and we report it alongside; when AMI and ARI disagree, the disagreement is usually about how much credit to give for splitting a reference theme in two, and that is a judgement call to make explicitly rather than to delegate to the metric.

Q: What breaks first in production? A: Theme continuity, usually after a change nobody classified as a modelling change. An embedding-model upgrade reorganises the tree, the new themes are perfectly good themes, every metric looks fine or better, and the docs team’s 41 article assignments silently stop pointing at anything. Track the maximum Jaccard overlap of each new theme against the previous hierarchy and gate publication on it, because this failure is completely invisible from inside the model.

Interview Questions

Q: You have 500,000 documents and need a dendrogram. The distance matrix does not fit in memory. What do you do? Expected depth: Start with the arithmetic: 500,000 squared over 2 is 1.25e11 pairs, 500 GB at float32, so a dense matrix is out. Then give the two real options and their costs. A sparse connectivity constraint from a kNN graph restricts merges to graph edges, cutting the candidate set by four orders of magnitude, at the price of biasing the tree toward locally dense structure and the risk of a disconnected graph producing a forest. Two-stage pre-clustering, MiniBatchKMeans to 20,000 micro-clusters then Ward on size-weighted centroids, makes cost independent of corpus size at the price of freezing the micro-cluster boundaries. Mention that Ward and average linkage support the nearest-neighbour-chain algorithm at O(n squared) time and O(n) memory, which changes the memory story but not the time story.

Q: Explain why single linkage fails on text and Ward does not. Expected depth: Define both: single linkage takes the minimum distance between any cross-pair, Ward merges the pair minimising the increase in total within-cluster sum of squares. Single linkage is therefore decided by one document per merge, so an ambiguous bridging document fuses two themes irreversibly, and with hundreds of thousands of documents there are thousands of bridges, giving the chaining effect and a mega-cluster. Ward’s objective is a variance increase over the whole union, so no single point can force a merge. Add the Lance-Williams framework as the unifying view, and note Ward’s bias toward equal-sized clusters as the cost, along with its Euclidean-only requirement and why L2-normalisation makes that acceptable for cosine-similar text: squared Euclidean on unit vectors is monotone in cosine pairwise, though Ward’s centroid-based objective is not literally a cosine objective.

Q: Your silhouette score says 14 clusters and your domain experts say about 70. Who is right, and how would you settle it? Expected depth: The experts, and the interesting part is why the metric is confidently wrong. Silhouette compares mean intra-cluster distance against mean nearest-cluster distance, which in high dimensions concentrates: both quantities converge and the ratio carries little information. It also monotonically rewards merging genuinely distinct but adjacent groups, since fewer fatter clusters are more compact by this definition. Settle it with an external metric on a small labelled reference sample, ARI or AMI, and with bootstrap stability, which needs no labels. Say explicitly that internal metrics are appropriate for comparing runs of the same algorithm at the same cluster count and inappropriate for choosing the cluster count.

Q: How would you evaluate a document clustering system before shipping it? Expected depth: Three layers with distinct jobs. External agreement against a human-labelled reference sample, ARI or AMI, reported on reference labels never used to tune the cut depth, to answer whether the groups are the right groups. Bootstrap stability, mean pairwise ARI across refits on resampled subsets, to answer whether they survive a rebuild. A downstream operational metric, here ticket deflection after articles ship, as the only real launch gate. Be explicit that internal metrics do not belong in this list, and that the reference set has to be split because the cut threshold is a hyperparameter fitted to whatever signal it is shown.

Q: A month after launch the hierarchy is completely reorganised but every metric looks the same or better. What happened and what do you do? Expected depth: Recognise this as the clustering-specific version of label instability. Clustering has no canonical labelling, so a rebuild can produce an equally good or better partition whose cluster identities bear no relation to the previous one, and every quality metric is invariant to exactly the thing that broke. Likely causes: an embedding-model change, a text-pipeline change that altered what was stripped, a shift in the inbound mix, or a fixed cluster count forcing different merges on slightly different data. The fix is a continuity metric, maximum Jaccard overlap per theme against the previous rebuild, plus a mapping step that carries old identities forward where overlap is high enough, and a cut specified by distance rather than count so that stable structure produces stable output.

View full code for this problem