Sub topic 13
Evaluating NER with entity-level metrics
This chapter assumes you can run the spaCy and Hugging Face examples from earlier chapters. It also assumes you know BIO tags and the definitions of precision, recall and F1 for a binary classifier. You will learn why NER is scored on whole entities instead of tokens, how to compute those scores with seqeval and spaCy, and how to read the numbers.
Why token accuracy misleads
An NER model outputs one tag per token. The obvious score is the share of tokens tagged correctly. That score is inflated, because most tokens in real text are O (outside any entity). A model that predicts O everywhere can reach 85–90% token accuracy on typical news text and find no entities.
Token accuracy also ignores what the task needs. An application usually needs a complete span with the right label, such as "Bank of America" as ORG. Getting two of the three tokens right yields a wrong entity, even though two of three tokens are correct.
Entity-level evaluation fixes both problems. It compares whole entities and counts one as correct only when it matches a gold entity exactly. Both the span boundaries and the label must match.
True positives, false positives and false negatives for spans
Convert the gold tags and the predicted tags into sets of entities. Each entity is a triple of label, start and end. Then compare the sets.
- A true positive (TP) is a predicted entity that also appears in the gold set.
- A false positive (FP) is a predicted entity that is not in the gold set.
- A false negative (FN) is a gold entity that the model did not predict.
The formulas are the usual ones:
- Precision = TP / (TP + FP). Of the entities the model predicted, how many were right.
- Recall = TP / (TP + FN). Of the real entities, how many the model found.
- F1 = 2 · P · R / (P + R). The harmonic mean of the two.
How each kind of error is counted
Strict matching makes some errors cost double. A prediction with the right type but a shifted boundary is both a false positive (the wrong span) and a false negative (the missed gold span).
| Situation | Gold | Predicted | Counted as |
|---|---|---|---|
| Exact match | ORG "Bank of America" | ORG "Bank of America" | 1 TP |
| Boundary error | ORG "Bank of America" | ORG "Bank of" | 1 FP and 1 FN |
| Type error | ORG "Jordan" | LOC "Jordan" | 1 FP and 1 FN |
| Missed entity | PER "Ada" | nothing | 1 FN |
| Spurious entity | nothing | PER "Monday" | 1 FP |
Because of this double count, strict F1 is a harsh score. It is still the standard, because it matches how entities are used downstream, for example when you link them to a database or index them.
Computing entity-level scores with seqeval
seqeval implements the CoNLL-style evaluation on lists of BIO tag sequences. Install it with pip install seqeval. Each sequence is one sentence, and the predictions must use the same tokenization as the gold tags.
from seqeval.metrics import accuracy_score, f1_score, precision_score, recall_score
y_true = [["B-ORG", "I-ORG", "I-ORG", "O", "B-PER"]]
y_pred = [["B-ORG", "I-ORG", "O", "O", "B-PER"]]
print("token accuracy:", accuracy_score(y_true, y_pred))
print("precision:", precision_score(y_true, y_pred))
print("recall:", recall_score(y_true, y_pred))
print("entity F1:", f1_score(y_true, y_pred))Token accuracy is 0.8, since four of five tags are right. The model found two entities, and the three-token ORG has the wrong end. So there is one true positive (PER), one false positive (the truncated ORG) and one false negative (the full ORG). Precision, recall and F1 are all 0.5. The gap between 0.8 and 0.5 is the reason to use entity-level scoring.
The example from the chapter plan shows a missed entity:
from seqeval.metrics import classification_report, f1_score
y_true = [["B-PER", "I-PER", "O", "B-LOC"]]
y_pred = [["B-PER", "I-PER", "O", "O"]]
print(f1_score(y_true, y_pred))
print(classification_report(y_true, y_pred))The PER entity matches, and the LOC entity is missed. Precision is 1.0, recall is 0.5, and F1 is about 0.667. The report lists precision, recall, F1 and support (the number of gold entities) for each label, followed by averages. seqeval may print a warning that LOC precision is ill-defined, because the model predicted no LOC entities. It reports 0.0 for that case.
Micro, macro and weighted averages
The overall number depends on how you average across entity types.
- Micro average pools all entities from all types, then computes one P, R and F1. Frequent types dominate. This is the headline score in most NER papers and in seqeval's default
f1_score. - Macro average computes F1 per type and takes the unweighted mean. A rare type counts as much as a common one, so it exposes weak performance on small classes. Use
average="macro". - Weighted average takes the mean per-type F1 weighted by support. It lies between the two.
If your data has 5,000 PER entities and 50 PRODUCT entities, a micro F1 of 0.92 can hide a PRODUCT F1 of 0.40. Always look at the per-type rows before you trust one summary number.
Evaluating a spaCy pipeline
spaCy evaluates on Example objects. Each one pairs a predicted Doc with a reference annotation, and the reference spans are given as character offsets. The Language.evaluate method returns a dictionary of scores.
import spacy
from spacy.training import Example
nlp = spacy.load("en_core_web_sm")
text = "Apple is looking at buying a U.K. startup for $1 billion."
annotations = {"entities": [(0, 5, "ORG"), (29, 33, "GPE"), (46, 56, "MONEY")]}
examples = [Example.from_dict(nlp.make_doc(text), annotations)]
scores = nlp.evaluate(examples)
print("precision:", scores["ents_p"])
print("recall:", scores["ents_r"])
print("F1:", scores["ents_f"])
print(scores["ents_per_type"])The keys ents_p, ents_r and ents_f are micro-averaged, and ents_per_type holds precision, recall and F1 for each label. One sentence only demonstrates the API. A meaningful score needs hundreds or thousands of held-out sentences.
For a trained model on disk, the command line does the same work on a .spacy file:
python -m spacy evaluate ./output/model-best ./dev.spacyDuring spacy train, the score printed each evaluation step is the entity F1 on the dev set. The pipeline keeps model-best, the checkpoint with the best weighted score, and model-last. Evaluate model-best on a separate test set to get a fair final number.
Evaluating a Hugging Face model
A fine-tuned token-classification model predicts one label per subword token. Before scoring, you must map predictions back to word-level tags. Take the prediction at each word's first subword and skip positions labelled -100. This is the same rule you used when aligning labels for training. Then convert label ids to tag strings and pass the lists to seqeval.
Two mistakes recur here. Scoring subword-level predictions against word-level gold tags gives lists of different lengths. Scoring with the -100 positions left in makes seqeval treat them as tags. Filter both lists with the same mask.
Reading the numbers: what to check beyond F1
A single F1 tells you the model is good or bad, not why. Use these checks to find out why.
- Compare precision and recall. High precision with low recall means a conservative model that misses entities. The reverse means over-prediction. The fixes differ. Conservative models often need more training examples or rules. Over-predicting models often need cleaner negative examples.
- Count boundary errors apart from type errors. Compute a relaxed score where any overlap with the right label counts. If relaxed F1 is far above strict F1, boundaries are the problem, and your annotation guidelines may be inconsistent.
- Build a confusion table of gold label against predicted label, with a row for "not an entity". Frequent
ORG/GPEswaps point to ambiguous entity types. - Inspect examples. Sort errors by frequency and read thirty of them. Patterns such as titles, hyphenated names or all-caps headings appear quickly.
- Slice by source. Score by document type, length or domain. A model trained on news text may score 0.90 on news and 0.65 on social media.
Common pitfalls
- Tokenization mismatch. spaCy and seqeval must see the same tokens as the gold data. If you re-tokenize, spans shift and scores drop for reasons unrelated to the model.
- Comparing across datasets. F1 on CoNLL-2003 and F1 on your own corpus are not comparable. Label sets, annotation rules and text domains differ.
- Small test sets. With 100 gold entities, one entity changes recall by one point. Report the support next to each score, and for small sets prefer a confidence interval from bootstrap resampling.
- Ignoring annotation noise. Gold labels have errors too. A model that looks wrong on a sample may be right. Check the labels before blaming the model.
- Different match rules. A paper reporting "partial match" F1 and your strict F1 measure different things. Name the rule when you quote a number.
Exercise
A gold sentence has these entities: PER "Marie Curie", ORG "Sorbonne", LOC "Paris". The model predicts PER "Curie", ORG "Sorbonne", and LOC "Paris" but also predicts ORG "Monday". Compute strict precision, recall and F1.
Show answer
Matches: ORG "Sorbonne" and LOC "Paris", so TP = 2. The prediction PER "Curie" has the wrong boundary, and ORG "Monday" is spurious, so FP = 2. The gold PER "Marie Curie" was not matched, so FN = 1. Precision = 2/4 = 0.5. Recall = 2/3 ≈ 0.667. F1 = 2 · 0.5 · 0.667 / (0.5 + 0.667) ≈ 0.571.
Exercise
A model scores micro F1 0.93 on a test set where 95% of gold entities are PER or ORG. A colleague says the model is ready for a product that depends on a rare PRODUCT label. What should you check first, and why?
Show answer
Check the per-type results for PRODUCT, and its macro-averaged F1. Micro averaging pools entities across types, so the two frequent types dominate and the 0.93 can hide a very low PRODUCT F1. Also look at the PRODUCT support, because a handful of examples makes the score unreliable.