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

Resampling: The Bootstrap & Cross-Validation

You have one dataset and one number computed from it. Resampling lets you ask how much that number would wobble, and how well a model would do on data it hasn't seen, without any new data and without a formula.

Lesson 5 gave you a formula for the uncertainty of an average: standard error = standard deviation / √N. Lesson 9 told you to check a gap between two prompts with "a real significance test (a two-proportion z-test or a bootstrap resample)", and left the bootstrap at that. The formula covers the mean and little else. What is the standard error of a median latency? Of a p95? Of the gap between two prompts graded on the same items? Of a model's accuracy on data it never trained on? No tidy formula answers these, but one idea answers all of them: reuse the data you have, over and over, and watch how the answer moves. That idea has two main forms. The bootstrap measures the uncertainty of a statistic. Cross-validation estimates how well a model generalizes. This lesson covers both.

1. The bootstrap: resample your sample

Lesson 5 imagined repeating your eval many times, each time drawing a fresh sample from the population, and looking at how the statistic varies. You can't do that: you have one sample. The bootstrap's move is to treat your sample as a stand-in for the population and draw fresh samples from it.

1. You have n observations.
2. Draw n items from them WITH replacement (a "bootstrap sample", same size as the original).
3. Compute your statistic on that bootstrap sample (median, p95, accuracy gap, anything).
4. Repeat steps 2-3 B times (say B = 10,000).
5. The spread of those B statistics approximates the spread you'd see across real fresh samples.

"With replacement" is the part that matters. After an item is drawn, it goes back in the pool, so the same item can appear twice or three times in one bootstrap sample while other items don't appear at all. Drawing without replacement would just hand you your original data back in a different order, and every resample would give the identical statistic.

Key Insight The bootstrap swaps "the unknown population" for "the sample I actually have" and then does by simulation what Lesson 5 did with algebra. It works for any statistic you can compute, which is why it is the default tool when no standard-error formula exists.

2. Worked example by hand: a bootstrap interval for median latency

A team logs the latency of 9 requests to a summarization endpoint, in milliseconds. In the order logged (call the positions 0 to 8):

position: 0 1 2 3 4 5 6 7 8
latency: 212 245 198 410 232 221 530 205 240
sorted: 198 205 212 221 232 240 245 410 530
median (5th of 9) = 232 ms mean = 2493 / 9 = 277 ms

The mean (277) sits well above the median (232) because of the two slow requests, 410 and 530. That is why a team reports the median here. The question is how far off 232 could be. Draw 9 positions at random with replacement, twice. (These positions came from a seeded random generator, so you can reproduce them; the Python block below does the whole thing at scale.)

Resample 1: positions 5 2 6 0 1 8 1 5 0
values 221 198 530 212 245 240 245 221 212
sorted 198 212 212 221 221 240 245 245 530
median (5th) = 221
Resample 2: positions 8 3 0 1 6 6 1 3 1
values 240 410 212 245 530 530 245 410 245
sorted 212 240 245 245 245 410 410 530 530
median (5th) = 245

Two resamples gave medians of 221 and 245. Notice that position 1 (245 ms) turned up three times in resample 2 and position 2 (198 ms) never did. Each resample is a plausible alternate version of the afternoon you logged. Two is too few to read an interval from.

3. The same thing in Python, with a fixed seed

import random, statistics as st
data = [212, 245, 198, 410, 232, 221, 530, 205, 240]
rng = random.Random(42) # fixed seed: reproducible
B = 10_000
meds = sorted(st.median(rng.choices(data, k=len(data))) for _ in range(B))
print(st.mean(meds), st.pstdev(meds)) # centre and spread
print(meds[249], meds[9749]) # 2.5th and 97.5th percentiles
234.7909 32.943...
205 410

