Sub topic 14
Error analysis and choosing an approach
This chapter assumes you have trained or run at least one NER model from the earlier chapters. You should also know the entity-level precision, recall and F1 that seqeval reports. It covers what to do after you have a score: find where the model fails, and decide whether rules, a spaCy model or a fine-tuned transformer fits your task.
Why a single F1 is not enough
An entity-level F1 of 0.82 tells you how often the model is right. It does not tell you why it is wrong. Two models with the same F1 can fail in different ways, and each failure has a different fix. A model that cuts "Bank of America" down to "America" needs different treatment from one that never sees the entity at all.
Error analysis means reading the model's mistakes on a held-out set and sorting them into categories. Do it on the dev set, never the test set, so that your fixes do not leak into your final number.
A taxonomy of NER errors
Under strict entity-level matching, a predicted entity is correct only if its start, end and label all match a gold entity. Every other outcome falls into one of these categories.
| Error | Gold | Prediction | Typical cause |
|---|---|---|---|
| Missed entity | `Kiro` ORG | nothing | Rare or unseen name, lowercase text, domain shift |
| Spurious entity | nothing | `Monday` ORG | Overgeneralised pattern, noisy training labels |
| Wrong type | `Paris` GPE | `Paris` PERSON | Ambiguous name, little context |
| Boundary error | `Bank of America` ORG | `America` GPE | Inconsistent annotation, tokenization mismatch |
| Boundary and type | `New York Times` ORG | `New York` GPE | Both of the above |
A boundary error counts as one false positive and one false negative in strict scoring. It is therefore penalised twice. If most of your errors are boundary errors, check the annotation guidelines before you change the model.
Counting errors in code
The function below compares gold and predicted spans for one document. Spans are (start_char, end_char, label) tuples, which is what you get from doc.ents in spaCy and from the start, end and entity_group fields of the Hugging Face pipeline.
from collections import Counter
def categorize(gold, pred):
"""gold, pred: sets of (start, end, label) tuples for one document."""
counts = Counter()
used = set()
for g in gold:
if g in pred:
counts["correct"] += 1
used.add(g)
continue
overlaps = [p for p in pred if p[0] < g[1] and g[0] < p[1]]
if not overlaps:
counts["missed"] += 1
continue
used.update(overlaps)
p = overlaps[0]
same_span = (p[0], p[1]) == (g[0], g[1])
same_label = p[2] == g[2]
if same_span:
counts["wrong type"] += 1
elif same_label:
counts["boundary"] += 1
else:
counts["boundary and type"] += 1
for p in pred:
if p not in used:
counts["spurious"] += 1
return counts
gold = {(0, 12, "PERSON"), (24, 30, "GPE"), (40, 50, "ORG")}
pred = {(0, 12, "PERSON"), (24, 30, "LOC"), (40, 44, "ORG"), (60, 65, "ORG")}
print(dict(categorize(gold, pred)))This prints {'correct': 1, 'wrong type': 1, 'boundary': 1, 'spurious': 1}. To run it on a spaCy model, build the sets from the gold Doc and the predicted Doc:
def spans_of(doc):
return {(e.start_char, e.end_char, e.label_) for e in doc.ents}Sum the counters over the whole dev set. Then group by label as well, because a model can be strong on PERSON and weak on ORG. The overall proportions tell you where to look first.
Reading the examples
Counts only point you at a category. You still have to read the examples. For each category, print 20 to 30 errors with a few words of context on each side. Look for patterns such as:
- Errors cluster on one label or one source, for example product names or tweets.
- Missed entities are mostly lowercase, all caps or hyphenated.
- Spurious entities are mostly sentence-initial capitalised words.
- The gold label looks wrong, and the model is arguably right.
That last pattern is common. If the gold annotations are inconsistent, for example "Google" labelled ORG in one document and PRODUCT in another, no model can score well. You will gain more from fixing labels than from changing architecture.
Common causes and their fixes
| Symptom | Likely cause | First thing to try |
|---|---|---|
| Many missed entities in new text | Domain shift: the training data looks different from your data | Annotate a few hundred in-domain examples and fine-tune or retrain |
| Lowercase or all-caps text is missed | Cased models rely on capitalisation | Use a model trained on similar text, or add case-varied training examples |
| Many boundary errors | Inconsistent guidelines, or tokenization splits entities | Audit annotations, and check offsets with `doc.char_span` |
| `char_span` returns `None` during data prep | Annotation offsets do not align with tokens | Fix the offsets, or the tokenizer rules |
| Wrong type on ambiguous names | Little context, or classes that overlap | Merge labels, add context, or add more examples of the confusing cases |
| Fixed list of names is missed | Statistical model never saw them | Add an `EntityRuler` before `ner` |
| Fine-tuned model has worse recall than expected | Labels misaligned to subwords, or `-100` applied wrongly | Re-check `word_ids()` alignment on a few examples |
Many failures are data problems rather than model problems. Before you change the architecture, ask whether more or cleaner labelled data would fix the pattern you see.
Choosing an approach
You now have three families of tools. They are not mutually exclusive.
- Rules (
EntityRuler, or patterns onMatcher) are exact, explainable and need no training data. They work when entities come from a closed list or follow a strict format, such as product codes, ticker symbols or drug names from a lexicon. They cannot generalise to names they have not been given. - spaCy statistical models (
en_core_web_sm,md,lg, or a custom-trained model) are fast on CPU and easy to deploy. Training your own needs a few hundred to a few thousand annotated examples per label, depending on how hard the labels are. - Transformer models (
en_core_web_trf, or a fine-tuned Hugging Face model) usually score higher on ambiguous or context-dependent entities. They cost more per document, work best on a GPU at scale, and take more care to deploy.
| Criterion | Rules | spaCy CPU model | Transformer |
|---|---|---|---|
| Labelled data needed | None | Some | Some |
| Handles unseen names | No | Partly | Best |
| Uses context to disambiguate | No | Limited | Strong |
| Throughput and cost | Highest, lowest | High, low | Lower, higher |
| Explaining a single prediction | Easy | Hard | Hard |
| Behaviour when you change one case | Edit a pattern | Retrain | Retrain |
Combining approaches
The strongest systems often mix methods. A typical pattern is a statistical or transformer model for general entities, with an EntityRuler for names and formats you know exactly. Where you put the ruler matters:
before="ner"makes the rules win. The statistical model respects entities that are already set and does not overwrite them.after="ner"makes the model win. Rules can then fill gaps, but they can also overlap with existing entities. By default spaCy'sEntityRulerdoes not overwrite existing entities (overwrite_ents=False).
Pick the order from the error analysis. If the model keeps mislabelling known product names, put the rules first.
Practical decision criteria
Ask these questions in order:
- Do the pretrained labels match yours? If not, you must train or use rules. A model trained on
PERSON,ORGandGPEcannot outputGENEorCONTRACT_CLAUSE. - Is the entity set closed? If so, start with rules. They are a baseline you can build in an hour.
- How much labelled data do you have, and how consistent is it? Small or noisy data favours rules and a small spaCy model. Larger, clean data benefits more from a transformer.
- What are your latency and hardware limits? A transformer on CPU may be too slow for high-volume streams. Measure on your own data before you decide.
- How costly are errors? High-recall use cases such as redaction need a different threshold and review process from high-precision ones such as populating a database.
Gotchas to watch for
- Strict versus partial matching changes scores. Two papers or tools may report different F1 for the same predictions. Say which matching you use.
- Averaging matters. Micro-F1 is dominated by common labels. Macro-F1 gives rare labels equal weight. Report per-label scores.
- Aggregation can hide errors. With the Hugging Face pipeline,
aggregation_strategy="simple"merges subwords by label, so check how it handles entities where the model predicts different labels inside one span. - Confidence scores are not calibrated probabilities. Use them to rank errors for review, not as a literal chance of being right.
- Production text drifts. Re-run the error analysis on a fresh sample of real input every so often.
Exercise
A custom spaCy NER model has an overall F1 of 0.78. On the dev set, your error counts are: 40 missed, 12 spurious, 15 wrong type, and 95 boundary errors. Most of the boundary errors involve company names such as "Acme Corp" versus "Acme". What do you check first, and why does this not point to a bigger model?
Show answer
Check the annotation guidelines and the gold labels first. If some documents label "Acme Corp" and others label "Acme", the training signal is inconsistent, and a bigger model cannot learn a consistent boundary from contradictory examples. Also confirm that offsets align with token boundaries, because misaligned spans from doc.char_span are silently dropped. Fix and normalise the annotations, then retrain and re-measure. Boundary errors count twice under strict matching, so this is also the fix most likely to raise F1.
Exercise
You need to find a fixed list of 300 internal product names in support tickets, and also find person names in the same text. Which approach would you choose?
Show answer
Use a combination. A pretrained spaCy model (or a transformer) handles PERSON, and an EntityRuler placed before ner handles the 300 product names, since that list is closed and exact patterns are reliable and need no training data. Evaluate each label separately on a dev set, and add training data only if the error analysis shows the rules miss variants such as misspellings.