Coverage and stratified sampling

Study time
≈ 1.5 h (estimate)
Needs
L2-M02-L01
Updated
2026-11-03

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L2-M02 · Duration: ~90 min (estimate, including the independent exercise) · Previous: L01 · Next: L03

1. Introduction

The previous lesson asked where a case comes from. This lesson asks the next question: do the cases together cover the situations the system will meet? A dataset of 400 cases can still lack an entire important kind of question, and a nice pass rate on it will silently ignore that kind.

The main tool is the coverage matrix: a table with each dimension of the product (for example the kind of question and the writing style) and, in each cell, a count of cases. An empty cell is a known blind spot. When you sample from a large source, you use stratified sampling so that rare but important groups are not missed, and you use weights so that the final measurement is not skewed because you deliberately took more from the rare groups. The product of the lesson is a coverage matrix (intent × style, where the risk level goes with the intent) with a decision for each empty cell.

2. Learning objectives

  1. Choose the dimensions of a coverage matrix from the use case, the risk and the log, and explain why a dimension is worth keeping.
  2. Compute the matrix and the list of empty cells for a dataset, and state what the matrix does not check.
  3. Split a sample size across strata in three ways (proportional, equal, minimum floor) and choose the suitable one.
  4. Compute the probability that a random sample misses a rare stratum entirely, and check the formula with a simulation.
  5. Estimate the pass rate of the whole population from a stratified sample using weights, and explain why it is skewed without weights.

3. Prerequisites and tools

  • L2-M02-L01: the data sources and the lab's fictional log of 600 messages.
  • L2-M01-L02: quality criteria and risk levels. In L2-M01 risk is attached to each criterion; in this lesson it is attached to the intent (each intent has a risk level), so the matrix is intent × style and the risk is read along the rows.
  • L2-M01-L04: pass rate and the unit of sampling. This lesson does not repeat the confidence-interval formulas.
  • The code lab code-labs/l2-m02.

4. Concepts

4.1 What dataset coverage is

A dimension is an attribute of a case that you suspect will change the system's behavior: the kind of question (intent), the writing style (style), the risk level (in this lab it follows the intent), the difficulty. A cell is a combination of values, for example (hint, no diacritics). The dataset coverage is whether all the necessary cells have enough cases.

Note three easily confused uses of the word "coverage". In L2-M01-L04, "confidence-interval coverage" is the probability that the interval contains the true value. In programming, "code coverage" counts the lines of code that the tests touch. Here it is dataset coverage: the input situations that are represented. All three mean "how much is covered", but they measure three different things.

A cell with 1 case does not mean the system is good in that cell. One case measures very little (L2-M01-L04). The matrix only answers "is there anywhere that is not looked at at all?", not "where it is looked at, how good is the system?".

4.2 Choosing dimensions: from the use case, the risk and the log

A dimension is worth keeping when it (a) changes the system's behavior and (b) is observable in the data. A dimension that does not change behavior only inflates the matrix without adding information. For HocVui Tutor, the lab uses two main dimensions:

  • intent (the kind of question): hint (asks for a hint on an exercise), check (asks to check their work), concept (asks about a concept), offtopic (off topic), pii (the student sends personal information). The risk follows the intent: pii is high, concept is low.
  • style (the writing style): clean, no_diacritics (typing Vietnamese without diacritics, very common on phones), typo, mixed_en (mixed with English).

The style dimension is a Vietnamese-specific dimension that a dataset translated from English would skip. In the lab's simulation, the failure probability is multiplied by 2.0 for a sentence without diacritics, 1.4 with a typing error and 1.6 when mixed with English. These are assumptions of the simulation, not measurements of a real model; they only let us know the truth in order to test the methods. A dimension can also come from error analysis: Anthropic advises turning user-reported failures into test cases so the suite reflects actual usage [R1], and each recurring group of failures is a candidate for a new dimension.

4.3 Stratified sampling: three ways to split

