Lesson 17 of 19 · Statistics for AI, GenAI & LLMs

Study Design: Randomization, Confounding & Data Leakage

Every test and interval in Lessons 9, 15 and 16 assumes the data was collected fairly. This lesson is about how it gets collected, and the three ways an AI evaluation quietly produces a number that means less than it looks like.

Lesson 15 gave you the machinery for asking whether a difference is bigger than noise. That machinery answers one question: if the data came from a fair comparison, is the gap real? It cannot tell you whether the comparison was fair. A significance test run on a biased sample, a confounded comparison, or a leaked test set returns a small p-value with total confidence, and it is wrong. Study design is the work you do before the test so that the number you compute answers the question you asked.

1. Random sampling vs. a convenience sample

Lesson 5 showed that a random sample's error shrinks as it grows. That promise only holds if the sample is random: every item in the population had a known chance of being picked. A convenience sample is whatever was easiest to grab, and a bigger one does not fix it. You just get a more precise estimate of the wrong quantity. The gap between what you measured and what you wanted is selection bias.

Say a support team wants to know how often a new ticket-answering model resolves a ticket correctly. Ticket volume splits 55% easy (password resets, billing lookups) and 45% hard (multi-step bugs). In truth the model is right 92% of the time on easy tickets and 64% on hard ones. An engineer builds the eval set from tickets that already have a clean, short, agent-approved reply, because those are the ones with an obvious reference answer. That set is almost all easy tickets.

True accuracy over all tickets:
0.55 × 0.92 + 0.45 × 0.64 = 0.506 + 0.288
= 0.794 → 79.4%
Accuracy on the convenience set (easy tickets only):
0.92 → 92.0%

The eval reports 92% for a system that is right about 79% of the time in production, a 12.6-point overstatement. Collecting 100,000 convenience tickets instead of 1,000 would not change it. A random draw from the live ticket stream would have: each ticket, easy or hard, shows up in proportion to how often it occurs.

Pitfall Eval sets built from "prompts we already have good answers for," "prompts the team wrote," or "conversations users rated" are convenience samples. Each is filtered by something related to difficulty or satisfaction, so it will not look like production traffic.

2. Observational study vs. randomized experiment

Lesson 6 warned that correlation is not causation. Study design says what to do about it. In an observational study you watch what happened and compare groups that formed on their own: tickets that went to the new model versus tickets that went to the old one. In a randomized experiment you decide the group for each unit by a random mechanism, such as a coin flip, so nothing about the unit can influence which group it lands in.

Only the experiment supports a causal claim, and the reason is mechanical. If a coin decides which model handles a ticket, then on average the two groups hold the same mix of easy and hard tickets, the same users, the same times of day, and the same things nobody thought to measure. The only systematic difference left is the model. In an observational comparison the groups differ in the model and in whatever caused them to be assigned differently, and the data cannot separate the two.

3. Confounding

A confounder is a variable that influences both the treatment (which model, which prompt) and the outcome (resolved correctly, user satisfied). When it does, the raw comparison mixes the treatment's effect with the confounder's. Lesson 6's emoji-and-toxicity example was the same shape, with casual register as the confounder.

Observational: confounded Randomized: coin flip assigns Ticket difficulty confounder Model version treatment Resolved? outcome easy tickets go to new model easy tickets resolve more dashed link: real effect, or just difficulty? Ticket difficulty still varies, but is balanced Model version treatment Resolved? outcome coin flip × difficulty no longer decides who gets which model

Randomization cuts the arrow from the confounder into the treatment. What is left of the model-to-outcome link can be read as the model's effect.

Confounders are not always bad data. Here, routing easy tickets to the cheaper new model was a sensible product decision. It just makes the two groups incomparable.

4. Simpson's paradox: a model that wins overall and loses everywhere

A team rolls out a new ticket model. It handles 350 tickets and the old model handles 350. Both groups are the same size, but the new model was routed mostly easy tickets and the old model kept the hard ones. Here are the resolved-correctly counts, with each rate checked as correct divided by tickets:

SegmentOld modelNew modelWinner
Easy tickets81 / 87 = 93.1%234 / 270 = 86.7%Old
Hard tickets192 / 263 = 73.0%55 / 80 = 68.8%Old
All tickets273 / 350 = 78.0%289 / 350 = 82.6%New
Old total: 81 + 192 = 273 correct of 87 + 263 = 350
New total: 234 + 55 = 289 correct of 270 + 80 = 350
Share of each group that was easy:
Old: 87 / 350 = 24.9% New: 270 / 350 = 77.1%
The new model's overall rate is built mostly from the easy segment.

