Sub topic 10
Error Types in Sequence Labeling
This chapter assumes you have trained a sequence tagger, such as a named entity recognizer, at least once. It also assumes you know the BIO tagging scheme and the difference between precision, recall and F1. Earlier chapters covered confusion matrices for classifiers. A tagger needs more than that, because its errors have positions and lengths.
Why token accuracy hides tagger errors
A sequence labeler assigns a tag to every token. Most tokens are outside any entity, so they carry the tag O. A model that predicts O everywhere can reach 90% or more token accuracy and still find no entities.
Entity-level evaluation fixes this. A predicted entity counts as correct only if its start, end and type all match a gold entity. This is the strict-match scheme used by conlleval and by the seqeval library. The strict score is the right headline number, but it gives one failure for very different mistakes:
- The model found the right words but called a person an organization.
- The model found the right type but included one word too many.
- The model found nothing at all.
Each of these has a different cause and a different fix. Error analysis for taggers begins by separating them.
Four span error categories
Represent each entity as a span (start, end, type), with end exclusive. Compare the set of gold spans with the set of predicted spans. Exact matches are correct. Everything else falls into one of these categories:
| Category | What happened | Typical cause | Typical fix |
|---|---|---|---|
| Type error | Same boundaries, wrong type | Ambiguous names (a company named after a city), weak context features | More contrastive training examples, clearer annotation guidelines |
| Boundary error | Same type, overlapping but different boundaries | Titles, suffixes such as "Inc.", punctuation, tokenization mismatch | Check guideline rules on what belongs inside a span, check the tokenizer |
| Type and boundary error | Overlapping, with both different | Often a sign of a truly confusing mention | Read these by hand, they are often label noise |
| Missed (false negative) | A gold span with no overlapping prediction | Rare entities, unseen vocabulary, lowercase text | Gazetteers, more data, domain adaptation |
| Spurious (false positive) | A predicted span with no overlapping gold span | Over-eager model, capitalized non-entities, missing gold annotations | Negative examples, check whether the gold data omitted a real entity |
The last two categories are different in kind. Missed and spurious spans have no partner on the other side. The first three categories describe a gold span and a prediction that overlap.
A decision procedure
The order of the checks matters. First test whether any prediction overlaps the gold span at all. Only then compare boundaries, and only then compare types.
Two spans overlap when each starts before the other ends: g.start < p.end and p.start < g.end. This test is correct for half-open intervals. A test such as g.start <= p.end would wrongly treat two adjacent entities as overlapping.
Implementing the categorizer
The function below walks over the gold spans that were not predicted exactly. It pairs each with the first unmatched overlapping prediction and removes that prediction from the pool so it cannot be reused. Predictions left in the pool at the end are spurious. The script also counts categories and computes strict-match precision, recall and F1, so you can see how one number summarizes four kinds of failure.
from collections import Counter
def categorize(gold, pred):
"""Spans are (start, end, type) with end exclusive."""
errors = []
unmatched_pred = set(pred - gold)
for g in sorted(gold - pred):
overlap = [p for p in sorted(unmatched_pred) if g[0] < p[1] and p[0] < g[1]]
if not overlap:
errors.append((g, None, "missed"))
continue
p = overlap[0]
unmatched_pred.discard(p)
if (g[0], g[1]) == (p[0], p[1]):
kind = "type_error"
elif g[2] == p[2]:
kind = "boundary_error"
else:
kind = "type_and_boundary_error"
errors.append((g, p, kind))
errors.extend((None, p, "spurious") for p in sorted(unmatched_pred))
return errors
gold = {(0, 2, "PER"), (5, 7, "ORG"), (9, 10, "LOC"), (15, 16, "PER")}
pred = {(0, 2, "PER"), (5, 7, "LOC"), (9, 11, "LOC"), (13, 14, "ORG")}
rows = categorize(gold, pred)
for row in rows:
print(row)
print(dict(Counter(kind for _, _, kind in rows)))
tp = len(gold & pred)
precision = tp / len(pred)
recall = tp / len(gold)
f1 = 2 * precision * recall / (precision + recall) if tp else 0.0
print(f"strict P={precision:.2f} R={recall:.2f} F1={f1:.2f}")Running it prints:
((5, 7, 'ORG'), (5, 7, 'LOC'), 'type_error')
((9, 10, 'LOC'), (9, 11, 'LOC'), 'boundary_error')
((15, 16, 'PER'), None, 'missed')
(None, (13, 14, 'ORG'), 'spurious')
{'type_error': 1, 'boundary_error': 1, 'missed': 1, 'spurious': 1}
strict P=0.25 R=0.25 F1=0.25Strict F1 of 0.25 says the model is poor. The category counts say that the failures are evenly spread, so no single fix will cure the model.
Edge cases in the categorizer
The greedy pairing is simple, and it makes choices you should know about.
- Merged entities. If the model predicts one long span that covers two gold spans, the first gold span pairs with it as a boundary error. The second gold span finds no remaining overlap and is counted as missed. Merges therefore show up as a boundary error plus a miss.
- Split entities. If the model predicts two spans inside one gold span, one pairs as a boundary error and the other is spurious.
- Nested or overlapping gold spans. The scheme assumes flat annotation. Nested entities need a different matching procedure.
- Pairing order. When several predictions overlap one gold span, the first in sorted order wins. For a larger study you may prefer to choose the overlap with the largest intersection.
Your counts will depend slightly on these choices, so keep the same procedure when you compare two models.
Problems that look like model errors
Several tagger "errors" start in the data or in the pipeline, not in the model.
- Invalid BIO sequences. A model may emit
I-ORGright afterO. Decoders differ in how they repair this. Some treat it as the start of a span and some discard it. Check how your evaluator and your decoder treat it, because a different repair rule changes your span counts. - Tokenization and subword alignment. Transformer models predict on subwords. If you keep only the first subword's tag and a word is split differently from the gold tokenization, boundaries drift. A cluster of boundary errors near hyphens, apostrophes or URLs often points at the tokenizer.
- Guideline gaps. Whether "Dr. Smith" or "the University of Leeds" includes the title or the article is a guideline decision. If annotators disagree, the gold data contains boundary "errors" the model cannot learn. Read a sample of boundary errors against the guidelines before changing the model.
- Missing gold annotations. Many spurious predictions are real entities the annotators skipped. If a sample of spurious spans looks correct, your gold data is the problem. This ties back to the earlier chapter on label noise.
Reading the counts
After categorizing, read about 30 examples from each large category and write one line on why each happened. This is the same manual taxonomy step from earlier in the tutorial, now with a head start because the categories are fixed.
Use the counts to choose where to look first:
- Mostly missed spans point to recall problems: rare entities, out-of-vocabulary words, domain shift.
- Mostly spurious spans point to precision problems, or to missing gold annotations.
- Mostly boundary errors point to guidelines, tokenization or decoding.
- Mostly type errors point to missing context or ambiguous names.
Also compute these counts per slice, such as by sentence length or by whether the entity appears in the training set. As in earlier chapters, report the number of spans in each slice next to the rate, because small slices produce unstable rates.
Exercise
The gold set is {(0, 3, "ORG")} and the predicted set is {(0, 2, "ORG")}. Which category does the categorizer assign, and what does strict-match F1 equal?
Show answer
The spans overlap, the boundaries differ, and the types match, so it is a boundary error. No span matches exactly, so true positives are 0 and strict precision, recall and F1 are all 0.0. A relaxed overlap-based metric would give partial credit, but strict match gives none.
Exercise
A tagger reaches 96% token accuracy but only 0.60 entity-level F1. Give two reasons the two numbers can differ so much, and say what you would compute next.
Show answer
Most tokens are O, so correct O predictions inflate token accuracy. Also, one wrong token inside an entity makes the whole entity wrong under strict matching, so partial boundary mistakes cost an entity but only one token. Next, run the categorizer to count missed, spurious, boundary and type errors, and read a sample from the largest category.