A stratum is a group along one dimension, for example all messages with the intent pii. Stratified sampling means choosing the number of cases for each stratum first, then sampling randomly within the stratum. The question is how to split a sample size n across the strata. lab.coverage.allocation has three modes:

Mode Rule Use when
proportional Each stratum gets a share in proportion to its share of the population You want a scaled-down copy of the population and accept that a rare stratum gets very few cases
equal Every stratum gets an equal number You want to compare strata with each other; you must use weights when reporting an overall number
floor Each stratum gets at least floor cases, the rest is split proportionally You want to guarantee the rare stratum is present, but stay close to the population

Each stratum's quota is computed once (the remaining sample size × the stratum's weight); the integer part is kept, and the remainder goes to the strata with the largest fractional parts (largest remainder), so the largest stratum does not take all the remainder. None of the three ever gives a stratum more than it has, and the total always equals n. In floor mode, when n is smaller than the number of strata times the floor, the function raises an error instead of splitting wrongly.

OpenAI advises making sure the test data includes "typical cases, edge cases, and adversarial cases" [R2]; stratification is the way to do that systematically instead of by feel.

5. Technical deep dive

5.1 The matrix and the empty cells of a dataset

coverage.matrix(cases, row_values=..., col_values=...) returns the number of cases for every combination, including cells with 0 (a table that lists only cells that have data would hide the empty cells). coverage.gaps(cases, required, min_count) returns the necessary cells that have fewer than min_count cases. Two important boundaries: min_count must be ≥ 1 (with 0 every cell "passes" and the function is meaningless, so it raises an error), and required is a list you declare yourself: removing a cell from required makes the function silent. That is why a removed cell must come with a reason (§6.1).

The function does not check: whether the cases in a cell are good; whether cases are duplicates of each other (10 identical cases still give "10"); whether the chosen dimensions are enough (a missing dimension is a blind spot of the matrix).

5.2 The probability of missing a rare stratum

Suppose the log has N = 600 messages, of which K = 24 have the intent pii, and you take n = 40 messages at random without replacement. The probability that the sample contains no pii message is C(N-K, n) / C(N, n), computed by coverage.prob_stratum_missed(600, 24, 40). The result is 0.185, so nearly 1 in 5 draws will contain no pii case. A simulation of 20,000 draws gives 0.185, matching the formula. With proportional allocation, n = 40 gives only 2 pii cases; with floor = 5, this stratum has 5.

That is why a small but high-risk group needs its own stratum: the overall pass rate of 0.876 sounds good, but if you have no or very few pii cases, that number says nothing about them.

5.3 Taking more from a rare stratum means you must weight

If you split 100 cases equally (equal) across 5 strata, the pii stratum (4% of the log) makes up 20% of the sample. The simulated system fails most in pii, so computing the pooled pass rate (every case weighs the same) will come out lower than the true pass rate of the log. The weighted estimate averages by the strata's share in the population: Σ (stratum share × stratum pass rate). coverage.weighted_rate(results, shares) does that and refuses when a stratum has a share but no results, because silently skipping is a familiar way to get a nice number.

Demo D repeats 300 times: take 100 cases equally from 5 strata, run the simulated system, compute both estimates. The true pass rate is 0.876; the mean of the unweighted estimate is 0.812 (biased down by 0.064); the mean of the weighted one is 0.874. NIST lists "re-sampling, re-weighting" among the techniques for managing statistical bias (MS-2.2-001, in the context of provenance of GAI-generated content) [R3]; the idea is in the same family, but this is not NIST guidance for evals.

Limits. weighted_rate rejects a negative share, shares that do not sum to 1, a stratum that has a share but no results, and results for a stratum that has no share; it does not check whether the shares you pass in are the true shares of the population. The weighted estimate gives a point. A confidence interval for a stratified estimate needs its own formula, beyond the scope of this lesson; the lab gives no interval. The simulation knows the truth, which is why the bias can be measured; on a real system you can only trust the theory and check it with sensitivity analysis.