Sort the 10,000 bootstrap medians and read off the 2.5th and 97.5th percentiles: 205 ms to 410 ms. That is a percentile bootstrap interval for the median latency. The bootstrap medians average 234.8 ms with a spread (standard deviation, the bootstrap's estimate of the standard error) of about 32.9 ms.

The interval is wide, lopsided (27 ms below the sample median, 178 above), and honest: with 9 requests, two of them slow, the median could plausibly sit anywhere from the low 200s to 410. Every bootstrap median is one of the original values, since the median of a sample is always one of its members. Only 9 distinct medians were possible in this experiment, which is a small-data warning in itself.

4. Why the bootstrap works: and the 63.2% fact

The logic: your sample is the best picture of the population you have. Sampling from the sample mimics sampling from the population, and the wobble of a statistic across bootstrap samples mimics its wobble across real ones.

A concrete property falls out of "with replacement". Any single bootstrap sample of n items contains only some of the originals. How many?

One draw misses item i with probability 1 - 1/n
n independent draws all miss item i: (1 - 1/n)^n
n = 10 (0.9)^10 = 0.3487 so item is in the sample 1 - 0.3487 = 0.6513
n = 1,000 (0.999)^1000 = 0.3677 so in the sample 0.6323
Limit: (1 - 1/n)^n -> e^(-1) = 0.3679 so 1 - 1/e = 0.63212

Why the limit is 1/e: take logs. n·ln(1 - 1/n) ≈ n·(-1/n) = -1, because ln(1 - x) ≈ -x for small x. Exponentiate and you get e-1. So a bootstrap sample contains about 63.2% of the distinct original items, and the other 36.8% are left out. Check it by simulation:

rng = random.Random(42); n = 1000
fr = [len(set(rng.choices(range(n), k=n))) / n for _ in range(1000)]
print(st.mean(fr), min(fr), max(fr))
0.632326 0.601 0.665

Across 1,000 bootstrap samples of 1,000 items, the average share of distinct items was 0.6323, matching 1 − 1/e = 0.6321. The left-out items are called out-of-bag. Random forests use them as a free validation set for each tree. For you, the 63.2% is a reminder that a bootstrap sample has fewer distinct items than the original, which is part of why the bootstrap is shakier on small data.

5. When the bootstrap fails

6. Comparing two prompts on the same items: the paired bootstrap

Lesson 9 compared two prompts by their pass rates. The common eval setup is stronger than that: both prompts are run on the same 40 items. Some items are just hard and both prompts fail them; some are easy and both pass. That shared difficulty is noise you can cancel out, if you keep each item's pair of results together.

B passesB failsTotal
A passes28129
A fails7411
Total35540
A pass rate = 29/40 = 0.725 B pass rate = 35/40 = 0.875 gap = +0.150
Per item, d = (B result) - (A result): +1 on 7 items, -1 on 1 item, 0 on 32 items
mean of d = (7 - 1) / 40 = 0.150 (the same gap, computed item by item)

The paired bootstrap resamples the items, 40 at a time with replacement, and recomputes the gap from the same resampled items for both prompts. Resampling the list of d values does exactly that. The unpaired version, for contrast, resamples each prompt's results independently, as if the two had been tested on different items:

pairs = [(1,1)]*28 + [(1,0)]*1 + [(0,1)]*7 + [(0,0)]*4 # (A passed, B passed)
a = [p[0] for p in pairs]; b = [p[1] for p in pairs]; d = [y - x for x, y in pairs]
rng = random.Random(42)
paired = sorted(st.mean(rng.choices(d, k=40)) for _ in range(10_000))
unpaired = sorted(st.mean(rng.choices(b, k=40)) - st.mean(rng.choices(a, k=40))
for _ in range(10_000))
print(paired[249], paired[9749]); print(unpaired[249], unpaired[9749])
paired 95% interval: 0.025 to 0.275
unpaired 95% interval: -0.025 to 0.325

The paired interval, +2.5 to +27.5 points, stays above zero: prompt B is probably better on this kind of item. The unpaired interval, −2.5 to +32.5 points, includes zero and would make you shrug. Same data, same point estimate (+15 points), different verdict. Pairing is worth the effort because 28 of the 40 items were passed by both prompts. Only the 8 items where the prompts disagreed (7 for B, 1 for A) tell you anything, and the paired bootstrap focuses on those.

Key Insight If both prompts ran on the same items, use the item as the unit of resampling. Pairing never makes the interval worse when results are positively correlated across prompts, and in practice they usually are. Breaking the pairs throws away information and widens the interval for no reason.

7. Cross-validation: how will this model do on data it hasn't seen?

The bootstrap asks "how uncertain is this number?" Cross-validation asks a different question: "how well will a model trained like this do on new data?" Lesson 8 split data into train and validation. A single split wastes data and depends on luck: with 100 labeled examples, one split's validation score reflects whichever 20 examples landed there. K-fold cross-validation uses every example for validation exactly once.

1. Shuffle the labeled data and cut it into k equal folds.
2. For each fold i = 1..k: train on the other k-1 folds, score on fold i.
3. You now have k scores. Report their mean (the estimate) and their spread.
5-fold cross-validation on 100 labeled examples Round 1Round 2Round 3Round 4Round 5 0.800.850.750.900.80 fold 1fold 2fold 3fold 4fold 5 Test set held out, touched once validation fold (score shown) training folds

Every example is scored exactly once while unseen. The dashed test set sits outside the loop entirely.

A worked 5-fold example

A team has 100 labeled support tickets and wants to know how accurate a ticket-routing classifier built with a given recipe will be. They cut the data into 5 folds of 20, train five times, and score each model on the fold it didn't see:

fold scores (accuracy): 0.80 0.85 0.75 0.90 0.80
mean = (0.80 + 0.85 + 0.75 + 0.90 + 0.80) / 5 = 4.10 / 5 = 0.82
deviations from 0.82: -0.02 +0.03 -0.07 +0.08 -0.02
squared: 0.0004 0.0009 0.0049 0.0064 0.0004 sum = 0.0130
sample variance = 0.0130 / (5 - 1) = 0.00325
sample std dev = √0.00325 = 0.0570
std error of the mean ≈ 0.0570 / √5 = 0.0255

Report it as 0.82 with a fold-to-fold standard deviation of 0.057. The spread matters as much as the mean: fold 3 scored 0.75 and fold 4 scored 0.90, a 15-point range inside the same dataset. The standard error line is only a rough guide. The training sets overlap heavily (any two share 75% of the data), so the folds are not independent and the true uncertainty is larger than 0.0255. Treat it as a floor.

Leave-one-out and the choice of k

Leave-one-out cross-validation (LOO) is the extreme: k = n, so each fold is a single example. With 100 examples that is 100 training runs instead of 5, each on 99 examples. LOO uses nearly all the data for each run, so it is the least pessimistic, but it costs n fits whose models are almost identical, and it is unaffordable for anything expensive to train, such as an LLM fine-tune. Common practice is k = 5 or 10.

The bias-variance of the CV estimate, in one paragraph

Each fold's model trains on only (k−1)/k of the data (80% for k = 5), so it is slightly weaker than a model trained on everything, and CV tends to be a little pessimistic: that is bias, and it shrinks as k grows (LOO trains on n−1 of n). The other side is variance: the estimate depends on which random folds you drew, and a larger k makes the training sets overlap more, so the k models and scores move together and averaging them removes less noise. LOO is low-bias but often noisy and always expensive; k = 5 or 10 is the usual compromise. This is the bias-variance tradeoff from Lesson 8, now applied to the measurement of the model instead of the model itself.

8. Stratified folds, time-series splits, and the leakage trap

Stratified folds for imbalanced classes

Say 1,000 tickets include 50 urgent ones (5%), cut into 5 folds of 200. Each fold should hold 10 urgent tickets. Purely random folds won't: the count in a fold varies with a standard deviation of √(200 × 0.05 × 0.95 × 800/999) ≈ 2.8, so a fold with 5 or 15 urgent tickets is routine, and a rare class with 10 positives in total can leave a fold with none, making recall undefined there. Stratified k-fold deals the positives and negatives into folds separately, so every fold keeps the 5% ratio. Use it for any classification task with a rare class (the same imbalance trap as Lesson 9's 95% "do nothing" moderator).