This is Simpson's paradox: the old model wins in every segment and the new one wins overall. Nothing is miscalculated. The overall rate is a weighted average of the segment rates, and the weights differ between the two groups. The new model's 82.6% is mostly easy-ticket performance (77.1% weight on a segment where everyone scores well). The old model's 78.0% is dragged down by carrying 75.1% hard tickets.

Key Insight When groups were formed by something related to the outcome, the aggregate tells you about the mix as much as about the treatment. The fix is not "always split by segment." You also need to know which variable is the confounder. Splitting by a variable that sits downstream of the treatment can create the paradox instead of removing it. A causal diagram, as in the figure above, is how you decide which comparison to trust.

5. Randomizing an A/B test of prompts or models

The clean way out is to run the comparison as an experiment. Say you are testing prompt variant A against variant B on live traffic. Design choices decide whether the result is trustworthy:

Choose the unit of randomization

If you assign by request, the same user can see both variants. That is fine when requests are independent and the user will not notice, but it breaks if one variant's behavior shapes the next request (a user who got a bad answer retries, and the retry is counted as a fresh request). If you assign by user, each user sees one variant for the whole test, which avoids that carry-over and is the usual choice for chat products. The cost is fewer independent units: 4,000 users with 20 requests each give you about 4,000 independent observations, not 80,000, because requests from one user are correlated. Analyze at the unit you randomized.

Stratify and block

Pure coin-flipping balances groups only on average, and in a small test chance can put too many heavy users in one arm. Stratified randomization splits the population by a variable you know matters (language, plan tier, ticket difficulty) and randomizes inside each stratum. Blocking is the same idea applied to assignment order: within each stratum, assign in small shuffled blocks so the arms stay equal in size throughout. With 1,000 users, 700 English and 300 other languages, stratifying gives 350 and 350 English users and 150 and 150 others, so language cannot tilt either arm.

Check the split before you read the result: sample ratio mismatch

If you designed a 50/50 split, the assignment counts should be close to 50/50. If they are not, something upstream is broken: a variant crashes for some clients, a cache serves one arm preferentially, a bot filter removes more of one arm. That is a sample ratio mismatch (SRM), and it means the groups are no longer comparable, whatever the metric says. A test with 10,000 users shows 5,200 in A and 4,800 in B. Compare the counts to the 5,000 expected in each arm with a chi-square goodness-of-fit test (the same idea as the z-test in Lesson 15: how far is the observed from the expected, in units of chance variation?):

χ² = (5200 − 5000)²/5000 + (4800 − 5000)²/5000
= 40,000/5000 + 40,000/5000 = 8 + 8
= 16 (1 degree of freedom, p ≈ 0.00006)

A 52/48 split looks harmless, but a gap this large arising by chance has a probability around 6 in 100,000. Treat the test as invalid until you find the cause. Check this first, before computing any lift.

6. Train/test contamination and data leakage

An eval set is only useful if the model has never seen it. Data leakage is any path by which information from the test set, or from the future, reaches the model during training or selection. The reported score then measures memory, not ability. Three common routes:

Duplicates across splits

The same or near-identical item sits in both train and test: repeated support tickets, copied forum threads, an eval prompt published online and scraped into pretraining data. The model recalls instead of generalizing.

Time leakage

A random split of data that has a time order lets the model train on March and be tested on February. In production it only ever predicts forward, so split by date: train on the past, test on the future.

Target leakage

A feature contains the answer, or a proxy for it. A churn model that sees "account closed flag" or a refund-processed field is not predicting; it is reading the label from another column.

Here is how much duplicates alone can inflate a score. A team's test set has 1,000 items. Unknown to them, 300 are exact copies of training items. The model recalls those 98% of the time. On the 700 genuinely unseen items it is right 74% of the time.

Reported accuracy = 0.30 × 0.98 + 0.70 × 0.74
= 0.294 + 0.518
= 0.812 → 81.2%
True accuracy on unseen data: 74.0%
Inflation: 81.2% − 74.0% = 7.2 points

That 7-point gap is larger than most differences teams ship on. It is also easy to miss: nothing errors, the score simply looks good. Remove the duplicates by exact match and by near-match (normalized text, embedding similarity above a threshold) before trusting a score, and keep the test set out of every choice you make, including prompt tuning and checkpoint selection. Lesson 8 covered overfitting to the training set; repeatedly tuning against one test set overfits to that set in the same way.

