Sub topic 10
Analyzing Errors by Category
This chapter assumes you can write basic Python and read JSON. It also assumes you have a gold dataset and can compute span-level precision, recall and F1, as covered in the earlier chapters. You will learn to break an F1 score into error categories, to find out which category dominates, and to choose a fix from that.
Why one F1 score is not enough
An F1 of 0.71 says a system is imperfect. It does not say whether to rewrite the prompt, label more data, or switch models. Two systems with the same F1 can fail in very different ways. One may miss entities it has never seen. Another may find every entity but cut the boundaries one word too short.
Error analysis means reading the mistakes, assigning each to a category, and counting. The counts tell you where effort will pay off. It is the step that connects measurement to decisions, and it is the main input to the final chapter on choosing an approach.
A taxonomy of extraction errors
Under exact-match scoring, a prediction counts as correct only if its start, end and label all equal a gold span. Everything else is both a false positive (the prediction) and possibly a false negative (the gold span). The categories below split those mistakes by cause.
| Category | What happened | Example |
|---|---|---|
| Missed | A gold span has no overlapping prediction | "Berlin" never extracted |
| Spurious | A prediction overlaps no gold span | "Monday" extracted as a person |
| Boundary | Right label, overlapping span, wrong edges | "Bank of" instead of "Bank of America" |
| Label | Exact span, wrong label | "Paris" tagged PER instead of LOC |
| Label and boundary | Overlapping span, wrong edges and wrong label | "Mr. Paris" tagged ORG |
| Normalization | Right span, but the output value differs from the gold value | "1,200" returned as 1.2 |
| Format | Output cannot be parsed or breaks the schema | Prose around the JSON, missing key |
| Ungrounded | The value does not appear in the source text | A vendor name the model invented |
The last three apply mostly to generative systems that write values rather than select spans. A token classifier cannot return text that is not in the input, and it cannot return invalid JSON. A prompted model can do both.
Note that one boundary error costs you twice under exact match: one false positive and one false negative. Counting the error category once, not twice, keeps the analysis honest about how many mistakes there are.
Classifying span errors in code
The function below takes gold and predicted spans as (start, end, label) tuples and assigns each mistake a category. It pairs each unmatched gold span with at most one overlapping unmatched prediction.
from collections import Counter
def overlaps(a, b):
return a[0] < b[1] and b[0] < a[1]
def classify_errors(gold, pred):
gold, pred = set(gold), set(pred)
missing = sorted(gold - pred)
extra = sorted(pred - gold)
used = set()
errors = []
for g in missing:
match = None
for p in extra:
if p not in used and overlaps(g, p):
match = p
break
if match is None:
errors.append(("missed", g, None))
continue
used.add(match)
if (g[0], g[1]) == (match[0], match[1]):
errors.append(("label", g, match))
elif g[2] == match[2]:
errors.append(("boundary", g, match))
else:
errors.append(("label_and_boundary", g, match))
for p in extra:
if p not in used:
errors.append(("spurious", None, p))
return errors
gold = [(0, 2, "PER"), (5, 6, "LOC"), (8, 10, "ORG"), (12, 13, "DATE")]
pred = [(0, 1, "PER"), (5, 6, "ORG"), (8, 10, "ORG"), (15, 16, "LOC")]
errors = classify_errors(gold, pred)
for kind, g, p in errors:
print(kind, g, p)
print(dict(Counter(kind for kind, _, _ in errors)))Running it prints:
boundary (0, 2, 'PER') (0, 1, 'PER')
label (5, 6, 'LOC') (5, 6, 'ORG')
missed (12, 13, 'DATE') None
spurious None (15, 16, 'LOC')
{'boundary': 1, 'label': 1, 'missed': 1, 'spurious': 1}Run this over the whole evaluation set and keep the per-error records, not only the counts. You will want to read the underlying text for each category.
Checking grounding for generated values
For prompted extraction, add a check that the returned value is actually in the source. This catches invented values that still pass schema validation.
def is_grounded(value, text):
def norm(s):
return " ".join(s.split()).lower()
return norm(value) in norm(text)
print(is_grounded("Acme Corp", "Invoice from ACME corp, total 5"))
print(is_grounded("Acme Inc", "Invoice from Acme Corp"))This prints True, then False. The check applies to string fields copied from the text. It does not apply to fields the schema asks the model to compute or normalize, such as a date converted to ISO format. For those, compare against the gold normalized value and count mismatches as normalization errors.
Triage: from error pattern to fix
Once you have counts, the dominant category suggests where to look first. The diagram shows the usual order of checks.
The table gives the same mapping with the reasoning behind each step.
| Dominant error | Likely cause | First thing to try |
|---|---|---|
| Format failures | Prompt does not constrain output, or the model adds prose | Tighten the schema in the prompt, use structured-output features if available, retry on parse failure |
| Ungrounded values | Model fills fields it cannot find | Strengthen the null rule, drop or flag values that fail the grounding check |
| Spurious spans | Model or classifier is too eager | Add negative examples, state what must not be extracted |
| Missed spans | Pattern is rare or unseen | Add examples covering that pattern; for a classifier, add labeled data |
| Boundary errors | Guideline does not say where spans start and end | Specify rules for titles, suffixes and punctuation, then relabel |
| Label confusions | Two labels overlap in meaning | Write definitions that separate them, add contrasting examples |
| Normalization | Format rules missing from the schema | State the target format with an example, or normalize in code afterward |
Normalizing in code is often better than asking the model to do it. A deterministic function never varies between runs.
A repeatable procedure
- Score the system on the full gold set and save every error with its source text.
- Draw a sample. If you have fewer than about 100 errors, read all of them. Otherwise take at least 100 at random, stratified by label so rare labels are not drowned out.
- Assign one primary category to each error. When several apply, use a fixed priority, for example format, then ungrounded, then the span categories, so two readers reach the same answer.
- Check gold labels first. In many projects a noticeable share of apparent errors turn out to be annotation mistakes. Fix them and rescore before drawing any conclusion about the model.
- Slice the counts by label, document source, document length and any other field you have. A system that looks fine overall may fail on one source, such as scanned PDFs or one vendor's invoices.
- Make one change, re-run, and compare the category counts again.
If two people classify the same 30 errors and disagree often, your categories or priority rules are not clear enough. Fix that before trusting the counts.
Comparing prompted and fine-tuned systems
Run the same classifier on both systems using the same gold data. The profiles often differ in kind. These patterns are common tendencies, not rules, so check them against your own data:
- A prompted model tends to produce more format, ungrounded and normalization errors, and to follow the guideline loosely at span edges.
- A fine-tuned token classifier tends to follow the annotators' edge conventions closely, because it learned them from labeled spans. It tends to miss patterns that do not appear in its training data.
- A classifier trained with labels only on the first sub-token of each word, or an aggregation step that merges word pieces badly, can produce boundary errors that look like model weakness but come from the pipeline. Check offsets against the raw text before blaming the model.
A system that fails mostly on format and grounding can often be repaired cheaply with validation, retries and a clearer prompt. A system that fails mostly on missed spans for unseen patterns needs more examples, which favors whichever approach makes adding examples cheapest.
Edge cases and pitfalls
- Small counts are noisy. A category with 4 errors versus 7 is not evidence of a difference. Look for large gaps, and sample more if the decision depends on a small one.
- Relaxed matching hides problems. Scoring with overlap-based matching shows how much of the loss comes from boundaries. Report both exact and relaxed scores, but base your fixes on the exact-match categories your application depends on.
- Duplicates. A model that returns the same entity twice may be counted as one prediction by a set-based scorer and hide the problem. Count duplicates separately if downstream code cares.
- Fixing the metric instead of the system. If you widen the matching rule until the score rises, you have changed the target. Decide the matching rule from the downstream use, then keep it fixed.
- Overfitting to the error sample. If you add the exact error examples to your few-shot prompt or training set, the same examples no longer measure anything. Keep a held-out set that you do not read.
Exercise
A prompted invoice extractor scores 0.68 F1. You classify 120 errors and get: format 4, ungrounded 38, normalization 31, boundary 9, missed 22, spurious 16. After checking, you find 6 of the "missed" errors are gold mistakes. What do you do first, and what do you change next?
Show answer
First fix the 6 gold mistakes and rescore, because they distort every number. The largest categories are ungrounded (38) and normalization (31), so work on those next. Strengthen the null rule and add a grounding check that drops or flags values not found in the text. Move date and amount normalization into deterministic code. Only after those two categories shrink should you look at the 16 missed and 22 spurious errors, and a model change is premature while the cheap fixes remain.
Exercise
Gold spans are [(3, 6, "ORG")]. A system predicts [(3, 4, "PER")]. Which category does classify_errors assign, and why?
Show answer
labelandboundary. The prediction overlaps the gold span, so it is not missed or spurious. The edges differ (4 versus 6), so it is not a pure label error. The labels also differ (PER versus ORG), so it is not a pure boundary error.