Sub topic 10
Checking the Set Against Held-Out Real Questions
This chapter assumes you have read the earlier chapters on cleaning, clustering, intent labels, phrasing and sampling. You should be comfortable reading short Python scripts. By now you have a draft prompt set. This chapter covers how to test it against real questions that played no part in building it, so you can tell whether it reflects what customers ask.
Why a draft set needs an outside check
Every step so far used judgement. You chose cluster boundaries, rewrote questions into prompts and picked sampling quotas. A set can look reasonable to its builders and still be skewed. If you check the set against the same questions you built it from, the check will pass, because those questions shaped the set.
A held-out set is a slice of real questions that you set aside before building and never look at while building. It acts as an independent sample of real demand. You compare the finished prompt set to it and ask three questions:
- Does the prompt set cover the same topics and intents as the held-out questions?
- Is the share of each topic similar?
- Do the held-out questions use wording that the prompts also use?
Hold out before you cluster
The split must happen early, right after cleaning and deduplication and before intent labelling, clustering or sampling. If the held-out questions influence the cluster centres or the taxonomy, they are no longer independent.
Split by unique normalised question, not by raw rows. The cleaning step already merged duplicates. If a duplicate survives on both sides of the split, the held-out set tests memory instead of coverage.
The loop back to labelling is deliberate. When a check fails, you fix the build side. Do not fix the problem by moving held-out questions into the build side. That would spoil the test, and you would need a fresh held-out slice for the next round.
import random
def split_holdout(rows, fraction=0.2, seed=11):
"""Return (build_rows, heldout_rows). Same seed gives the same split."""
rng = random.Random(seed)
ordered = sorted(rows, key=lambda r: r["id"])
rng.shuffle(ordered)
cut = max(1, round(len(ordered) * fraction))
return ordered[cut:], ordered[:cut]Sorting by id before shuffling makes the split reproducible even if the input order changes between runs. Store the held-out IDs in a file and treat that file as read-only.
How big should the held-out set be? Twenty percent is a common default. For small collections, the number of held-out questions per cluster matters more than the percentage. If a cluster has only two held-out questions, its share is too noisy to interpret. In that case, report the cluster as "too few to judge" instead of calling it a pass or fail.
Check 1: topic and intent coverage
The first check is simple. List every cluster and intent that appears in the held-out set. Confirm that each one also appears in the prompt set.
A held-out question needs a cluster label to take part. Assign it by running it through the same labelling step, such as the same classifier or the same nearest-cluster rule. Do not label it by hand with a different standard. A cluster that exists in the held-out set but not in the prompt set is a real gap. It usually means that sampling dropped a rare topic, or that clustering merged it into a neighbour.
Be careful with the opposite case. A cluster in the prompt set that never appears in the held-out set is not automatically wrong. It may be a rare topic that you deliberately oversampled with a minimum quota. Record it as intentional so that later readers don't remove it.
Check 2: do the shares match?
Coverage says what is present. Shares say how much. Compute each cluster's share of the held-out questions, weighting each question by its count field. That weighting reflects real demand, because a question asked 37 times matters more than one asked once.
Then compute each cluster's share of the prompt set. Here you usually count each prompt once, since each prompt is run once during measurement.
To summarise the gap in one number, use total variation distance. It is half the sum of the absolute differences between the two share tables. It runs from 0 (identical) to 1 (no overlap). It reads directly as "the fraction of the set that would have to move to another cluster to match demand".
import re
from collections import Counter
def cluster_shares(rows, weighted):
totals = Counter()
for row in rows:
totals[row["cluster"]] += row.get("count", 1) if weighted else 1
grand = sum(totals.values())
return {name: n / grand for name, n in totals.items()}
def total_variation(p, q):
keys = set(p) | set(q)
return 0.5 * sum(abs(p.get(k, 0.0) - q.get(k, 0.0)) for k in keys)
def tokens(text):
return set(re.findall(r"[a-z0-9']+", text.lower()))
def jaccard(a, b):
union = a | b
return len(a & b) / len(union) if union else 0.0
def wording_coverage(prompts, heldout, threshold=0.3):
prompt_tokens = [tokens(p["text"]) for p in prompts]
unmatched = []
for row in heldout:
ht = tokens(row["text"])
best = max((jaccard(ht, pt) for pt in prompt_tokens), default=0.0)
if best < threshold:
unmatched.append((row["id"], round(best, 2)))
matched = len(heldout) - len(unmatched)
return matched / len(heldout), unmatched
prompts = [
{"id": "q-0042", "cluster": "account_management",
"text": "Can I move my subscription to a different email address?"},
{"id": "q-0107", "cluster": "billing",
"text": "How do I cancel my plan?"},
]
heldout = [
{"id": "q-9001", "cluster": "account_management", "count": 10,
"text": "How can I change the email on my subscription?"},
{"id": "q-9002", "cluster": "billing", "count": 30,
"text": "Why was I charged twice this month?"},
]
shares_prompts = cluster_shares(prompts, weighted=False)
shares_heldout = cluster_shares(heldout, weighted=True)
missing = sorted(set(shares_heldout) - set(shares_prompts))
coverage, unmatched = wording_coverage(prompts, heldout)
print("missing clusters:", missing)
print("share distance:", round(total_variation(shares_prompts, shares_heldout), 2))
print("wording coverage:", coverage)
print("unmatched:", unmatched)With this toy data the script prints no missing clusters, a share distance of 0.25, a wording coverage of 0.5, and one unmatched question, q-9002, with a best score of 0.08. The prompt set splits 50/50 between the two clusters, but demand is 25/75. The "charged twice" question has no similar prompt at all, even though its cluster is present. That second finding is the reason the wording check exists.
Check 3: wording match
A cluster can be present while every prompt in it uses different words from customers. This check looks for that. For each held-out question, find the most similar prompt and record the score. Questions whose best score falls below a threshold are "unmatched". Read them, because they show what the prompt set cannot currently represent.
The script uses word overlap (Jaccard similarity), which is the number of shared words divided by the number of distinct words in both. It is crude but needs no libraries and is easy to explain. Two things to know about it:
- It rewards shared filler words such as "how", "I" and "my". Removing stop words can help, but it can also remove words that carry intent, such as "not" or "without". Test both on a sample.
- It misses paraphrases. In the example, "move my subscription to a different email address" and "change the email on my subscription" ask the same thing, yet they score only about 0.36. Embedding similarity handles paraphrases better, but its scores are harder to interpret and depend on the model you pick.
Whichever measure you use, set the threshold by reading, not by guessing. Take 30 pairs scored near your proposed cutoff and mark each one as "same question" or "different question" by hand. Move the threshold until the automatic decision agrees with your reading on most pairs. Record the threshold with the set.
Reading the results
| Finding | Likely cause | Fix on the build side |
|---|---|---|
| Held-out cluster missing from the prompt set | Minimum quota too low, or cluster merged into another | Raise `min_per_cluster` or split the merged cluster |
| High share distance, same clusters | Sampling is proportional to unique questions, not to demand | Weight by `count`, or accept the difference and document it |
| Many unmatched held-out questions in one cluster | Prompts were written in internal wording | Rewrite those prompts from real phrasing in that cluster |
| Intent present in held-out set but absent from prompts | Taxonomy collapsed an intent, or sampling skipped it | Add prompts for that intent |
| Everything matches almost perfectly | Leakage between build and held-out sides | Check the split order and look for near-duplicates |
The last row deserves attention. A result that is too good is a warning sign. Near-duplicates such as "cancel my plan" and "How do I cancel my plan?" can survive normalisation and end up on both sides. Run the wording check between the build side and the held-out side. If many held-out questions have a near-identical twin in the build data, re-split after a stricter deduplication pass.
Deciding whether it passes
Choose pass criteria before you look at the numbers, and write them down. Reasonable starting points, which you should adjust to your data, are:
- Every held-out cluster with enough questions to judge is present in the prompt set.
- Share distance is below a limit that you chose in advance, such as 0.15, or each gap is explained as intentional rare-topic oversampling.
- At least a chosen fraction of held-out questions, such as 80 percent, have a close prompt.
- You have read every unmatched question and classified it as a gap to fix, a one-off to ignore, or noise.
Common mistakes
- Splitting after clustering. The held-out questions have already shaped the clusters, so coverage looks better than it is.
- Comparing weighted to weighted. If the prompt set is weighted by
countand the held-out set is too, you hide the fact that each prompt runs once. - Treating a small cluster's share as precise. With three held-out questions, one extra question moves the share by a third.
- Hand-labelling held-out questions more carefully than build questions. This makes the two sides inconsistent, and the comparison measures the labelling difference.
- Ignoring unmatched questions. The list of unmatched held-out questions is the most useful output of this chapter. It tells you what to write next.
Exercise
A teammate clusters all 5,000 cleaned questions, samples 300 prompts, and then picks 500 questions at random from the original 5,000 as a "held-out set" to validate. Name two problems and say how to fix the process.
Show answer
First, the held-out questions were part of the clustering input, so they shaped the clusters and are not independent. Second, 300 prompts were sampled from the same 5,000, so many of the 500 are probably the very questions that became prompts, which makes coverage and wording matches look inflated. Fix it by splitting off the held-out questions with a fixed seed right after cleaning and deduplication. Then cluster and sample only from the build side. Run the checks on the finished prompt set against the locked held-out side.
Exercise
In the example code, the prompt set is 50/50 between account_management and billing, while held-out demand is 25/75. The share distance is 0.25. Describe two reasonable responses and one reason you might choose to leave the gap alone.
Show answer
One response is to add or reweight billing prompts so that billing makes up roughly 75 percent of the set. Another is to keep the set balanced but report results per cluster and weight them by held-out demand when you compute an overall score. You might leave the gap if the account_management topic is small but high-stakes, so you intentionally oversample it. In that case, record the choice as intentional so that later reviewers don't treat it as an error.