Time-series splits

Random folds assume order doesn't matter. If you are predicting next month's traffic, or classifying support tickets whose wording drifts as the product changes, a random fold lets the model train on March and be scored on February, using the future to predict the past. Use a forward-chaining split instead: always train on earlier data, validate on later data: train on months 1-3 and validate on month 4, then train on months 1-4 and validate on month 5, and so on.

Likewise, keep grouped rows (several turns from one user, several chunks from one document) inside a single fold, or near-copies of training examples will flatter the validation score.

The leakage trap: preprocessing before splitting

Leakage is any way information from the validation data reaches the model during training. The classic version is subtle: compute a preprocessing step on the whole dataset, then cross-validate.

WRONG: scale / normalize / pick top features / fit a vocabulary on ALL 100 tickets
then run 5-fold CV on the transformed data
RIGHT: inside each fold: fit the preprocessing on the 80 training tickets only,
apply it unchanged to the 20 validation tickets

In the wrong version, the means, vocabulary, or "best 50 features" were chosen with a look at the validation examples, so the validation fold is no longer unseen. Feature selection is the worst offender: choose the features most correlated with the label using all the data and you can get impressive CV accuracy on pure noise. The rule is that everything that learns from data (scalers, imputers, feature selectors, tokenizer vocabularies, even deduplication thresholds) belongs inside the loop. Lesson 17 (study design and confounding) shows the wider family: a number that looks like evidence because the data collection or the analysis let information in that shouldn't be there.

