What counts as an entity is a product decision
Named entity recognition sounds like a fixed task until you specify the inventory. Person, organization, and location cover the classic three, but a clinical system needs dosage, procedure, and diagnosis; a finance system needs ticker, currency, and filing type; an e-commerce system needs product model and brand. The moment the inventory is chosen, so is the annotation guideline, and two teams given the same corpus will disagree on whether Apple Park is one organization span or whether Apple is the organization and Park is a location. Inter-annotator agreement on entity boundaries routinely sits in the low nineties even for well-funded projects, and every point of disagreement there becomes an unreachable ceiling on model F1.
Beyond boundaries there is a second design question: flat or nested. Flat tagging assumes entities never overlap, which holds for simple news pipelines and fails for biomedical text where a protein name sits inside a disease name sits inside a sentence describing a study. Choosing flat BIO is a genuine simplification that buys mature tooling and costs you the ability to express real structure.
A third question is whether to tag at all, or to detect-and-normalise jointly. Tagging followed by linking gives you two systems to evaluate and two places for error to accumulate; joint models remove the seam but couple your annotation effort to a specific knowledge base. Most teams are better served by the two-stage version first, because it lets you measure tagging quality independently of any linking decisions.
This lesson covers the tagging schemes, reconstructs spans from tag sequences, and compares a feature-based CRF with a transformer classifier, then turns to the evaluation trap that makes most reported NER numbers unreliable.
The BIO family of tagging schemes
The encoding you choose determines what the model can express at all. BIO is the baseline; its variants exist to solve specific boundary problems that BIO cannot represent.
| Scheme | Tags | Expresses | Fails on |
|---|---|---|---|
| Plain labels | PER, ORG, LOC | One tag per token | Multi-token boundaries |
| BIO | B-PER, I-PER, O | Start versus continuation | Two adjacent same-type entities |
| BIOES / BILOU | B, I, E, S, L | Start, inside, end, single | Nothing basic; adds clarity |
| BIOHD | B, I, O, H, D | Head and discontinuous parts | Rarely supported by tooling |
| BMES | Begin, Middle, End, Single | Chinese word segmentation style | Same as BIOES |
| Nested layers | Multiple tag rows per token | Overlapping entities | Needs a structured decoder |
The B versus I distinction is what resolves adjacency. Without it, John Smith Mary Johnson would be a single undifferentiated person span, because nothing in a plain PER, PER, PER, PER sequence says where one person ends and the next begins. BIOES adds an explicit single-token tag, which removes the ambiguity between a one-token entity and the start of a longer one and measurably helps sequence decoders.
Reconstructing spans from tags
Tagging is a per-token problem, but evaluation and downstream use are span problems. Converting between them is short code and the most common source of subtle NER bugs: off-by-one boundaries, dropped trailing entities, and entities lost because a subword tokenizer split them across predictions.
from collections import Counter
def bio_to_spans(tokens, tags):
spans, cur, start = [], None, None
for i, (tok, tag) in enumerate(zip(tokens, tags)):
if tag.startswith("B-"):
if cur is not None:
spans.append((cur, start, i - 1))
cur, start = tag[2:], i
elif tag.startswith("I-") and cur is not None and tag[2:] == cur:
continue
else:
if cur is not None:
spans.append((cur, start, i - 1))
cur, start = None, None
if cur is not None:
spans.append((cur, start, len(tokens) - 1))
return spans
tokens = ["John", "Smith", "works", "at", "Acme", "Corp", "in", "Berlin"]
tags = ["B-PER", "I-PER", "O", "O", "B-ORG", "I-ORG", "O", "B-LOC"]
print(bio_to_spans(tokens, tags))
# [('PER', 0, 1), ('ORG', 4, 5), ('LOC', 7, 7)]
def spans_to_bio(spans, n):
tags = ["O"] * n
for label, a, b in spans:
tags[a] = f"B-{label}"
for i in range(a + 1, b + 1):
tags[i] = f"I-{label}"
return tags
print(spans_to_bio([("PER", 0, 1), ("LOC", 7, 7)], len(tokens)))
Note the inconsistency guard: an I-PER following an O is malformed input, and the function above closes the current span rather than silently merging across the gap. Decoders that skip this check produce entities spanning half a sentence.
Feature-based sequence models
Before transformers, the standard approach paired hand-engineered features with a conditional random field, which scores the whole tag sequence rather than each token independently. That joint scoring is the essential contribution: it enforces constraints such as I-PER never following O, which a per-token classifier violates freely.
def word_features(tokens, i):
w = tokens[i]
feats = {
"bias": 1.0,
"w.lower": w.lower(),
"w.isupper": w.isupper(),
"w.istitle": w.istitle(),
"w.isdigit": w.isdigit(),
"w.suffix3": w[-3:].lower(),
}
if i > 0:
feats["prev.w"] = tokens[i - 1].lower()
feats["prev.istitle"] = tokens[i - 1].istitle()
if i < len(tokens) - 1:
feats["next.w"] = tokens[i + 1].lower()
feats["next.isupper"] = tokens[i + 1].isupper()
return feats
def sent_features(tokens):
return [word_features(tokens, i) for i in range(len(tokens))]
# With sklearn-crfsuite:
# model.fit(sent_features(train_tokens), train_tags)
# pred = model.predict(sent_features(test_tokens))
The istitle and suffix features do most of the heavy lifting in English news text, because capitalisation and morphology are strong entity priors. They also explain why the same model collapses on all-lowercase social media input, where those cues vanish entirely.
Transformers and their confidence behaviour
Modern NER uses a token classifier over a pretrained encoder, usually with subword tokenization. Two behaviours catch teams out. First, the model predicts one label per subword, so Hawthorne split into Haw and thorne yields two predictions that must be aligned back to the original word, and ignoring the alignment silently corrupts metrics. Second, confidence scores near the boundary are systematically lower than in the middle of a span, which is useful signal â aggregating probabilities across a span rather than taking the minimum gives better-calibrated entity scores.
from transformers import pipeline
ner = pipeline("ner", aggregation_strategy="simple", device=-1)
text = "Elon Musk founded SpaceX in Hawthorne, California in 2002."
for ent in ner(text):
print(f"{ent['entity_group']:<6} {ent['score']:.3f} {ent['word']} [{ent['start']}:{ent['end']}]")
# Raw subword output, showing the alignment problem:
raw = pipeline("ner", aggregation_strategy="none", device=-1)
for ent in raw(text):
print(ent["word"], ent["entity"], round(ent["score"], 3))
Comparing the two outputs side by side makes the alignment issue concrete: Elon and ##Musk each carry their own tag and score, and only aggregation produces the span you want to store.
Difficult cases you will meet in production
| Case | Example | Handling |
|---|---|---|
| Ambiguous surface form | Washington person or state | Context window, or accept both with scores |
| Nested entities | New York City Police Department | Layered tagging or a span classifier |
| Discontinuity | New York and Chicago offices | Special tags or post-processing merge |
| Nested subwords | Subword pieces of one entity | Align to word spans before scoring |
| Novel entities | A brand launched yesterday | Subword coverage, then human review loop |
| Domain vocabulary | Gene and drug names | Domain pretraining or lexicon features |
Flat BIO cannot represent the nested case at all, which is why biomedical pipelines often use a two-layer scheme â one BIO row for chemicals, one for diseases â and decode each layer separately before merging overlaps.
Evaluating with span-level F1
Token accuracy is meaningless for NER because the O class dominates: a model that predicts O everywhere scores well above 90 percent accuracy on typical news data while detecting nothing. The correct metric is span-level exact-match F1, where a prediction counts only if the boundary and the type both match.
def span_f1(gold, pred):
gold, pred = set(gold), set(pred)
tp = len(gold & pred)
fp, fn = len(pred - gold), len(gold - pred)
p = tp / (tp + fp) if tp + fp else 0.0
r = tp / (tp + fn) if tp + fn else 0.0
f = 2 * p * r / (p + r) if p + r else 0.0
return p, r, f
gold = [("PER", 0, 1), ("ORG", 4, 5), ("LOC", 7, 7)]
pred = [("PER", 0, 1), ("ORG", 4, 6), ("LOC", 7, 7)]
print("P/R/F1:", [round(x, 3) for x in span_f1(gold, pred)])
# partial boundary overlap scores zero, which is the intended behaviour
That strictness is deliberate. A system that gets the type right but the boundary wrong will retrieve a record you cannot match against a database key, so relaxing the criterion hides exactly the failure you need to see. For error analysis, partition the misses into type errors, boundary errors, and missed detections â the three have completely different fixes.
đĄMeasure agreement before blaming the model
Common Mistakes
Reporting token accuracy for an NER system
Fix: Use span-level exact-match F1; the dominant O class makes accuracy look excellent while recall is near zero.
Ignoring subword-to-word alignment when scoring a transformer tagger
Fix: Aggregate subword predictions back onto original word spans before computing any metric.
Shipping a model with an inventory the annotation guidelines never pinned down
Fix: Resolve boundary and type ambiguity with a written guideline and a measured inter-annotator agreement first.
Using flat BIO on data with genuinely nested entities
Fix: Either adopt layered tagging or a span-classification head, or document the truncation as an accepted loss.
Best Practices
- Write the entity inventory and boundary rules before collecting labels, then measure agreement against them
- Prefer BIOES over BIO when the decoder supports it, since explicit single-token tags remove ambiguity
- Store entity spans with offsets rather than strings, so text edits cannot silently invalidate annotations
- Keep a small frozen test set of hard cases â ambiguity, nesting, new entities â and review its errors every release
Interview Questions
Q1: Why is token accuracy useless for NER?
The outside class dominates, so predicting O for every token yields over 90 percent accuracy while the model detects no entities at all.
Q2: What problem does the B- tag solve that a plain entity tag cannot?
It marks the start of a new entity, so two adjacent entities of the same type are separated instead of merging into one long span.
Q3: How do you evaluate a transformer NER model that predicts on subwords?
Map subword predictions back to word spans first, then compute span-level exact-match precision, recall, and F1 on those word-level spans.
Key Takeaways
- The entity inventory and boundary guideline define the task; disagreement there caps achievable F1
- BIO encodes starts and continuations, BIOES additionally encodes single-token entities
- Span reconstruction is where most implementation bugs hide, especially around malformed tag sequences
- CRFs score whole sequences and enforce tag transitions; transformers need explicit subword alignment
- Span-level exact-match F1 is the only defensible headline metric, with errors split by type, boundary, and miss