Named Entity Recognition
Prerequisites
- !Sequence models and the idea of a transition
- !Token classification with a transformer backbone
- !Precision and recall on spans rather than documents
What You'll Learn
- 1Resolve the annotation decisions that make or break an NER dataset
- 2Explain why BIO encoding exists and decode tag sequences with Viterbi
- 3Align word-level labels onto subword tokens without silently corrupting them
- 4Evaluate entities by exact span match and interpret where the model loses points
What counts as an entity is an annotation decision
Point a general model at a contract and ask it to mark organizations, and it will highlight "the Board", "the Committee of Creditors", and "the Buyer's affiliates" with equal enthusiasm â three things your downstream system cannot use identically. Entity recognition starts with a type list and a boundary rule, and both must be written down.
Four decisions cause almost all annotator disagreement. Boundary: does "Bank of America Corporation" include the trailing legal suffix? Nested entities: when "New York University" contains both a location and an organization, does the guideline keep both or keep the outer one? Implicit mentions: is "the White House" an organization or a location when it means the administration? Annotator scope: should an unlisted type be marked as OTHER or left untouched? Each answer changes the model you can train.
Because annotation disagreements concentrate at boundaries, a quick audit is to double-annotate fifty sentences and measure exact-span agreement separately from type agreement. If boundaries agree but types do not, fix the type definitions. If boundaries do not, tighten the rules with examples â models trained on fuzzy boundaries learn fuzzy boundaries, and no architecture change compensates.
BIO, BILOU and the reason encoding exists
A sequence labeler cannot emit arbitrary text; it emits one tag per token. The encoding encodes where entities start and continue, and the scheme you choose changes how much structure the decoder must learn.
| Scheme | Tags per entity | Example for "Sarah Connor" | Notes |
|---|---|---|---|
| BIO | 2 or 3 | B-PER I-PER | Minimum viable encoding |
| BILOU | 4 | B-PER L-PER | Marks single-token entities explicitly |
| BIOES | 4 | B-PER E-PER | Same idea, different letter names |
| Plain type | 1 | PER PER | Cannot express boundaries at all |
The distinction is not cosmetic. Under plain type tagging, "Sarah Connor in Paris" would label three consecutive tokens as PER, PER, PER with nothing separating the person from the place; the decoder has to infer a boundary it was never shown. BIO gives it an explicit B- signal. The practical difference between BIO and BILOU is smaller but real: BILOU removes the ambiguity between a one-token entity and the continuation of a longer one, which measurably improves boundary F1 on datasets with many short entities.
A Viterbi decoder that respects transitions
A linear-chain CRF scores whole tag sequences, not tokens independently, and that is its advantage: I-PER after O is impossible, and a tagger that scores tokens alone will happily emit it. The Viterbi algorithm finds the best path under those constraints.
import numpy as np
def viterbi_decode(emissions: np.ndarray, transitions: np.ndarray,
start: np.ndarray, allowed_starts: set[int]):
"""emissions: (T, K) per-token scores. transitions: (K, K) from i to j."""
T, K = emissions.shape
score = np.full(K, -1e9)
for k in allowed_starts:
score[k] = start[k] + emissions[0, k]
back = np.zeros((T, K), dtype=int)
for t in range(1, T):
cand = score[:, None] + transitions # cand[i, j]
back[t] = cand.argmax(axis=0)
score = cand.max(axis=0) + emissions[t]
path = [int(score.argmax())]
for t in range(T - 1, 0, -1):
path.append(int(back[t][path[-1]]))
path.reverse()
return path
def assert_valid_bio(path: list[int], tag_names: list[str]) -> None:
"""No I-X token may follow O or a different entity type."""
prev = "O"
for idx in path:
tag = tag_names[idx]
if tag.startswith("I-") and (prev == "O" or prev[2:] != tag[2:]):
raise ValueError(f"illegal transition {prev} -> {tag}")
prev = tag
The transition matrix encodes the grammar: rows are the previous tag, columns the next, and impossible pairs receive a large negative score so no optimal path can use them. In practice the transition weights are learned alongside the emission scores during CRF training, which is why a CRF head beats an independent softmax head even on a strong transformer â the head learns that your data almost never starts an entity with I-.
Subword alignment: the bug that quietly costs points
Transformers tokenize words into subwords, but labels are usually written per word. Naively copying the word label onto every subword inflates metrics and confuses training, because a five-subword organization gets five chances to be right while a one-subword person gets one.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
LABELS = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
label2id = {l: i for i, l in enumerate(LABELS)}
def align_words_to_subwords(words: list[str], word_labels: list[str],
max_length: int = 128):
ids, aligned = [], []
for w, lab in zip(words, word_labels):
sub = tokenizer.encode(w, add_special_tokens=False)
for j, s in enumerate(sub):
ids.append(s)
# First subword keeps the tag; continuations get I- (or -100).
if lab.startswith("B-") and j > 0:
aligned.append(label2id["I-" + lab[2:]])
elif lab == "O" and j > 0:
aligned.append(-100) # ignore continuation of O words
else:
aligned.append(label2id[lab])
ids = ids[:max_length - 2]
aligned = aligned[:max_length - 2]
# Special tokens contribute no loss.
aligned = [-100] + aligned + [-100]
ids = [tokenizer.cls_token_id] + ids + [tokenizer.sep_token_id]
return ids, aligned
Two conventions are defensible: label only the first subword and mask the rest with -100, or propagate B- into I- for continuations as above. What is not defensible is treating every subword as an independent gold entity â evaluation then measures tokenization rather than understanding. Whatever you choose, decode back to word level before scoring, because the user asked about words.
Fine-tuning the tagger
Architecture selection is straightforward once the data is clean. A transformer encoder with a token-classification head, trained with cross-entropy and optionally a CRF on top, handles flat entity types well; start from a cased model if casing carries signal, since "Jordan" and "jordan" are different hypotheses. Class imbalance is severe â O is typically 80â95% of tokens â so either downsample O tokens or use a weighted loss, and always monitor per-type F1 rather than token accuracy, which stays above 0.95 even for a useless model.
Long documents need a windowing strategy: slide a window with overlap and merge predictions, keeping the higher-scoring span when windows disagree. Evaluate with document-level deduplication, since duplicated spans from overlapping windows otherwise inflate recall.
Evaluation that matches how the output is used
Token-level accuracy flatters every model. Entity-level exact match tells the truth: a prediction counts only if start, end and type all match.
| Metric | Counts a match when | Fails to catch |
|---|---|---|
| Token accuracy | Individual tag correct | Boundary and type errors |
| Exact span F1 | Start, end and type identical | Off-by-one partial credit |
| Partial span F1 | Overlap above a threshold | Wrong but overlapping types |
| Type-strict span F1 | Span and type both correct | Normalization errors |
| Normalized F1 | Mention links to the right ID | Linker and resolver bugs |
Report exact span F1 as the headline and partial overlap as a diagnostic: a gap between them means boundaries are the problem, while a gap between per-type F1 and overall F1 points at a rare type with too few examples. For downstream use, measure the metric the consumer feels â a billing pipeline extracting account numbers needs exact matches on B-ACCOUNT, not a good micro-average.
Normalization, gazetteers and the last mile
Raw spans are rarely what systems consume. Post-processing converts them into identifiers: strip legal suffixes consistently, resolve "IBM" and "International Business Machines" to one canonical ID, and use a gazetteer as a precision floor for high-value, enumerable types like currencies, countries, and product codes. Gazetteers must never be the only source of recall, though â they cannot name the next startup â so the usual pattern is model proposes, gazetteer validates, resolver links. Log every span the model emitted but the resolver rejected; that log is the cheapest source of new training data you will find.
Common Mistakes
Copying a word label onto all of its subwords without a rule
Fix: Label only the first subword or propagate B- to I-, mask the rest with -100, and decode to words before scoring
Reporting token accuracy as NER performance
Fix: Score exact span F1 per type and keep token accuracy as a debugging signal only
Leaving boundary and nesting rules in annotators' heads
Fix: Write explicit rules with near-miss examples and measure inter-annotator span agreement first
Merging overlapping window predictions naively
Fix: Deduplicate spans across windows and keep the higher-scoring one before evaluation
Best Practices
- Choose BIO versus BILOU based on your single-token entity rate, then stay consistent
- Keep the CRF transition matrix or its equivalent constraints â illegal paths should be impossible, not merely unlikely
- Score per entity type; rare types are where macro and micro averages disagree
- Use gazetteers to validate precision and to harvest hard negatives for the next training round
- Version the annotation guideline with the dataset so results stay reproducible
Key Takeaways
- NER quality is set early by boundary, nesting and type decisions written into the guideline
- BIO-style encoding exists so the decoder can see where entities begin; BILOU adds explicit single-token markers
- A Viterbi or CRF head enforces legal tag paths, which independent per-token softmax cannot do
- Subword alignment needs a documented rule â otherwise metrics measure tokenization, not recognition
- Evaluate with exact span F1 per type, and treat the model-resolver rejection log as free training data