Sub topic 12
Measuring detection quality
A detector that "seems to work" on a few examples is not good enough for redaction. A missed email address reaches the model provider. A false alarm removes a word the model needed. This chapter shows how to turn those two failures into numbers, so you can compare detectors, choose thresholds, and know where to improve.
This chapter assumes you have read the earlier chapters on regex, checksum, and NER detection, and on combining detectors into one pipeline. It also assumes you are comfortable with Python lists, dictionaries, and tuples. Every detector here returns spans as (start, end, label) tuples.
What you are measuring
A detector reads text and returns predicted spans. A person has already marked the correct spans, called the gold spans. Evaluation compares the two lists. Each comparison produces one of three outcomes:
- True positive (TP): the detector reported a span that matches a gold span.
- False positive (FP): the detector reported a span that matches no gold span. This is a false alarm. The text is over-redacted.
- False negative (FN): a gold span has no matching prediction. This is a miss. Personal data leaks through.
True negatives, meaning all the text that is correctly left alone, are not counted. Nearly every character is a true negative, so a count of them says nothing useful.
Precision, recall, and F1
Three numbers come from the counts:
| Metric | Formula | Question it answers |
|---|---|---|
| Precision | TP / (TP + FP) | Of the spans I redacted, how many really were personal data? |
| Recall | TP / (TP + FN) | Of the personal data that exists, how much did I find? |
| F1 | 2 × P × R / (P + R) | A single score that is high only when both are high. |
For redaction, recall usually matters more. A false negative is a privacy failure. A false positive is a quality cost, such as a model that cannot see a product code that looked like a phone number. Report both numbers, and do not rely on F1 alone. F1 hides which side is failing, and it treats a miss and a false alarm as equally bad.
Handle empty denominators explicitly. If a detector predicts nothing for a label, precision is 0/0. Pick a convention, such as reporting 0.0, and use it everywhere.
What counts as a match
You must decide when a predicted span matches a gold span. Two common rules:
- Exact match: start, end, and label are all equal.
- Overlap match: the label is equal and the character ranges overlap.
The two rules answer different questions. Suppose the gold span is "Maria Lopez" and the NER model returns only "Maria". Under exact matching this is one false positive and one false negative. Under overlap matching it is a true positive. But redacting only "Maria" leaves "Lopez" in the text. Overlap matching can therefore overstate how well you protect the data.
A practical approach is to report both. The exact-match score tells you about boundary quality. The overlap score tells you whether the detector found the entity at all. A large gap between them points to a boundary problem, not a detection problem. Typical causes are trailing punctuation, titles such as "Dr.", and spaces or hyphens inside card numbers.
For a strict privacy check, you can add a third rule: coverage. A gold span counts as found only if the predicted spans together cover all of its characters. This rule is the closest to the question "did the sensitive text actually disappear?"
Computing the metrics
The code below implements both matching modes. Each gold span can match at most one prediction, and each prediction can match at most one gold span. Scores are computed per label and overall.
from collections import defaultdict
def overlaps(a, b):
return a[0] < b[1] and b[0] < a[1]
def count_matches(gold, pred, mode):
used = set()
tp = 0
for g in gold:
for i, p in enumerate(pred):
if i in used or p[2] != g[2]:
continue
if mode == "exact":
matched = (p[0], p[1]) == (g[0], g[1])
else:
matched = overlaps(p, g)
if matched:
used.add(i)
tp += 1
break
return tp, len(pred) - len(used), len(gold) - tp
def evaluate(docs, mode="exact"):
counts = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0})
for gold, pred in docs:
labels = {s[2] for s in gold} | {s[2] for s in pred}
for label in labels:
g = [s for s in gold if s[2] == label]
p = [s for s in pred if s[2] == label]
tp, fp, fn = count_matches(g, p, mode)
counts[label]["tp"] += tp
counts[label]["fp"] += fp
counts[label]["fn"] += fn
return counts
def scores(c):
tp, fp, fn = c["tp"], c["fp"], c["fn"]
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return precision, recall, f1
# Each item is (gold_spans, predicted_spans) for one document.
# Doc 1: "Contact [email protected] or call 555-0100."
# Doc 2: "Order 1234567890123 shipped to Maria Lopez."
docs = [
([(8, 23, "EMAIL"), (32, 40, "PHONE")],
[(8, 23, "EMAIL")]),
([(31, 42, "PERSON")],
[(6, 19, "PHONE"), (31, 36, "PERSON")]),
]
for mode in ("exact", "overlap"):
counts = evaluate(docs, mode)
total = {k: sum(c[k] for c in counts.values()) for k in ("tp", "fp", "fn")}
print(mode)
for label in sorted(counts):
p, r, f = scores(counts[label])
print(f" {label:7} P={p:.2f} R={r:.2f} F1={f:.2f}")
p, r, f = scores(total)
print(f" {'ALL':7} P={p:.2f} R={r:.2f} F1={f:.2f}")The example has three errors. The phone number in document 1 is missed. The 13-digit order number in document 2 is reported as a phone number. The name is found only partly. In exact mode the overall precision, recall, and F1 are all 0.33. In overlap mode they are all 0.67, because the partial name counts as a hit. The per-label lines show where the errors sit: EMAIL is perfect, PHONE has both a false positive and a false negative, and PERSON depends on the matching rule.
Building a labelled test set
The metrics are only as good as the gold data. Follow these rules:
- Use realistic text. Sample from real prompts, support tickets, or documents, after getting permission and protecting them properly. If you cannot use real text, generate synthetic text that includes your messy formats, such as phone numbers with dots, spaces, and country codes.
- Include hard negatives. Add text that looks like personal data but is not: order numbers, version strings, product codes, and dates that are not birth dates. Without them, precision looks better than it is.
- Cover every label you detect. Give each label enough examples that its score is meaningful. A recall of 1.0 over three examples tells you almost nothing.
- Label consistently. Write down rules for edge cases. Decide whether "Dr. Chen" includes the title, and whether a company name that contains a surname is a PERSON. Have a second person label a sample and compare. Disagreement between labellers sets a ceiling on any detector's score.
- Split the data. Keep a development set for tuning and a test set that you touch rarely.
Error analysis
A score says how much is wrong. Error analysis says why. List every false positive and false negative with a few characters of context, then group them by cause. Common groups:
| Symptom | Likely cause | Typical fix |
|---|---|---|
| Many false positives on digit strings | Broad pattern, no validation | Add a checksum or context words |
| Missed phone numbers | Format not covered by the pattern | Extend the pattern, add test cases |
| Names missed in lowercase or all-caps text | NER model trained on clean text | Try a larger model or add a gazetteer |
| Exact score far below overlap score | Boundary differences | Trim punctuation, merge adjacent spans |
| Same text reported with two labels | Overlapping detectors | Resolve overlaps by score or priority |
Fix the largest group first. Add each failing example to the development set as a regression test, so the same error cannot return unnoticed.
Scores and thresholds
Many detectors attach a confidence score to each span. A score threshold sets the trade-off between precision and recall. Raising it removes uncertain spans, which increases precision and lowers recall. Lowering it does the reverse.
To choose a threshold, compute precision and recall at several values on the development set and compare them. For redaction, pick the threshold that reaches your recall target first, then accept whatever precision results. Consider setting a different threshold per label. A checksum-validated card number deserves a low threshold because false alarms are rare. A bare person name from NER may need a higher one.
Common mistakes
- Reporting one overall number. A strong EMAIL score can hide a weak PERSON score. Always show per-label results.
- Mixing matching rules between runs. Compare detectors only under the same rule.
- Testing on too little data. With 20 examples, one error moves recall by 5 points. Collect enough examples that a single error does not dominate.
- Ignoring the pipeline. Measure the whole pipeline after overlap resolution, not each detector alone. Overlap resolution can drop correct spans.
- Treating a high score as proof of safety. The test set only contains the cases you thought of. The final chapter covers what automated detection cannot catch.
Exercise
A detector returns 40 spans on a test set. 30 of them match gold spans. The test set contains 50 gold spans in total. What are the precision, recall, and F1?
Show answer
TP = 30, FP = 40 - 30 = 10, FN = 50 - 30 = 20. Precision = 30/40 = 0.75. Recall = 30/50 = 0.60. F1 = 2 × 0.75 × 0.60 / (0.75 + 0.60) = 0.90 / 1.35 ≈ 0.67. For redaction, the recall of 0.60 is the worrying number: 20 pieces of personal data would reach the model.
Exercise
Your evaluation shows exact-match F1 of 0.55 and overlap-match F1 of 0.85 for the PERSON label. What does the gap suggest, and what would you check first?
Show answer
The detector finds most names but gets the boundaries wrong. Inspect the false positive and false negative pairs that overlap each other. Look for titles, trailing punctuation, or names split into separate spans, and fix them with trimming or span merging. Also check whether the partial spans leave part of the name unredacted, because overlap scoring hides that leak.