Most eval sets are written from the inside out. Someone on the team lists the requests they expect the feature to handle, writes twenty or fifty cases around them, and the suite becomes the definition of "working." Then the feature ships, and users ask for things nobody on the team imagined: a support bot gets used as a translator, a code assistant gets pasted entire log files, a search box receives full sentences in three languages. The eval still passes, because it is measuring the product the team designed rather than the one people use.
The fix is not to write more cases from imagination. It is to look at what users actually send, group it into intents, and compare those groups against what your eval set covers. This article walks through a small, repeatable way to do that with embeddings and density-based clustering, and explains where the method misleads you.
Why clustering, and why not just read the logs
Reading a random sample of production queries is valuable, but it has two weaknesses for coverage work. First, it is biased toward the head: in a sample of 200 queries, an intent that makes up 2% of traffic shows up about four times, which is easy to dismiss as noise. Second, it produces impressions, not a table. "People seem to ask a lot about billing" is hard to turn into a decision about which eval cases to add.
Clustering gives you a table. Each row is a group of semantically similar queries, with a size, a few representative examples and some distinguishing terms. Once your eval cases are mapped onto the same rows, the gap is visible as a number: this cluster is 6% of traffic and has zero eval cases.
The choice of algorithm matters. K-means forces you to pick the number of clusters up front and assigns every query to some cluster, including the one-off oddities. A density-based method such as HDBSCAN needs no cluster count and labels points outside any dense region as noise, which turns out to be useful information. scikit-learn has shipped sklearn.cluster.HDBSCAN since version 1.3, so there is no extra dependency beyond scikit-learn itself.
A worked pipeline: from query log to coverage table
The pipeline has five steps: sample, embed, cluster, describe, and map the eval set. The code below assumes you already have an embed(texts) -> np.ndarray function wrapping whatever embedding model you use in production, and a list of eval case inputs.
import numpy as np
from collections import Counter
from sklearn.cluster import HDBSCAN
from sklearn.feature_extraction.text import TfidfVectorizer
def unit(v):
return v / np.linalg.norm(v, axis=1, keepdims=True)
# 1. Sample: a few thousand recent, de-duplicated, redacted queries.
queries = load_redacted_queries(days=14, limit=5000)
queries = list(dict.fromkeys(q.strip() for q in queries if q.strip()))
# 2. Embed and L2-normalize, so Euclidean distance ranks pairs
# the same way cosine distance does.
Q = unit(embed(queries))
# 3. Cluster. min_cluster_size is the smallest group you would
# write eval cases for; start around 0.5% of the sample.
hdb = HDBSCAN(min_cluster_size=max(10, len(queries) // 200), min_samples=5)
labels = hdb.fit_predict(Q)
# 4. Describe each cluster: size, distinguishing terms, exemplars.
tfidf = TfidfVectorizer(ngram_range=(1, 2), max_df=0.5, stop_words="english")
X = tfidf.fit_transform(queries)
terms = tfidf.get_feature_names_out()
clusters = {}
for c in sorted(set(labels) - {-1}):
idx = np.where(labels == c)[0]
centroid = unit(Q[idx].mean(axis=0, keepdims=True))[0]
top_terms = terms[np.asarray(X[idx].mean(axis=0)).ravel().argsort()[-6:][::-1]]
exemplars = [queries[i] for i in idx[np.argsort(-hdb.probabilities_[idx])][:5]]
clusters[c] = dict(size=len(idx), centroid=centroid,
terms=list(top_terms), exemplars=exemplars)
# 5. Map eval cases onto clusters by nearest centroid, with a cutoff.
E = unit(embed(eval_inputs))
C = np.stack([clusters[c]["centroid"] for c in clusters])
ids = list(clusters)
sims = E @ C.T
nearest = sims.argmax(axis=1)
eval_counts = Counter(ids[j] for k, j in enumerate(nearest)
if sims[k, j] >= SIM_CUTOFF)
n = len(queries)
for c in sorted(clusters, key=lambda c: -clusters[c]["size"]):
info = clusters[c]
print(f"{info['size']/n:6.1%} evals={eval_counts.get(c, 0):3d} "
f"{', '.join(info['terms'])}")
print(f"noise: {(labels == -1).mean():.1%} of sampled traffic")Normalizing before clustering. HDBSCAN defaults to Euclidean distance. For unit-length vectors, squared Euclidean distance equals 2 minus twice the cosine similarity, so normalizing lets you use the default metric while getting the neighbourhood structure most embedding models are designed for.
`min_cluster_size` as a business threshold. This parameter is the minimum number of samples HDBSCAN will call a cluster; smaller groupings become noise. Set it to the smallest slice of traffic you would actually act on. If you would never write eval cases for an intent below half a percent of traffic, there is no point asking the algorithm to find one.
Exemplars by membership strength. probabilities_ reports how strongly each point belongs to its cluster (noise points get zero). Picking the top five gives you the most typical queries rather than borderline ones, which makes the cluster easier to name.
TF-IDF terms as labels, not truth. The top terms are a quick hint for a human reviewer. They are not the cluster's meaning; the exemplars are. You can ask an LLM to propose a one-line name from the exemplars, but have a person confirm it, because a confident wrong label is how a coverage table starts lying.
A similarity cutoff when mapping evals. Without SIM_CUTOFF, every eval case gets assigned to some cluster, even if it resembles nothing users send. Calibrate it by inspecting a dozen eval cases next to their nearest cluster's exemplars and picking the value below which the pairing stops making sense. Eval cases that fall below it everywhere are worth a second look too: they may be testing an intent nobody has.
Reading the coverage table
The output is a list of clusters sorted by share of traffic, each with an eval count. Three patterns are worth acting on.
High traffic, zero or few evals. This is the main thing you are looking for. Before writing cases, read twenty or thirty queries from the cluster, not just the five exemplars, and decide whether the intent is something the feature should handle well, should decline politely, or should route elsewhere. All three outcomes deserve eval cases; the expected output just differs.
Low traffic, many evals. Not necessarily a problem. Rare but high-stakes intents (account deletion, refunds, anything legal or safety-related) should be over-represented in an eval set. But if a cluster is over-covered simply because it was the team's mental model of the product, you have found cases you can thin out or move to a slower tier of the suite.
A large noise fraction. If a third of your sampled queries end up labelled -1, either your traffic is genuinely long-tailed or the embedding space is not separating intents well for your domain. Read a sample of the noise. If it is mostly one-off oddities, that is fine and tells you your eval set cannot cover everything by intent alone. If it contains recognisable intents, lower min_cluster_size, try min_samples lower than the default (which otherwise equals min_cluster_size), or test whether a different embedding model separates your domain better.
Record the table with the date and the sample window. Re-running it monthly, or after a launch that changes how people reach the feature, shows you new clusters appearing, which is often the earliest sign that usage has shifted.
Where this method misleads you
Embeddings group by topic, not by difficulty. "Summarize this contract" and "summarize this contract, which is in Portuguese and 80 pages long" will likely land in the same cluster. The eval set may cover the intent but none of the hard variants. Pair the cluster view with slices on input length, language and attachment type.
Surface form can dominate. Queries that share a template, such as an auto-generated prefix from a client integration, can cluster together regardless of what they ask. Strip known boilerplate before embedding.
Duplicates inflate clusters. A single user retrying the same request twenty times can create a cluster. The de-duplication step helps for exact repeats; for near-duplicates, cap the number of queries per user or session in your sample.
The sample is a window. Two weeks of traffic will miss seasonal intents and anything that only happens at month-end. If your product has known cycles, sample across them.
Privacy is not optional. Production queries contain personal data. Run redaction before the pipeline, keep the clustering output inside the same access boundary as the raw logs, and do not paste exemplars into eval files without checking them. When you write eval cases from a cluster, paraphrase or synthesise inputs that preserve the intent rather than copying user text.
Clusters are not stable labels. HDBSCAN results change when the sample changes. Do not build dashboards keyed on cluster IDs. Instead, maintain a small named intent list that a person curates, and use each run of the pipeline to propose additions to it.
Checklist
- Sample a few thousand recent queries; redact, strip boilerplate, de-duplicate, and cap per-user contributions.
- Embed with your production embedding model and L2-normalize.
- Run HDBSCAN with
min_cluster_sizeset to the smallest traffic share you would act on. - For each cluster, record size, top terms and the five highest-membership exemplars; have a person name it.
- Map eval inputs to cluster centroids with a calibrated similarity cutoff.
- Act on high-traffic clusters with no eval cases: decide handle, decline or route, then write cases (paraphrased, not copied).
- Read a sample of the noise label before dismissing it.
- Add slices for length, language and input type, because clusters only capture topic.
- Re-run on a schedule and diff the cluster list against your curated intent list.
Further reading
- scikit-learn, `sklearn.cluster.HDBSCAN`: parameters, noise labels and
probabilities_. - scikit-learn, Clustering user guide, HDBSCAN section.
- scikit-learn, `TfidfVectorizer`.
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.