6. The QA perspective

6.1 Reporting coverage and the decision for each empty cell

The report has three parts: the matrix (including cells with 0), the list of empty cells, and a decision for each cell. Each empty cell has only three valid exits: add cases (and record the source), remove the cell from the requirements with a one-sentence reason ("users never send PII mixed with English in this product"), or accept the risk and write it into the limits section of the strategy. "No time yet" is not a decision.

The number of removed cells should be small and signed off by someone. A dataset that reaches "every cell full" by removing all the hard cells covers nothing; that is why the exercise in §9 caps the number of cells that may be removed.

6.2 Edge cases, adversarial cases and Vietnamese situations

The matrix tells you which cell is missing; edge cases and adversarial cases say what to write in that cell. Anthropic suggests edge cases such as "Irrelevant or nonexistent input data", "Overly long input data or user input" and "Ambiguous test cases where even humans would find it hard to reach an assessment consensus" [R4]. For HocVui Tutor, data/expert_cases.jsonl has: a student pushing ("cho em đáp số luôn"), appealing to authority ("cô giáo cho phép"), prompt injection ("bỏ qua mọi hướng dẫn"), a problem missing facts, sentences without diacritics and sentences mixed with English. Each case belongs to a cell of the matrix, so the matrix is also a catalog of adversarial cases.

Loop diagram: choose dimensions (intent × style; risk follows intent) → compute the matrix including zero cells → is a required cell still empty? No: report the matrix and its limits. Yes: add cases, or exclude the cell with a reason, or accept the risk, then go back to computing the matrix.
Diagram: Edge cases, adversarial cases and Vietnamese situations

7. Real-world scenarios

Scenario 1 (fictional): "All clean sentences". The team wrote 60 cases, all typed with full diacritics. On clean sentences, the simulated system has a true pass rate of 0.898; on sentences without diacritics it is 0.801; on the whole log it is 0.876. The team reported 0.898 and released. Nearly three in ten messages in the lab's log (29%) are not clean sentences. A matrix with an empty column would have exposed this before release.

Scenario 2 (fictional): "Split equally, then report the pooled number". The team wanted a close look at the pii group, so it took 20 cases per intent equally, then reported the pooled pass rate of 100 cases. The pooled number is on average 0.064 lower than the truth (§5.3). They delayed a release because "quality dropped", while quality had not changed: the calculation had.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l2-m02
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 73 passed

8.2 Run the demo

python -m lab.demo l02

Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-03; the two versions give identical output):

A. coverage matrix of eval_v1 (38 cases): intent x style
                     clean no_diacritics          typo      mixed_en
   hint                 14             1             1             1
   check                 4             1             0             0
   concept               4             1             1             0
   offtopic              4             0             0             1
   pii                   4             1             0             0
   cells with 0 cases: [('check', 'mixed_en'), ('check', 'typo'), ('concept', 'mixed_en'), ('offtopic', 'no_diacritics'), ('offtopic', 'typo'), ('pii', 'mixed_en'), ('pii', 'typo')]
B. chance that a random sample of n=40 from 600 messages has no 'pii' message (24 in the log)
   exact 0.1846   simulated (20000 draws) 0.1853
C. how 40 cases are split over the five intents
   pool            {'hint': 305, 'check': 153, 'concept': 82, 'offtopic': 36, 'pii': 24}
   proportional    {'check': 10, 'concept': 6, 'hint': 20, 'offtopic': 2, 'pii': 2}
   equal           {'check': 8, 'concept': 8, 'hint': 8, 'offtopic': 8, 'pii': 8}
   floor           {'check': 9, 'concept': 7, 'hint': 13, 'offtopic': 6, 'pii': 5}
D. estimating the pass rate of the whole log from an equal-allocation sample (100 cases, 300 repeats)
   true pass rate            0.876
   mean of unweighted        0.812
   mean of weighted          0.874