7. Survivorship and label-noise bias

Survivorship bias means you only see the cases that made it through some filter. Suppose a model is asked 1,000 questions, refuses or times out on 200, and the report scores only the 800 it answered. At 90% on those, the headline says 90%. But 0.90 × 800 = 720 correct answers out of 1,000 asked is 72% of what users actually experienced. Count the dropped cases as failures, or report their rate next to the score.

Label noise is wrongness in the answer key. Say a model is truly correct on 90% of items, and 8% of the labels are wrong at random on a yes/no task. A correct prediction scores as right only when the label is right (0.92), and a wrong prediction scores as right when the label is also wrong (0.08):

Measured accuracy = 0.90 × 0.92 + 0.10 × 0.08 = 0.828 + 0.008
= 0.836 → 83.6% (true: 90.0%)

Noise pulls the measured score toward 50% and compresses gaps between models, so a real improvement looks smaller. When two strong models disagree with the key on the same items, audit those labels before ranking the models.

8. A checklist for reading any AI evaluation claim

  1. How was the eval sample chosen? Random from production, or convenient? Does it match the traffic the system will see?
  2. Was assignment randomized? If the comparison is observational, name the likely confounders and check the result within segments (Simpson's paradox).
  3. Is the split what the design says it is? Check the group sizes against the plan before reading any metric (sample ratio mismatch).
  4. What is the unit? Users, sessions, or requests, and was the analysis done at that unit?
  5. Could the test set have leaked? Duplicates, time order, target-revealing features, public benchmarks scraped into training data.
  6. What got dropped? Refusals, timeouts, filtered rows, users who left. Are they counted?
  7. How trustworthy are the labels? Who wrote them, and what is the measured disagreement rate?
  8. Only then, is the gap bigger than noise? Lessons 9 and 15 cover the interval and the test.

9. Why this matters for building AI systems

Why This Matters Most large errors in AI evaluation come from the design of the comparison, not from the statistics applied afterwards. Better inference on a bad design does not repair it.

Decisions get made on these numbers

A model swap, a prompt rollout, or a safety sign-off usually rests on one headline number. A convenience sample, an unbalanced rollout, or a leaked test set can move that number by 7 to 13 points, more than the differences teams usually act on.

Randomize when you can, adjust when you cannot

For anything you can control (prompt variants, model versions, retrieval settings), a randomized test is cheap and removes whole classes of confounding. For things you cannot randomize (which users adopt a feature), say so, list the confounders, and describe the claim as an association.

Treat leakage as the default suspicion

The more data a model trains on, the harder it is to be sure a given test item was not in it. Deduplicate, split by time where order matters, and keep a held-out set you have never tuned against.

Recap

Leads into Lesson 18 Once the design is sound, you still have one dataset and need to know how much to trust a number computed from it. Lesson 18 covers resampling: the bootstrap, which estimates uncertainty by re-drawing from your own data, and cross-validation, which gives a more honest estimate of performance on unseen data without burning a separate test set.

✅ Check Yourself

1. A team builds its eval set only from tickets that already have an approved reference reply. Most of those tickets are easy. What is the main problem?

The set is too small, so adding more of the same tickets will fix it
The set is random, but random sets cannot be used to measure accuracy
It is a convenience sample, so accuracy is overstated and a larger set of the same kind would not fix that

2. Why can a randomized experiment support a causal claim when an observational comparison cannot?

Random assignment makes the groups alike on average in everything else, including factors nobody measured
Randomized experiments always have bigger samples
Randomized experiments never need a significance test

3. The old model scores higher than the new model on easy tickets and on hard tickets, yet the new model scores higher overall. Which explanation fits?

At least one of the segment tables must have an arithmetic error
The groups have different segment mixes (the new model got mostly easy tickets), so the overall rates are weighted differently
The new model is secretly better in both segments

4. An A/B test planned as 50/50 ends with 5,200 users in A and 4,800 in B (χ² = 16). What should you do first?

Ignore it, because 52/48 is close enough to 50/50
Report the lift and mention the split in a footnote
Treat the test as suspect and find why assignment or logging was uneven before trusting any metric

5. A random split of timestamped user data puts later messages in training and earlier ones in the test set, and the test score is surprisingly high. What is the likely cause, and the fix?

Label noise; collect more labels from the same source
Time leakage; split by date so the model trains on the past and is tested on the future
Survivorship bias; remove the refusals from the test set