Sub topic 14
Sample size, variance, and confidence intervals
This chapter assumes you can compute the retrieval metrics and faithfulness scores from earlier chapters. It also assumes you know what a mean and a standard deviation are. By the end you should be able to attach an uncertainty range to any evaluation number and decide whether a change in score is real.
Why one number is not enough
Suppose your RAG system scored a mean faithfulness of 0.72 on an evaluation set of 40 questions. After you change the prompt, it scores 0.76. Did the prompt help?
You can't tell from those two numbers. Each score is an estimate of how the system would behave on all the questions your users might ask. A different sample of 40 questions would give a different mean. The size of that wobble depends on how many questions you have and how much the per-question scores vary.
Three sources of noise mix together in a RAG evaluation:
- Question sampling noise. Your evaluation set is a small sample of possible questions.
- Generator noise. An LLM sampled at a temperature above 0 can give different answers to the same question on different runs.
- Judge noise. An LLM judge can give different verdicts for the same claim on different runs, and different judges disagree with each other.
Confidence intervals mainly address the first source. You must handle the other two by repeating runs and by validating your judge, as covered in the previous chapters.
The unit of analysis is the question
Compute one score per question, then summarize across questions. For faithfulness, that means computing the fraction of supported claims within each answer, then averaging those per-question fractions. Do not pool all claims from all answers into one big list and treat each claim as an independent sample. Claims from the same answer share a question, a retrieved context, and a generation, so they are correlated. Pooling makes the sample look larger than it is and gives intervals that are too narrow.
The same rule applies to retrieval metrics. Precision@k, reciprocal rank, and nDCG are each defined per question. The mean of reciprocal rank over questions is MRR. The confidence interval is built from the per-question values.
Questions whose metric is undefined need explicit handling. In this tutorial, recall_at_k returns None when a question has no labelled relevant documents, and faithfulness_score returns None when an answer has no claims. Drop these from the mean, and report how many you dropped. Silently converting them to 0 or 1 biases the result.
How wide is the noise?
For a metric that is a proportion (hit rate, or the share of questions that are fully faithful), the standard error of the mean is approximately:
SE = sqrt(p * (1 - p) / n)A 95% interval is roughly the mean plus or minus 1.96 times SE. The table shows the half-width of that interval when the true rate is about 0.8.
| Questions (n) | Standard error | 95% half-width |
|---|---|---|
| 50 | 0.057 | ±0.111 |
| 100 | 0.040 | ±0.078 |
| 200 | 0.028 | ±0.055 |
| 400 | 0.020 | ±0.039 |
| 1000 | 0.013 | ±0.025 |
Quadrupling the number of questions only halves the interval. With 100 questions, a score of 0.80 is consistent with a true rate anywhere from about 0.72 to 0.88. A 3-point improvement is invisible at that size.
For graded or continuous metrics such as nDCG or per-question faithfulness fractions, replace p * (1 - p) with the variance of the per-question scores. The pattern is the same: noise shrinks with the square root of n.
Percentile bootstrap
The normal-approximation formula assumes a well-behaved distribution. Per-question RAG scores often are not. Faithfulness fractions pile up at 1.0, with a tail of failures near 0. The bootstrap avoids assuming a distribution. It resamples your per-question scores with replacement many times, computes the mean of each resample, and reads the interval off the sorted means.
import random
def bootstrap_ci(scores, n_resamples=2000, alpha=0.05, seed=0):
rng = random.Random(seed)
n = len(scores)
means = []
for _ in range(n_resamples):
sample = [scores[rng.randrange(n)] for _ in range(n)]
means.append(sum(sample) / n)
means.sort()
lo = means[int((alpha / 2) * n_resamples)]
hi = means[int((1 - alpha / 2) * n_resamples) - 1]
return sum(scores) / n, lo, hi
per_question_faithfulness = [1.0, 0.5, 1.0, 0.0, 1.0, 0.75, 1.0, 0.5]
mean, lo, hi = bootstrap_ci(per_question_faithfulness)
print(f"mean={mean:.3f} 95% CI=({lo:.3f}, {hi:.3f})")The mean is 0.719. The interval is wide, because there are only eight questions and one of them scored 0. Report the interval next to the mean, as in "0.72 (95% CI 0.50 to 0.91, n=8)". The seed makes the result repeatable, which matters when the number appears in a report.
Comparing two systems: use paired differences
To compare a baseline and a candidate, run both on the same questions. Then bootstrap the per-question differences, not the two means separately.
Pairing removes the variation caused by some questions being easy and others hard. Both systems tend to do well on the easy questions and badly on the hard ones, so that variation cancels in the difference. A paired interval is usually much narrower than the two separate intervals would suggest.
import random
def bootstrap_ci(scores, n_resamples=2000, alpha=0.05, seed=0):
rng = random.Random(seed)
n = len(scores)
means = []
for _ in range(n_resamples):
sample = [scores[rng.randrange(n)] for _ in range(n)]
means.append(sum(sample) / n)
means.sort()
lo = means[int((alpha / 2) * n_resamples)]
hi = means[int((1 - alpha / 2) * n_resamples) - 1]
return sum(scores) / n, lo, hi
def paired_difference_ci(scores_a, scores_b, **kwargs):
if len(scores_a) != len(scores_b):
raise ValueError("both systems must be scored on the same questions")
diffs = [b - a for a, b in zip(scores_a, scores_b)]
return bootstrap_ci(diffs, **kwargs)
baseline = [1.0, 0.5, 1.0, 0.0, 1.0, 0.75, 1.0, 0.5, 0.5, 1.0]
candidate = [1.0, 0.75, 1.0, 0.25, 1.0, 0.75, 1.0, 0.75, 0.5, 1.0]
diff, lo, hi = paired_difference_ci(baseline, candidate)
print(f"candidate - baseline = {diff:+.3f}, 95% CI=({lo:+.3f}, {hi:+.3f})")
if lo > 0:
print("improvement is unlikely to be noise")
elif hi < 0:
print("regression is unlikely to be noise")
else:
print("inconclusive: the interval includes 0")Read the result by looking at whether the interval contains 0. If it does, the data do not distinguish the two systems. That is not proof they are equal. It means you need more questions or a larger change.
Do not decide by checking whether two separate intervals overlap. Two intervals can overlap while the paired difference is clearly positive.
Reducing variance and sizing your set
You have several options when the interval is too wide to be useful:
- Add questions. This is the most reliable fix, but each added question needs a label or a judged score, so it costs effort.
- Use paired comparisons. Always compare systems on identical questions.
- Repeat stochastic steps. Run generation and judging several times per question, average within each question, and then bootstrap over questions. This shrinks generator and judge noise, but it does not shrink question sampling noise. Ten runs on 50 questions is still 50 questions.
- Set temperature to 0 for evaluation runs where you can. This removes some generator noise, but your production setting may differ, so state which one you measured.
- Use graded metrics. nDCG and per-question faithfulness fractions carry more information per question than a binary pass or fail.
To plan a set size in advance, decide the smallest difference you care about, for example 3 points. Estimate the standard deviation of the paired differences from a pilot run of 30 to 50 questions. The questions needed for a 95% interval whose half-width is that target are about (1.96 * sd / target) ** 2. If the pilot differences have a standard deviation of 0.15 and you want to detect 0.03, you need about (1.96 * 0.15 / 0.03) ** 2, which is 96 questions.
Common errors
- Reporting means with no interval. A reader can't tell a 0.04 gain from noise.
- Treating claims as independent samples. This understates uncertainty, as described above.
- Testing many variants and keeping the best. If you compare 20 prompt variants on one set, one will look good by chance. Confirm the winner on fresh questions that you did not use to choose it.
- Tuning on the evaluation set. Repeated tuning against the same questions overfits to them. Keep a held-out set that you look at rarely.
- Ignoring clusters. If many questions come from the same document or were written from the same template, they are correlated, and the effective sample size is smaller than n. Resample at the document level if you can.
- Dropping undefined scores silently. Report how many questions were excluded and why.
The next chapter uses these intervals as the pass or fail rule in regression tests.
Exercise
Two systems are scored on the same 10 questions. System A has a mean faithfulness of 0.70 and system B has 0.74. Using paireddifferenceci, you get a 95% interval for B minus A of (-0.02, +0.10). A colleague says B is better because 0.74 is greater than 0.70. What do you reply, and what would you do next?
Show answer
The interval for the difference contains 0, so these 10 questions do not show that B is better. The 4-point gain is within the noise you would expect from so small a set. Next, estimate the standard deviation of the paired differences, compute how many questions you need for a half-width near the gain you care about, and add questions. Also check whether the questions are clustered by document, because that would make the real uncertainty larger.
Exercise
You judge each answer 5 times and have 60 questions. Which bootstrap should you run: over the 300 judged results, or over the 60 per-question averages? Why?
Show answer
Run it over the 60 per-question averages. The 5 repeats of the same question are not independent samples of questions. Repeating the judge reduces judge noise inside each question, but the amount of question sampling noise is set by the 60 questions. Bootstrapping the 300 results would give an interval that is too narrow.