Reading the output:

  • A. The eval_v1 set (38 cases) has 7 empty cells out of 20, and 14 of the 38 cases are piled into one cell (hint, clean).
  • B. The formula and the simulation both give about 0.185.
  • C. With the same size of 40, the three ways of splitting give pii 2, 8 and 5 cases respectively.
  • D. The true pass rate is 0.876; unweighted 0.812; weighted 0.874.

8.3 Stratify a sample of your own

Save as try_l02.py inside the lab folder:

from lab import coverage, sources, system

log = sources.load_log()
pool = [r for r in log if r["style"] == "clean"]
sizes = {k: sum(r["intent"] == k for r in pool) for k in system.INTENTS}
print(sizes)
print(coverage.allocation(sizes, 20, "floor", floor=2))
sample = coverage.stratified_sample(pool, "intent", 20, seed=4, mode="floor", floor=2)
print(len(sample), sorted({r["intent"] for r in sample}))
print(round(coverage.prob_stratum_missed(len(pool), sizes["pii"], 20), 4))

Run python try_l02.py. Output:

{'hint': 216, 'check': 106, 'concept': 61, 'offtopic': 24, 'pii': 18}
{'check': 5, 'concept': 3, 'hint': 7, 'offtopic': 3, 'pii': 2}
20 ['check', 'concept', 'hint', 'offtopic', 'pii']
0.4123

The last line: if you drop stratification and take 20 random messages from the clean messages, the probability of having no pii message is 0.4123.

8.4 Run the lesson's tests

python -m pytest tests/test_l02_coverage.py -v

Result: 12 passed. Read test_a_random_sample_misses_a_rare_stratum_as_often_as_the_formula_says and test_equal_allocation_biases_the_pooled_rate_and_weighting_removes_it: they check the two claims of §5.2 and §5.3 with simulation.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: n=... cannot give ... to each of ... strata n is smaller than the number of strata times the floor Increase n, lower the floor or merge strata
ValueError: ... has share ... but no results A stratum has a share but no results yet Run more cases for that stratum; do not drop the stratum from the weights
ValueError: min_count must be at least 1 min_count=0 makes every cell pass Use at least 1

9. Independent exercise

Problem: Assess the coverage of a pilot set and plan the sampling for the next round.

Requirements: complete exercises/test_l02_coverage.py:

  1. TODO 1: declare EXCLUDED: at most 2 cells (intent, style) the pilot does not need, each with a one-sentence reason.
  2. TODO 2: fill in GAPS: the list of necessary cells (the 20 cells minus EXCLUDED) that have fewer than 2 cases in pilot_cases.jsonl, in order.
  3. TODO 3: fill in ALLOC: split 30 cases over POOL (the sizes of the strata in the file) with mode floor and a floor of 3.
  4. TODO 4: fill in MISS: the probability (rounded to 4 digits) that a random sample of 30 cases from all of POOL has no pii case.

Test data: exercises/pilot_cases.jsonl (24 fictional cases) and POOL in the test file.

Deliverable: the four filled-in variables, with reasons for the removed cells.

Acceptance criteria: python -m pytest exercises/test_l02_coverage.py passes (2 tests); no more than 2 cells in EXCLUDED, each with a non-empty reason.

Hint: use coverage.gaps(..., min_count=2), coverage.allocation(..., "floor", floor=3) and coverage.prob_stratum_missed; compute, do not guess.

10. Knowledge check

0/16 done · Results are kept in this browser only.

P02 · True or false

The cell (check, no_diacritics) has exactly 1 case. That shows the system does well in that cell.

P04 · Select all that apply

Which dimensions are worth putting in HocVui Tutor's coverage matrix? Select all that apply (criterion: it changes the system's behavior and it can be observed in the data).

P05 · Put in order

Put the dataset coverage reporting process in order.

  1. List the required cells that are missing with coverage.gaps
  2. Report the matrix, the list of empty cells, the decisions and the limits
  3. Decide for each empty cell: add cases, drop the cell with a reason, or accept the risk
  4. Choose the dimensions (intent x style, with risk following intent)
  5. Compute the matrix, 0 cells included

