CD0008 Debug Eval Metrics Script

Mode A · Bug Hunt 30 Min Python 3 (stdlib only) 4 Silent Bugs

In a Google code-comprehension round, the interviewer shares a 42-line pure-Python scorer that a teammate wrote for a review-moderation classifier with three labels: ok, spam, and the rare abuse. It reads two CSV exports of example_id,label rows, one from the batch inference job and one from the labeling pipeline. It then prints overall accuracy and one row per class with its confusion counts (tp, fp, fn), precision P, and recall R. The script uses only the standard library and never raises.

Three reviewers still flag the output. (1) On a review fixture where two predictions have no gold row and the gold export carries two ids the inference job never scored, accuracy prints 1.250. (2) On the same fixture, the rare-class row prints abuse tp=1 fp=2 fn=0 P=1.000, a precision that cannot coexist with two false positives. (3) On a four-row file where every prediction is wrong, one class still reports P=1.000.

Read the script in data-flow order (load → pair → count → divide → print). Identify the 4 silent bugs in the metric computations and explain why each yields a plausible number instead of an exception. Patch them in place without restructuring the functions, then write a verification test on a hand-computable fixture that pins accuracy and every tp, fp, fn, P, and R value.

Evaluation Script (Find 4 Silent Bugs):

01  import csv
02
03
04  def load_labels(lines):
05      """Parse 'example_id,label' CSV lines into {example_id: label}."""
06      return {ex_id: label.strip() for ex_id, label in csv.reader(lines)}
07
08
09  def safe_div(num, den):
10      try:
11          return num / den
12      except ZeroDivisionError:
13          return 1.0
14
15
16  def accuracy(pred, gold):
17      scored = [ex_id for ex_id in pred if ex_id in gold]
18      correct = sum(p == y for p, y in zip(pred.values(), gold.values()))
19      return correct / len(scored)
20
21
22  def per_class(pred, gold):
23      rows = [(pred[ex_id], gold[ex_id]) for ex_id in pred if ex_id in gold]
24      classes = sorted(set(row[0] for row in rows))
25      report = {}
26      for c in classes:
27          tp = sum(1 for p, y in rows if p == c and y == c)
28          fp = sum(1 for p, y in rows if p == c and y != c)
29          fn = sum(1 for p, y in rows if p != c and y == c)
30          precision = safe_div(tp, tp + fn)
31          recall = safe_div(tp, tp + fp)
32          report[c] = (tp, fp, fn, precision, recall)
33      return report
34
35
36  def evaluate(pred_lines, gold_lines):
37      pred, gold = load_labels(pred_lines), load_labels(gold_lines)
38      acc, report = accuracy(pred, gold), per_class(pred, gold)
39      print(f"accuracy {acc:.3f}")
40      for c, (tp, fp, fn, prec, rec) in report.items():
41          print(f"{c:>6} tp={tp} fp={fp} fn={fn} P={prec:.3f} R={rec:.3f}")
42      return acc, report
Review fixture for the eval script: a predictions.csv table with ten rows r01 to r10 and a gold.csv table with ten rows in labeling-export order, shaded where an id appears in only one file; on the right, the unpatched script's printed output for the review fixture and for a four-row all-wrong file, with tags (1) to (3) marking the three reviewer flags

Figure 1: the two exports of the review fixture (shaded ids exist in only one file) and what the unpatched script prints for that fixture and for a four-row all-wrong file. Tags (1) to (3) mark the three reviewer flags.

Interactive Python Workspace: Switch to the split-screen workspace to patch the scorer in the live editor and run the behavioral check suite on the review fixtures.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Example Pairing: Check how each prediction meets its gold label, and confirm the accuracy numerator and denominator count the same population of examples.
(2) Ratio Denominators: Precision divides by the predicted-positive count and recall by the gold-positive count; check each printed ratio against the counts on its own row.
(3) Class Universe: A per-class report should contain a row for every class that appears in the gold labels.
(4) Undefined Ratios: Decide what a 0/0 ratio should report so that an all-wrong prediction file can never look good.

2Visual Review Map (Figure 2)
Data-flow review map of the scorer: CSV files feed load_labels, which branches into the accuracy path and the per-class path (rows, class list, tp fp fn counts, P and R ratios that call safe_div); four stages carry a uniform question-mark marker with their line ranges

Figure 2: The data-flow order a strong candidate reads aloud. Each of the four stages marked ? hides one silent bug, and the line ranges match the numbered listing.

3Interviewer Nudge & Line Focus

Walk each stage and answer the Socratic check before editing:

Accuracy Stage: Lines 17 and 18 each build their own view of which examples get scored. On the review fixture, how many (prediction, gold) pairs does the numerator iterate over, and how many examples does the denominator count? What invariant would make accuracy at most 1 by construction?
Per-Class Ratios: Take the abuse row with tp=1, fp=2, fn=0 and compute precision and recall by hand. Which of the two counts belongs in each denominator, and does the printed P agree with your number?
Class List: Each element of rows is a two-field tuple. If the model never predicts a class that gold contains, should that class still get a recall row? Which field decides whether it appears?
Division Guard: When a ratio’s denominator is zero, the metric is undefined. What does a reader of the report assume a printed 1.000 means, and what score should any class get on a file where every prediction is wrong?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *