Sub topic 8
Turning Grades into Metrics
A grader gives you a verdict for one output. A metric summarizes many verdicts into a number you can compare with a requirement. This chapter assumes you have an evaluation set and graders that return pass or fail per case, as in the earlier chapters. It also assumes you can read short Python. It covers how to aggregate grades, how to break them down, how much to trust the result, and how to handle output that changes between runs.
From verdicts to numbers
Suppose run_eval returned one record per case, each with an id, a severity and a passed flag. The simplest metric is the pass rate: passed cases divided by total cases. It is easy to explain and easy to compare with a threshold such as "at least 90%".
A single pass rate hides three things:
- Where the failures are. A 90% overall rate can mean 100% on easy questions and 0% on the ones that matter.
- How bad the failures are. One wrong refund amount and one awkward greeting count the same in a plain average.
- How uncertain the number is. Eight passes out of ten is not the same evidence as 800 out of 1,000.
The rest of the chapter addresses these three problems in turn.
Slice the results
A slice is a subset of cases that share a property: a category, a case type (typical, edge case, adversarial), or a severity level. Computing the pass rate per slice shows where the feature is weak.
The sample below has ten cases. Two fail: one critical refund edge case and one minor shipping edge case.
from collections import defaultdict
cases = [
{"id": "refund-001", "category": "refund_policy", "type": "typical"},
{"id": "refund-002", "category": "refund_policy", "type": "typical"},
{"id": "refund-003", "category": "refund_policy", "type": "edge_case"},
{"id": "refund-004", "category": "refund_policy", "type": "adversarial"},
{"id": "ship-001", "category": "shipping", "type": "typical"},
{"id": "ship-002", "category": "shipping", "type": "typical"},
{"id": "ship-003", "category": "shipping", "type": "typical"},
{"id": "ship-004", "category": "shipping", "type": "typical"},
{"id": "ship-005", "category": "shipping", "type": "typical"},
{"id": "ship-006", "category": "shipping", "type": "edge_case"},
]
failed = {"refund-003": "critical", "ship-006": "minor"}
results = [
{"id": c["id"], "severity": failed.get(c["id"], "minor"), "passed": c["id"] not in failed}
for c in cases
]
def pass_rate(results):
return sum(r["passed"] for r in results) / len(results) if results else 0.0
def by_slice(results, cases, field):
lookup = {c["id"]: c.get(field, "unknown") for c in cases}
groups = defaultdict(list)
for r in results:
groups[lookup[r["id"]]].append(r)
return {name: {"n": len(rs), "pass_rate": pass_rate(rs)} for name, rs in groups.items()}
def macro_average(slices):
rates = [s["pass_rate"] for s in slices.values()]
return sum(rates) / len(rates) if rates else 0.0
print("overall:", pass_rate(results))
print("by type:", by_slice(results, cases, "type"))
categories = by_slice(results, cases, "category")
print("by category:", categories)
print("macro average over categories:", round(macro_average(categories), 4))The output is:
overall: 0.8
by type: {'typical': {'n': 7, 'pass_rate': 1.0}, 'edge_case': {'n': 2, 'pass_rate': 0.0}, 'adversarial': {'n': 1, 'pass_rate': 1.0}}
by category: {'refund_policy': {'n': 4, 'pass_rate': 0.75}, 'shipping': {'n': 6, 'pass_rate': 0.8333333333333334}}
macro average over categories: 0.7917The overall 80% looks acceptable. The type breakdown shows that every edge case failed, and one of those failures is critical. The overall number alone would not have shown that.
Micro and macro averages
The overall pass rate is a micro average: every case counts equally, so categories with more cases dominate. A macro average takes the mean of per-slice rates, so every slice counts equally regardless of size. Use the micro average when your evaluation set mirrors real traffic. Use the macro average, or per-slice thresholds, when you deliberately oversampled rare but important slices. Say which one you report, because the two can differ by several points.
Handle severity separately
Do not fold severity into a weighted average and treat the result as the quality score. A weighted average lets many small passes offset one serious failure. Report two things instead:
- A pass rate for the ordinary requirement.
- A count, with case IDs, for each zero-tolerance severity level.
This matches the release gate shown earlier, which checks pass_rate >= min_pass_rate and an empty critical_failures list as separate conditions. The metric report should always list the failing critical cases by ID, so a reviewer can open each one.
Report uncertainty
An evaluation set is a sample of possible user inputs. A pass rate measured on it is an estimate of the pass rate on all inputs. The smaller the set, the wider the plausible range.
A Wilson score interval gives a range for a pass rate that behaves sensibly for small samples and for rates near 0% or 100%. The simple "plus or minus" formula based on the normal approximation does not.
import math
def wilson_interval(passes, total, z=1.96):
if total == 0:
return (0.0, 1.0)
p = passes / total
denom = 1 + z**2 / total
center = (p + z**2 / (2 * total)) / denom
margin = z * math.sqrt(p * (1 - p) / total + z**2 / (4 * total**2)) / denom
return (max(0.0, center - margin), min(1.0, center + margin))
for passes, total in [(8, 10), (95, 100), (950, 1000)]:
low, high = wilson_interval(passes, total)
print(f"{passes}/{total}: observed {passes/total:.3f}, 95% interval {low:.3f} to {high:.3f}")The output is:
8/10: observed 0.800, 95% interval 0.490 to 0.943
95/100: observed 0.950, 95% interval 0.888 to 0.978
950/1000: observed 0.950, 95% interval 0.935 to 0.962Three consequences follow:
- With 10 cases, an observed 80% is consistent with a true rate anywhere from about 49% to 94%.
- With 100 cases, an observed 95% does not show that the true rate is at least 95%. The lower bound is about 89%.
- If the requirement says "at least 95%", you need either many more cases or an agreed rule, such as requiring the lower bound to clear a lower floor.
Zero failures is not zero risk
A zero-tolerance rule such as "no critical contradictions" is checked by counting failures in a finite set. Observing 0 failures in n cases only bounds the true failure rate. A common approximation, the rule of three, says the 95% upper bound is about 3/n. With 50 cases and no failures, the true failure rate could still be near 6%. A zero-tolerance requirement therefore needs a stated sample size, or it needs a method other than sampling, such as an output filter that blocks the failure by construction.
Comparing two versions
When you compare two versions of the feature, run both on the same cases and look at the cases whose result changed. A difference of two cases in a set of 100 is usually noise. Ten cases moving from pass to fail, with none moving the other way, is a signal. Counting the changed cases in each direction, called paired comparison, is more informative than comparing two overall rates with overlapping intervals.
Handle nondeterministic output
The same input can produce different outputs, so a case can pass on one run and fail on the next. Running each case once measures one random draw. Run each case k times, such as 3 or 5, and compute metrics over the repeated grades.
def repeated_metrics(runs):
"""runs maps case id to a list of pass/fail booleans, one per repeat."""
total_runs = sum(len(v) for v in runs.values())
total_passes = sum(sum(v) for v in runs.values())
return {
"mean_pass_rate": round(total_passes / total_runs, 4),
"all_runs_pass": sum(all(v) for v in runs.values()) / len(runs),
"any_run_passes": sum(any(v) for v in runs.values()) / len(runs),
}
runs = {
"case-a": [True, True, True],
"case-b": [True, False, True],
"case-c": [False, False, False],
"case-d": [True, True, True],
}
print(repeated_metrics(runs))The output is:
{'mean_pass_rate': 0.6667, 'all_runs_pass': 0.5, 'any_run_passes': 0.75}Each of the three numbers answers a different question:
| Metric | Question it answers | Use it when |
|---|---|---|
| Mean pass rate | How often does a random attempt succeed? | Users see one answer and a miss is tolerable |
| All runs pass | Does the case pass every time? | A failure is costly, or the feature must be reliable |
| Any run passes | Can the feature succeed at all, given retries? | Users can regenerate, or you retry automatically |
Case-b is the instructive one. It passes two of three runs, so the mean counts it as mostly working, while the strict metric counts it as a failure. Choose the metric that matches how the feature is used, and write it into the requirement.
Aggregating scores that are not pass or fail
Some graders return a score, such as a 1 to 5 rubric rating or a latency in milliseconds. Pick the aggregate to match the requirement:
| Data | Aggregate | Why |
|---|---|---|
| Rubric rating 1 to 5 | Share of cases scoring at least 4 | A mean of 3.8 can hide a mix of 5s and 1s |
| Latency | 95th percentile | The average hides the slow responses users notice |
| Cost per request | Mean and 95th percentile | The mean predicts the bill, the tail predicts outliers |
| Count of unsupported claims | Share of answers with zero | The requirement cares about clean answers, not the average count |
Converting a score to pass or fail with a cutoff is often the simplest option. Choose the cutoff before looking at results, and write it in the requirement.
Common errors
| Error | Why it misleads | Fix |
|---|---|---|
| Reporting only the overall pass rate | Hides weak slices and critical failures | Report per-slice rates and list critical failures |
| Comparing runs on different case sets | Differences may come from case difficulty | Fix the set per comparison and record its version |
| Judging on one run | One random draw can pass or fail | Repeat runs and report the metric that fits the use |
| Reading 0 failures as safe | A finite sample bounds the risk, it does not remove it | State the sample size and the upper bound |
| Averaging severity into a score | Small passes offset a serious failure | Keep critical counts as a separate gate |
| Tuning the feature against the test cases | The metric rewards memorizing the set | Hold out a subset that nobody tunes against |
| Changing the metric after seeing results | The threshold stops meaning anything | Record the metric definition with the requirement |
What a metric report should contain
A report that supports a release decision has these parts:
- The evaluation set version and number of cases.
- The overall pass rate, with its 95% interval.
- The pass rate per category and per case type, with case counts.
- The repeated-run metric chosen for the requirement.
- The list of failed critical cases by ID.
- Changes against the previous version: cases that flipped in each direction.
The next step is to compare these numbers with thresholds, which is the subject of acceptance criteria.
Exercise
Your evaluation set has 40 cases. The feature passes 38. The requirement says "at least 95% of answers are correct." Does the result show the requirement is met? Give the reasoning in terms of the observed rate and the uncertainty, and name one change that would make the check more reliable.
Show answer
The observed rate is 38/40 = 95%, which meets the threshold exactly. The evidence is weak. With 40 cases, the 95% Wilson interval for 38 passes is roughly 83% to 98%, so the true rate could be well below 95%. The result is consistent with the requirement, but it does not demonstrate it. Reliable options are to add more cases (several hundred narrow the interval much more), to repeat each case several times if the output is nondeterministic, or to agree in advance on a decision rule, such as requiring the lower bound of the interval to exceed an agreed floor.
Exercise
A case passes on 2 of 5 repeated runs. For a support chatbot where the user sees a single answer, which repeated-run metric should the requirement use, and how does the case count under each of "mean pass rate", "all runs pass" and "any run passes"?
Show answer
Use the mean pass rate, or the all-runs-pass metric if wrong answers are costly, because the user sees one draw and cannot retry. Under the mean pass rate the case contributes 2/5 = 40%. Under all runs pass it counts as a failure. Under any run passes it counts as a success, but that metric overstates quality here because users do not get several attempts.
Exercise
An evaluation set contains 90 typical cases (all pass) and 10 adversarial cases (6 pass). What are the micro and macro averages over the two case types, and which one would you report if the set was built to match real traffic?
Show answer
The micro average is 96/100 = 96%. The macro average is (1.0 + 0.6) / 2 = 80%. If the set mirrors real traffic, report the micro average as the expected overall rate, and also report the adversarial slice at 60% separately, since the macro average and the slice rate show a weakness that the micro average hides.