Sub topic 9
Sampling so the set matches real demand and still covers rare topics
This chapter assumes you have already cleaned and deduplicated your questions, labelled each with an intent, and grouped them into topic clusters. It also assumes you can read short Python scripts. If your records do not yet carry cluster, intent and count fields, go back to the earlier chapters first.
By now you probably have thousands of unique questions. You cannot run all of them against every AI assistant on every refresh, so you must choose a subset. The way you choose decides what your measurements mean.
The two goals that pull against each other
A prompt set serves two purposes at once.
- Representativeness. If 40% of real customers ask about billing, then about 40% of your prompts should be about billing. Otherwise a headline score such as "the assistant mentions us in 55% of answers" does not describe what customers experience.
- Coverage. Some topics are rare but matter a great deal. Examples are account security, cancellation, safety warnings and legal terms. If you sample strictly in proportion, these topics may get zero prompts, and you will never see a failure there.
Pure proportional sampling gives the first goal and loses the second. Pure equal sampling per cluster gives the second and distorts the first. The usual answer is a hybrid: allocate by demand, then apply a floor, then report the results in a way that undoes the distortion the floor introduced.
Choosing the unit of demand
Your deduplication step collapsed repeated questions into one record with a count. That has a consequence you must handle on purpose.
- Counting records per cluster measures how many different questions exist. A cluster with many unusual phrasings looks large even if few customers ask them.
- Summing
countper cluster measures how often customers actually asked. This is the better proxy for demand.
The record-based version is simpler and is fine for a first pass. The count-based version matches real demand more closely. The code later in this chapter supports both.
| Allocation basis | What a cluster's share means | Risk |
|---|---|---|
| Number of unique records | Variety of phrasings | Over-weights topics with many near-unique questions |
| Sum of `count` | Frequency of asking | Over-weights topics where one question dominates |
| Equal per cluster | Every topic matters the same | Distorts the headline numbers |
| Hybrid (demand plus floor) | Demand, with a safety net | Final size drifts from the target |
How the allocation works
The process has four steps. Work out each cluster's share of demand, convert it to a prompt quota, raise small quotas to a floor, and cap each quota at the number of questions that exist.
Each step has an edge case.
- Rounding. Each quota is rounded separately, so the quotas rarely add up to exactly the requested total.
- The floor. A cluster with a 1% share of a 20-prompt set gets a quota of zero, so the floor lifts it to 2 or more. Every lift adds prompts beyond the target.
- The cap. A cluster with only one question cannot supply a floor of 2. Without the cap,
random.sampleraises aValueError. - The seed. A fixed seed makes the sample repeatable. It only works if the input order is also fixed, because Python dictionaries keep insertion order.
A runnable implementation
The function below follows the allocation steps. It sorts clusters and rows before sampling so the same data always yields the same prompts, whatever order the rows arrived in. It can also pick within a cluster in proportion to count, so that common phrasings are more likely to appear.
import random
from collections import Counter, defaultdict
def weighted_pick(items, k, rng):
"""Pick k items without replacement, favouring higher 'count'."""
keyed = sorted(
items,
key=lambda r: rng.random() ** (1 / r["count"]),
reverse=True,
)
return keyed[:k]
def sample_prompts(rows, total, min_per_cluster=2, seed=7,
by_demand=True, favour_common=False):
rng = random.Random(seed)
by_cluster = defaultdict(list)
for row in sorted(rows, key=lambda r: r["id"]):
by_cluster[row["cluster"]].append(row)
def demand(items):
return sum(r["count"] for r in items) if by_demand else len(items)
grand = sum(demand(items) for items in by_cluster.values())
chosen = []
for cluster in sorted(by_cluster):
items = by_cluster[cluster]
share = round(total * demand(items) / grand)
k = min(len(items), max(min_per_cluster, share))
if favour_common:
chosen.extend(weighted_pick(items, k, rng))
else:
chosen.extend(rng.sample(items, k))
return chosen
def demo_rows():
rows = []
sizes = {"billing": 60, "account_management": 30,
"shipping": 8, "security": 2}
for cluster, n in sizes.items():
for i in range(n):
rows.append({"id": f"{cluster}-{i:03d}",
"cluster": cluster,
"count": 1 + i % 5})
return rows
if __name__ == "__main__":
rows = demo_rows()
picked = sample_prompts(rows, total=20)
sizes = Counter(r["cluster"] for r in picked)
print(dict(sorted(sizes.items())), len(picked))
again = sample_prompts(list(reversed(rows)), total=20)
print([r["id"] for r in picked] == [r["id"] for r in again])Running it prints {'account_management': 6, 'billing': 12, 'security': 2, 'shipping': 2} 22 and then True.
The target was 20, but the set has 22 prompts. Billing and account management received their proportional quotas of 12 and 6. Shipping would have received 1 and security 0, and the floor raised both to 2. The second line shows that reversing the input order does not change the result.
The rng.random() ** (1 / count) key is a standard way to draw without replacement with weights. A question with count 5 is more likely to rank near the top than one with count 1, but low-count questions can still be chosen. That keeps some rare wording in each cluster.
Dealing with size drift
You will usually want to know the final size before you run the set, because each prompt costs time and money across several assistants. You have three options.
- Accept the drift. If the difference is a few prompts, say so in the set's documentation and move on.
- Trim proportionally. If the set is over the limit, remove prompts from the largest clusters first, and never go below the floor.
- Raise the target, then trim. Ask for slightly more than you need, then cut back under the same rule.
Do not trim by removing from the smallest clusters. That undoes the point of the floor.
Choosing what the floor protects
A flat floor of 2 per cluster is a blunt tool. Clusters differ in how costly a wrong answer is, so consider a per-cluster floor.
- A cluster about refunds, security or safety may deserve 5 prompts even if few customers ask.
- A cluster about a discontinued product may deserve the plain minimum.
- A cluster you suspect is under-reported, for example because customers rarely write support tickets about it, may deserve a higher floor until you collect more data.
Decide these floors from business risk, and write the reasons down next to the numbers. A floor that nobody can explain tends to be raised or removed arbitrarily at the next refresh.
FLOORS = {"security": 5, "billing": 3}
DEFAULT_FLOOR = 2
def floor_for(cluster):
return FLOORS.get(cluster, DEFAULT_FLOOR)To use this, replace min_per_cluster in sample_prompts with floor_for(cluster).
Stratifying by intent as well as cluster
Clusters describe what a question is about. Intent describes what the customer wants to do. If you sample by cluster only, you can end up with a billing cluster made up entirely of how-to questions and none that are complaints or comparisons. The assistant's behaviour can differ a lot between those intents.
A simple fix is to treat each pair of cluster and intent as the stratum. This gives more strata, so small strata appear quickly, and the floor must be lower or the set balloons. With 10 clusters and 5 intents there are up to 50 strata, and a floor of 2 would force at least 100 prompts.
A cheaper approach keeps the cluster as the main stratum and checks intent mix afterwards.
from collections import Counter
def intent_gap(all_rows, picked_rows):
def mix(rows):
total = sum(r["count"] for r in rows)
c = Counter()
for r in rows:
c[r["intent"]] += r["count"]
return {k: v / total for k, v in c.items()}
full, small = mix(all_rows), mix(picked_rows)
return {k: round(small.get(k, 0) - full[k], 3) for k in full}A gap near 0 means the sample's intent mix matches real demand. A large negative number, for example -0.15 for troubleshooting, means that intent is under-represented. Swap in a few prompts of that intent from clusters that are over their floor.
Reporting results with weights
The floor makes small clusters count for more in your prompt set than they do among your customers. If you average results across all prompts, rare topics have too much influence.
There are two honest ways to report.
- Report per cluster. Give a score for each cluster and say how many prompts it rests on. This is the clearest view and never hides a weak spot.
- Report a weighted overall score. Give each prompt the weight
cluster_demand_share / cluster_prompt_count. A prompt from a heavily sampled rare cluster then counts for less than a prompt from a lightly sampled common one.
def prompt_weights(rows_all, picked):
demand = Counter()
for r in rows_all:
demand[r["cluster"]] += r["count"]
grand = sum(demand.values())
in_set = Counter(r["cluster"] for r in picked)
return {
r["id"]: (demand[r["cluster"]] / grand) / in_set[r["cluster"]]
for r in picked
}The weights sum to 1, so the weighted average of per-prompt scores is a demand-matched overall score.
Common mistakes
- Sampling before deduplicating. Duplicates push up the count of popular phrasings. Always dedupe first, then use
countfor demand. - Forgetting the cap. A cluster with fewer questions than its floor makes
rng.samplefail. Always take the minimum with the cluster size. - Unseeded or order-dependent sampling. If you cannot rebuild the same set, you cannot compare this month's results with last month's.
- Treating the floor as a tuning knob after seeing results. If you raise a floor because a cluster looked bad, you are choosing the sample using the outcome. Fix floors before running anything.
- Reporting only the overall average. A good average can hide a failing rare topic, which is the reason for the floor.
What to check before moving on
Before you hand the sampled set to the validation step, confirm the following.
- Every cluster appears at least as often as its floor, unless it has fewer questions.
- The cluster shares in the set are close to the demand shares, apart from the small clusters you lifted.
- The intent gap for each intent is small, or you can explain it.
- Re-running the function with the same seed and data gives the same IDs.
- The weights file exists and sums to 1.
Exercise
A cluster has 3 unique questions, a demand share of 0.5% and a floor of 5. A set of 200 prompts is requested. How many prompts does the cluster get under the sample_prompts logic, and why?
Show answer
It gets 3. The proportional quota is round(200 x 0.005) = 1. The floor lifts that to max(5, 1) = 5. The cap then takes the minimum of 3 available questions and 5, which is 3. Without the cap, random.sample would raise a ValueError because it cannot draw 5 items from 3.
Exercise
You sample 40 prompts. Cluster X has 10% of real demand and received 4 prompts. Cluster Y has 1% of real demand but received 3 prompts because of its floor. What weight should each prompt in X and in Y carry in a demand-matched overall score, and what does the difference tell you?
Show answer
Each X prompt carries 0.10 / 4 = 0.025. Each Y prompt carries 0.01 / 3 = about 0.0033. An X prompt counts roughly 7.5 times as much as a Y prompt. The difference shows that the floor over-samples Y relative to its real demand, so Y prompts must be down-weighted in an overall score. Y's own score should still be reported separately so its weak spots stay visible.
Exercise
Why does sample_prompts iterate over sorted(by_cluster) and sort the rows by ID before sampling?
Show answer
A seeded random generator only gives the same result when it is asked the same questions in the same order. Dictionaries keep insertion order, so a different input row order would change the cluster order and the list each sample is drawn from, giving different prompts from the same seed. Sorting removes that dependence, so the selection is repeatable.