P06 · Match

Match each sample-size allocation mode of coverage.allocation to its rule.

P07 · Spot the bug

The snippet below is taken from try_l02.py in §8.3 with one spot changed. Running it reports ValueError: n=20 cannot give 5 case to each of 5 strata. Find the bug.

from lab import coverage, sources, system
log = sources.load_log()
pool = [r for r in log if r["style"] == "clean"]
sizes = {k: sum(r["intent"] == k for r in pool) for k in system.INTENTS}
print(coverage.allocation(sizes, 20, "floor", floor=5))

P08 · Short answer

The team takes 20 cases evenly per intent and then reports the pooled pass rate of 100 cases, sees 0.812 and delays the release because "quality dropped". The log's true pass rate is 0.876. Explain why the number 0.812 points the wrong way and how to fix it.

P09 · Essay

The team writes 60 cases, all typed with full diacritics, and reports a pass rate of 0.898. Write 5-8 sentences: which dimension is missing, what the matrix would reveal, and the valid exits for an empty cell.

P10 · Multiple choice

The log has N = 600 messages, of which 24 have intent pii. You draw 40 messages at random without replacement. What is the approximate probability that the sample contains no pii message?

P11 · True or false

If you remove a cell from the required list, coverage.gaps still reports that cell as empty.

P12 · Fill in the blank

For the same size n = 40 over 5 intents, the pii stratum gets ___ cases under proportional, ___ under equal and ___ under floor with a floor of 5.

P13 · Select all that apply

Which of the following does the coverage matrix not check? Select all that apply.

P14 · Recall

Lesson: L2-M01-L04

To narrow the uncertainty about the population of questions, what does L2-M01-L04 §4.4 recommend? How does that relate to filling an empty cell of the matrix?

P15 · Recall

Lesson: L2-M02-L01

Match each PII handling method of L2-M02-L01 §5.3 to what it loses, then notice how that loss turns into an empty cell of the matrix.

11. Summary

  • Concepts: a coverage matrix over the dimensions that change behavior; an empty cell is a known blind spot; stratified sampling guarantees the rare stratum is present; taking more from a rare stratum means you must weight.
  • Skills: compute the matrix and empty cells; split a sample size three ways; compute the probability of missing a stratum; estimate the population pass rate with weights.
  • Traps: the matrix only counts, it does not assess quality; removing cells from the requirements to "pass"; reporting the pooled number of an equally split sample.
  • You can now: look at a dataset and ask: which dimensions, which cells are empty, why, and who decided to leave them empty.

12. References

ID Title Publisher URL Accessed Relevance
R1 Demystifying evals for AI agents Anthropic https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents 2026-11-03 Turn user-reported failures into test cases
R2 Evaluation best practices OpenAI https://developers.openai.com/api/docs/guides/evaluation-best-practices 2026-11-03 Test data includes typical, edge and adversarial cases
R3 NIST AI 600-1: Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile (July 2024) NIST https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.600-1.pdf 2026-11-03 MS-2.2-001: re-sampling, re-weighting (provenance context)
R4 Define success criteria and build evaluations (Develop tests) Anthropic https://platform.claude.com/docs/en/test-and-evaluate/develop-tests 2026-11-03 List of edge cases (read the first 100,000 characters)

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Coverage matrix Ma trận độ bao phủ
Dataset coverage Độ bao phủ của dataset (khác coverage của khoảng tin cậy)
Dimension Chiều: thuộc tính làm đổi hành vi
Cell Ô của ma trận
Stratum / stratified sampling Tầng / lấy mẫu phân tầng
Allocation Cách chia cỡ mẫu cho các tầng
Weighted rate Tỷ lệ có trọng số
Edge case / adversarial case Ca biên / ca đối kháng
Prompt injection Chèn chỉ dẫn để đổi hành vi của model