Rule of thumb: a CV score that looks too good for the problem is a reason to check for leakage before celebrating.

9. The test set you touch once, and nested CV

Cross-validation is for choosing: prompt template, learning rate, number of retrieved chunks, which of three models. Every time you pick the best of many options by its CV score, a little of the score is luck you selected for, so the winning number is optimistic. That is why the final check needs data that played no part in any choice.

  1. Before anything else, set aside a test set (the dashed block in the diagram).
  2. Do all your exploring, tuning and model selection with cross-validation on the rest.
  3. When you have a final candidate, score it on the test set once. Report that number.

If the test score disappoints and you go back to tweak, the test set has become one more tuning set, and you've lost your only honest measurement. It matters for LLM work too: a prompt tuned for weeks against a fixed 200-item eval set is overfit to it (the held-out warning in Lesson 9's checklist).

Note: nested CV When you have too little data to spare a test set, nested cross-validation nests two loops: an inner CV picks the best setting using only the outer loop's training folds, and an outer CV scores that whole select-then-train procedure on held-out folds. It costs many more fits, but the outer score is not contaminated by the selection; it evaluates the procedure, not one final model.

10. Why this matters for building AI systems

Why This Matters These two tools turn "it scored higher" into a defensible claim, with almost no math.

Put an interval on every eval number you act on. Latency percentiles, pass rates and judge scores have no clean formula, and all are one bootstrap away from a range. Resample by item when two systems share items. Protect the score from yourself: the worst evaluation failures are leakage, peeking and a reused test set, not arithmetic. Split first, fit everything inside the fold, and keep one test set sealed until the end.

Recap

Leads into Lesson 19 Cross-validation and the bootstrap both ask "how well does this fitted model do, and how sure are we?" Lesson 19, Multiple & Logistic Regression with ANOVA, builds the models themselves: regression with several inputs, logistic regression for yes/no outcomes, and ANOVA for comparing many groups at once. Those are the models you will now know how to validate.

✅ Check Yourself

1. How is one bootstrap sample of a dataset of n items built?

Draw n items without replacement, in a new random order
Draw n items with replacement, so some items repeat and some are left out
Draw half the items and discard the rest

2. About what fraction of the distinct original items appears in a large bootstrap sample?

About 50%
About 36.8%
About 63.2%

3. Prompts A and B were both run on the same 40 eval items. Why is the paired bootstrap usually better than resampling each prompt's results separately?

It keeps each item's two results together, so item difficulty shared by both prompts cancels and the interval is tighter
It produces a larger gap between the prompts
It avoids needing a random seed

4. A team standardizes all features using the mean and standard deviation of the full dataset, then runs 5-fold cross-validation. What is wrong?

Nothing; scaling is harmless because it doesn't use the labels
The scaler saw the validation folds, so information leaked in; it should be fit on the training folds inside each round
Five folds are too few to scale features

5. You tuned a prompt against a 200-item test set for three weeks, then report its score on that same set as the final number. What is the problem?

200 items is always too few to report a score
Nothing, as long as the score is high
The set was used to make choices, so it is no longer an unbiased estimate; the score is optimistic