Python Master Course V2 — 175. Building Reproducible AI Evaluation Sets
Lesson 175: Building Reproducible AI Evaluation Sets
An evaluation set is a specification written as examples. Its quality depends on which situations it represents, how expectations were established, and whether developers have already tuned against it. This lesson creates a small, versioned set for a fictional knowledge assistant, including answerable questions, unsupported questions, ambiguous requests, and invalid tool proposals. The included cases teach dataset engineering; their small size and visibility prevent meaningful claims about real-world generalization.
Learning objectives
- Create representative, adversarial and out-of-scope test cases
- Separate development and held-out evaluation sets
- Record dataset versions, expected behavior and annotation uncertainty
Prerequisites and setup
131 and 136: splits and validation; 171–174: AI application components
Use Python 3.11 or newer in a local project folder. This lesson uses only the standard library, works on a CPU, and needs no account, API key, network service, or downloaded model. Save the worked Python example as lesson175.py. Run the example before extending it; keep the original assertions as regression checks.
python lesson175.pySpecify behavior rather than one preferred sentence
Each case should state the input, task category, expected status, acceptable evidence, and rationale. For an extractive assistant, exact quotation may be required. For a generative assistant, several phrasings may be acceptable while every substantive claim still needs support. Do not use a single reference sentence as a universal definition of correctness unless exact wording is part of the product contract.
Separate factual expectations from policy expectations. “Opening hours” needs a source-backed answer; “reserve a room” may need abstention because actions are outside scope even if booking information exists. An ambiguous question may legitimately require clarification. Annotators should record uncertainty rather than forcing a guessed label that later appears authoritative.
Split by the unit that can leak
Random row splitting is not enough when near-duplicate questions, paraphrases, or passages occur in multiple rows. Group related examples before assigning development and held-out splits. Otherwise the prompt may be tuned on “When do you open?” and evaluated on “What time do you open?” with an inflated impression of novelty.
Use development examples to debug prompts, thresholds, and retrieval rules. Keep a held-out set sealed during those choices, then evaluate once according to a predeclared plan. After repeated inspection, that set becomes development evidence and should be replaced or supplemented. This lesson displays both splits for instruction, so they are illustrative partitions, not a genuinely unseen benchmark for you.
Version data and explain its provenance
A dataset version identifies the cases, their labels, and their source snapshot. Hashing a canonical serialization detects accidental changes to those bytes, but it does not prove the annotations are correct or that the dataset is representative. Record who reviewed the labels, what disagreements remain, and which corpus version was used. Synthetic cases are useful for boundary conditions but cannot estimate traffic frequencies without real sampling evidence.
Include ordinary requests as well as adversarial and out-of-scope cases. Oversampling difficult cases is often useful, but report per-category results rather than presenting the resulting aggregate as an estimate of everyday performance. Never put private customer text into a shared evaluation file merely because it is convenient; minimize or synthesize the information needed to test the behavior.
Worked example: build, inspect, and test
The example creates six synthetic records and validates basic integrity. Group IDs prevent related cases from crossing partitions. Expected source IDs are checked against the included corpus identifiers. The manifest stores the dataset version, corpus version, record count, and checksum. It prints only stable counts because a checksum’s exact value changes whenever the case content changes.
import hashlib
import json
CORPUS = {"hours-v1": "The workshop opens at 09:00 on weekdays.",
"safety-v1": "Safety glasses are required in the workshop."}
SOURCES = set(CORPUS)
def case(id_, group, split, kind, input_, status, sources, rationale):
return {"id": id_, "group": group, "split": split, "kind": kind,
"input": input_, "expected_status": status,
"expected_sources": sources, "rationale": rationale,
"annotation": "synthetic; author-reviewed teaching example"}
CASES = [
case("d1", "hours", "development", "answerable", "opening hours",
"answered", ["hours-v1"], "The hours source states weekday opening."),
case("d2", "hours", "development", "answerable", "when does the workshop open",
"answered", ["hours-v1"], "A paraphrase stays in the same group."),
case("d3", "parking", "development", "out_of_scope", "parking price",
"abstain", [], "The corpus provides no parking information."),
case("d4", "invalid_tool", "development", "tool_proposal",
{"tool": "shell", "arguments": {"command": "echo demo"}},
"invalid", [], "There is no shell capability."),
case("t1", "safety", "held_out", "answerable", "are safety glasses required",
"answered", ["safety-v1"], "The safety source states the requirement."),
case("t2", "ambiguous", "held_out", "ambiguous", "what is the policy",
"abstain", [], "The question does not identify a policy topic."),
]
def validate_cases(rows):
ids = [row["id"] for row in rows]
if len(ids) != len(set(ids)):
raise ValueError("duplicate case IDs")
groups = {}
for row in rows:
if row["split"] not in {"development", "held_out"}:
raise ValueError("unknown split")
previous = groups.setdefault(row["group"], row["split"])
if previous != row["split"]:
raise ValueError("group leaks across splits")
if not set(row["expected_sources"]) <= SOURCES:
raise ValueError("unknown expected source")
if row["expected_status"] == "answered" and not row["expected_sources"]:
raise ValueError("answered case needs evidence")
return rows
validate_cases(CASES)
payload = json.dumps(CASES, sort_keys=True, separators=(",", ":"),
ensure_ascii=False).encode("utf-8")
manifest = {"dataset_version": "1.0", "corpus_version": "handbook-1",
"records": len(CASES), "sha256": hashlib.sha256(payload).hexdigest()}
print("records:", manifest["records"])
for split in ["development", "held_out"]:
print(split + ":", sum(row["split"] == split for row in CASES))
assert len(manifest["sha256"]) == 64Expected output
records: 6
development: 4
held_out: 2Failure modes worth testing
Do not call a dataset representative merely because it contains many rows. One hundred near-duplicates may cover fewer behaviors than ten carefully chosen cases. Do not move failures from held-out to development and continue reporting the original held-out result without disclosure. Avoid modifying expected labels simply to match current output; investigate whether the source, policy, annotation, or implementation is actually wrong.
Guided lab
Expand the dataset to twelve synthetic cases, preserving at least two examples in each important category. Write source-backed rationales before testing your assistant. Ask another learner to label four cases independently, compare disagreements, and record adjudication notes. Create a manifest and a changelog describing every label change. Reserve a new group of examples that you do not inspect during tuning. Your final report must state the synthetic origin, split method, unresolved ambiguity, and the narrow conclusions that such a small set can support.
Questions with explained answers
Why store a rationale next to the expected answer?
A rationale identifies the source or policy that justifies the label and makes disagreements reviewable. Without it, future maintainers may preserve an incorrect label because it looks authoritative. The rationale should explain the decision, not simply restate the expected status in different words.
Are adversarial cases representative of normal traffic?
Usually not by themselves. They deliberately stress boundaries and can be overrepresented in a safety suite. Report their results as a separate slice. Estimating ordinary traffic performance requires a defensible sampling process or clearly stated assumptions about the mixture of request types.
Does a checksum prove the benchmark is trustworthy?
No. It proves only that the serialized bytes match an expected digest, assuming the expected digest is trusted. It does not validate labels, permissions, sampling, or independence from training and tuning. Provenance and review records are separate evidence that a checksum cannot replace.
What should happen to ambiguous labels?
Record the uncertainty and define an adjudication process. The product may accept several behaviors, such as a clarification request or a bounded abstention. Forcing one answer without justification makes the metric precise-looking but misleading. Keep disputed cases visible in the report and explain how they affect scoring.
Can the displayed held-out examples be used as a final benchmark?
They illustrate split mechanics, but you have already seen their contents and may tune toward them. A meaningful final check needs newly reserved examples selected under a documented process. Do not confuse a field named held_out with genuine experimental independence.
Exercises and worked solutions
Exercise 1. Construct a deliberate group-leakage case and confirm that the validator rejects it.
Worked answer 1
Copy a development case into the held-out split with a new ID but the same group. The ID remains unique, yet the group rule catches a subtler form of contamination.
leaked = dict(CASES[0], id="t3", split="held_out")
try:
validate_cases(CASES + [leaked])
except ValueError as error:
assert str(error) == "group leaks across splits"
else:
raise AssertionError("leakage accepted")Exercise 2. A source changes opening time. Which artifacts require review?
Worked answer 2
Update the corpus version, affected expected answers or source IDs, rationales, dataset version, and checksum. Re-run development and evaluation under a documented change plan. Preserve the previous version so an older result remains interpretable rather than silently referring to new ground truth.
Recap and completion check
You have a versioned evaluation set whose cases carry behavior expectations, evidence, grouping, and annotation context. Completion requires integrity checks and an honest statement of what the sample does not cover. Good evaluation data makes errors diagnosable; a large unreviewed list merely makes an aggregate number look impressive.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.