Named-Entity Recognition
Consider the sentence "Marie Curie won the Nobel Prize in Stockholm in 1911." A human reader instantly picks out a person, an award, a place, and a date without effort. Teaching a machine to do the same is harder. It must find spans of text and assign each a category like PERSON, ORGANIZATION, or LOCATION. This is the task of named-entity recognition (NER). It sits at the foundation of nearly every information-extraction pipeline. Search engines use it to populate knowledge panels. Financial systems use it to flag company names in filings. Clinical NLP systems use it to pull drug names and dosages out of doctor's notes. NER looks deceptively similar to Part-of-Speech Tagging: both assign a label to every token in a sentence. But NER has a structural wrinkle that POS tagging does not. Entities can span multiple tokens ("New York City" is one entity, not three). The tagger must decide not just what a token is. It must also decide where an entity begins and ends. This chapter shows how to reduce span identification to per-token classification. It uses the BIO (Begin-Inside-Outside) encoding scheme. It then shows how to solve the resulting sequence-labeling problem with the same machinery used for POS tagging. Most notably, this means the The Viterbi Algorithm applied to a linear-chain Conditional Random Field (CRF) or Hidden Markov Model (HMM). The big picture is this: NER converts a segmentation problem into a labeling problem. The segmentation problem is finding the boundaries of entity mentions. The labeling problem is assigning one tag per token. It solves this via a clever encoding, then applies standard sequence models. This move — encode structure into labels, then apply generic sequence inference — is one of the most reusable ideas in NLP. It reappears in chunking, semantic role labeling, and even some formulations of Dependency Parsing. This article builds NER from the ground up. It covers the BIO tagging scheme and why it is necessary. It covers the features and model classes (HMM, MEMM, CRF) used to score tag sequences. It covers the Viterbi decoding algorithm that finds the best sequence efficiently. It also covers the evaluation metrics that make NER performance comparable across systems. We verify every complexity claim. We walk through a full numeric trace so that the mechanics are never left abstract.
- NER identifies spans of text (entities) and assigns each a type: PERSON, ORG, LOC, DATE, MISC, etc.
- The BIO scheme (B-egin, I-nside, O-utside) converts span detection into per-token classification.
- A linear-chain CRF (or HMM) scores whole tag sequences; The Viterbi Algorithm finds the best one in polynomial time.
- Features like word shape, prefixes/suffixes, gazetteers, and context words drive classical (non-neural) NER.
- Evaluation is span-based (exact match of boundary + type), scored with entity-level precision, recall, F1.
- NER is a stepping stone toward richer structure prediction such as Dependency Parsing and relation extraction.
Named-entity recognition turns "find the spans" into "label every token," using BIO tags so that standard sequence-labeling algorithms — the same Viterbi decoder used for POS tagging — can recover entity boundaries and types simultaneously.
The idea
A named entity is a real-world object referred to by a proper name: people, organizations, locations, dates, monetary amounts, and similar categories agreed upon by an annotation scheme (common sets include the four-type CoNLL-2003 scheme — PER, ORG, LOC, MISC — and richer schemes like OntoNotes with 18 types). Named-entity recognition is the task of finding every entity mention in a text, marking its exact token span, and assigning it a type label. The central difficulty is that entities have variable length. If we treated NER as ordinary classification — one label per token drawn from {PER, ORG, LOC, O} — we could not distinguish "New York" as a single two-token entity from "New" and "York" appearing as two separate one-token entities. The fix is the BIO tagging scheme:
- B-TYPE: this token begins an entity of type TYPE.
- I-TYPE: this token continues (is inside) an entity of type TYPE, immediately following a B-TYPE or another I-TYPE of the same type.
- O: this token is outside any entity.
So "Marie Curie won the Nobel Prize in Stockholm" becomes: ``` Marie B-PER Curie I-PER won O the O Nobel B-MISC Prize I-MISC in O Stockholm B-LOC ``` With entity types, the BIO scheme produces possible tags: one B-tag and one I-tag per type, plus the single O tag. Every span-detection problem is now an ordinary sequence-labeling problem over this enlarged tag set — precisely the same shape of problem as POS tagging, which means the same inference algorithms apply. (Variants exist — BIOES adds End and Single tags for tighter boundary modeling, and IOB2 vs IOB1 differ in whether B is mandatory at every entity start — but BIO is the canonical, most widely taught scheme.)
How it works
From tokens to tag sequences
Given a sentence , an NER system must produce a tag sequence over the BIO tag set. This is scored by a probabilistic sequence model. Two classical families dominate: 1. Hidden Markov Model (HMM) — generative, defines . 2. Linear-chain Conditional Random Field (CRF) — discriminative, defines
where are arbitrary feature functions (word identity, capitalization, prefixes/suffixes, gazetteer membership, POS tag, previous tag) and is the normalizing partition function. The CRF is preferred in practice because it can use overlapping, non-independent features of the whole observed sentence without violating any conditional-independence assumption — a freedom generative HMMs do not have. Both models factor the sequence score into a sum of local terms that depend only on adjacent tag pairs and the observation sequence. This local factorization is exactly what makes efficient dynamic programming possible.
Decoding: Viterbi over BIO tags
Given trained weights, the system must find
Because the score decomposes into a sum over adjacent-tag terms, this maximization is solved by The Viterbi Algorithm, exactly as in POS tagging — the only difference is that the tag alphabet is now the BIO set and certain transitions must be forbidden. A crucial detail specific to NER: not every BIO transition is valid. An I-LOC tag cannot legally follow an O tag or a B-PER tag — it can only follow B-LOC or I-LOC (of the same type). Enforcing these hard constraints (by setting their transition score to , or by structurally excluding them from the trellis) prevents the decoder from ever outputting an ill-formed tag sequence such as "O I-LOC," which would be nonsensical (an "inside" continuation with no beginning). ``` Algorithm: BIO-constrained Viterbi decoding for NER Input: sentence w[1..n] tag set T = {O} ∪ {B-c, I-c : c in entity types} transition score function trans(t_prev, t_curr) // -inf if illegal emission/local score function emit(t, w, i) // feature-weighted score at position i Output: highest-scoring tag sequence t[1..n] 1. // δ[i][t] = best score of any tag sequence for w[1..i] ending in tag t // ψ[i][t] = backpointer: the tag at position i-1 that achieves this best score for each tag t in T: δ[1][t] = emit(t, w, 1) + trans(START, t) ψ[1][t] = START 2. for i = 2 to n: for each tag t in T: best_prev, best_score = None, -infinity for each tag t_prev in T: s = δ[i-1][t_prev] + trans(t_prev, t) + emit(t, w, i) if s > best_score: best_score, best_prev = s, t_prev δ[i][t] = best_score ψ[i][t] = best_prev 3. // termination t[n] = argmax_t ( δ[n][t] + trans(t, END) ) 4. // backtrace for i = n-1 down to 1: t[i] = ψ[i+1][t[i+1]] 5. return t[1..n] ``` After decoding, a post-processing step reads the BIO sequence and emits entity spans: scan left to right, open a new span at each B-TYPE, extend it through following I-TYPE tokens of the same type, and close it the moment an O, a new B, or an I of a different type appears.
Training
For a CRF, training maximizes the conditional log-likelihood of the gold tag sequences over the training corpus via gradient-based optimization (e.g., L-BFGS or stochastic gradient descent). The gradient of the log-likelihood with respect to feature weight has the classic form
the difference between observed feature counts and their expectation under the model. This expectation is computed efficiently with the forward-backward algorithm, the same dynamic-programming trellis structure underlying Viterbi, just replacing max with sum.
Complexity & correctness
Time complexity of decoding. With tokens and tags, the Viterbi recurrence fills an table, and computing each cell requires examining all predecessor tags, giving time. With BIO's tags, this is — quadratic in the number of entity types but linear in sentence length, which is what makes the algorithm practical even for corpora with dozens of entity types. Space is for the and tables (or if only the final tag sequence is needed via online recomputation, though the standard implementation keeps the full table for backtracing).
Why Viterbi is correct here. The argument is the same optimal-substructure argument used for POS tagging, transplanted to the BIO alphabet. Define as the score of the best tag sequence for that ends in tag . Because the total sequence score decomposes as a sum of terms that each depend only on and the input, any optimal sequence ending in tag at position must, when restricted to positions , be an optimal sequence ending in some tag at position — otherwise swapping in a better prefix would strictly improve the whole sequence, contradicting optimality. This is precisely the optimal-substructure property required for dynamic programming, and it justifies the recurrence
Enforcing illegal transitions (I-LOC after O) as does not break this argument — it merely restricts the search space to well-formed BIO sequences, and the same optimal-substructure reasoning applies within that restricted space. Correctness of the final answer follows by induction on : the base case () is correct by direct computation, and the inductive step is exactly the recurrence above.
Honest tradeoffs.
- HMMs are cheap to train (closed-form counting) but assume tag-conditional independence of features, so they cannot easily use overlapping features like "capitalized AND ends in -son AND previous word is 'Mr.'"
- CRFs handle rich, overlapping features and are almost always more accurate, but training requires iterative optimization with repeated forward-backward passes, costing per sentence per gradient step — far more expensive than HMM counting.
- Enforcing BIO legality constraints is essentially free (it only shrinks the transition matrix), but it does not fix genuine model errors — a strong classifier score for a wrong boundary will still be chosen if it is the best legal option.
- Neither HMM nor CRF captures unbounded-length dependencies (e.g., an entity type depending on a noun ten tokens away); this is the classical model's central limitation, later addressed by neural sequence models (BiLSTM-CRF, transformer-based taggers) that keep the same BIO-and-Viterbi decoding backbone but replace hand-built features with learned representations.
Worked example
Sentence: "Yuri Gagarin visited Paris", true entities: PER = "Yuri Gagarin", LOC = "Paris". Suppose a trained (simplified, illustrative) CRF assigns the following local scores (emission + best incoming transition already folded in, rounded for readability) at each position, restricted to legal tags only:
| Position | Token | Candidate tag | Score | Best predecessor |
|---|---|---|---|---|
| 1 | Yuri | O | 1.0 | START |
| 1 | Yuri | B-PER | 4.5 | START |
| 1 | Yuri | B-LOC | 2.0 | START |
| 2 | Gagarin | O | 0.5 | (from any) |
| 2 | Gagarin | I-PER | 6.0 | B-PER (from pos 1) |
| 2 | Gagarin | B-PER | 1.5 | O |
| 3 | visited | O | 5.0 | I-PER (from pos 2) |
| 4 | Paris | O | 0.5 | O |
| 4 | Paris | B-LOC | 4.0 | O |
Running the Viterbi recurrence:
- dominates and .
- , the best option at position 2 (I-PER is only reachable from B-PER or I-PER, and B-PER was the strong choice at position 1, so this path is favored over starting fresh with B-PER at position 2).
- , clearly best since "visited" is not an entity token and O is reachable from any tag.
- , beating staying in O (which would give roughly ).
Backtracing from the highest final score gives the path:
which decodes to PER = "Yuri Gagarin", LOC = "Paris" — matching the gold entities exactly. Notice that even though "B-PER" at position 1 was chosen for local reasons, the global Viterbi search is what confirms it remains optimal once the strong I-PER continuation score at position 2 is taken into account; a greedy left-to-right tagger without the backward look implicit in dynamic programming could make the same choice here, but in general only the full Viterbi search guarantees the globally best sequence.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Illegal BIO transitions (e.g., O → I-LOC) | Training data sparsity lets the model assign nonzero score to impossible transitions | Hard-constrain the transition matrix so illegal pairs score |
| Token-level accuracy used to judge NER quality | O tags dominate most sentences, inflating accuracy trivially | Use entity-level (span + type) precision/recall/F1, e.g. CoNLL scoring |
| Confusing IOB1 and IOB2 conventions | B is only mandatory before a same-type entity in IOB1 but always mandatory in IOB2 | State the tagging convention explicitly; convert consistently before training/scoring |
| Tokenization mismatch with entity boundaries | Multi-word entities split incorrectly by a tokenizer (e.g., hyphenated names) | Align tokenizer and gold annotation boundaries before tagging |
| Gazetteer overfitting | Memorizing a fixed name list fails on unseen or novel entities | Combine gazetteers with contextual/orthographic features, not as the sole signal |
| Nested or overlapping entities ignored | Flat BIO cannot represent one entity inside another (e.g., "Bank of America" containing "America" as LOC) | Use specialized nested-NER models or layered tagging schemes when needed |
Pioneers & history
NER as a distinct shared task crystallized during the Message Understanding Conferences (MUC) in the 1990s, and the CRF formalism that dominates classical NER traces back to foundational work in statistical sequence modeling and probabilistic graphical models.
Origins · 1 minJohn D. Lafferty and how this was discovered
Lafferty, together with Andrew McCallum and Fernando Pereira, introduced Conditional Random Fields in 2001 as a discriminative alternative to hidden Markov models for sequence labeling, directly enabling modern feature-rich NER systems.
Where this matters
NER is a load-bearing component wherever unstructured text must be converted into structured facts. Search engines use it to detect entities in queries and documents for knowledge-panel construction and entity linking. Financial and legal technology firms use NER to extract company names, monetary amounts, and dates from filings and contracts for compliance monitoring. Clinical NLP pipelines rely on NER (often domain-tuned, e.g., i2b2 or BioNER) to pull medication names, dosages, and diagnoses from unstructured clinical notes. Chatbots and virtual assistants use lightweight NER modules to fill slots (dates, locations, product names) for downstream task completion. Downstream, NER output routinely feeds relation extraction, knowledge-graph population, and coreference resolution — and structurally, the same span-labeling-via-tagging idea recurs in shallow parsing and foreshadows the richer structural prediction problems tackled in Dependency Parsing, where entities and their syntactic relations are jointly modeled.
Ask the tutor: How would you extend BIO-based NER to handle entities that are nested inside one another?
What is the difference between IOB1, IOB2 (BIO), and BIOES tagging schemes?
IOB1 only requires a B-tag when two entities of the same type are directly adjacent; otherwise the first token of an entity can be tagged I-TYPE. IOB2 (commonly just called BIO) simplifies this by always requiring B-TYPE at the start of every entity, removing the ambiguity. BIOES (or BILOU) goes further, adding E-TYPE (end of a multi-token entity) and S-TYPE (a single-token entity standing alone), which gives the tagger more explicit boundary signal at the cost of a larger tag set. In practice, BIO (IOB2) is the most common default because it balances simplicity with unambiguous span recovery, while BIOES sometimes yields modest accuracy gains in neural taggers by making boundaries more explicit features.
Can NER handle nested entities, like an organization name containing a location?
Standard flat BIO tagging cannot represent nested spans, because each token receives exactly one tag, so "Bank of America" tagged as ORG leaves no room to also mark "America" as LOC underneath it. Handling nested entities requires specialized approaches: layered BIO tagging (running multiple independent taggers, one per nesting level), span-based classifiers that score all possible (start, end, type) triples directly rather than tagging tokens, or sequence-to-sequence models that generate structured output. Corpora like GENIA and ACE explicitly annotate nested entities and are used to benchmark these extensions, which are considered a more advanced, separate line of work beyond flat BIO NER.
Why do CRFs generally outperform HMMs for NER despite HMMs being simpler to train?
HMMs are generative models that factor using the strong assumption that each observed word depends only on its own hidden tag, which makes it awkward to incorporate overlapping, non-independent features (word shape, capitalization, surrounding words, gazetteer membership) without violating the model's assumptions. CRFs are discriminative: they directly model and can freely combine arbitrary, overlapping features of the entire observed sentence at every position, since there is no need to model how itself was generated. This flexibility consistently yields higher accuracy in practice, at the cost of more expensive training via iterative gradient optimization instead of simple frequency counting.
How is NER performance measured, and what counts as a correct prediction?
NER is scored at the entity level, not the token level. A predicted entity is counted as a true positive only if both its exact boundary (start and end token) and its type label match a gold-standard annotation exactly; a boundary that is one token too short, or a correct span with the wrong type, both count as errors. From these counts, precision (fraction of predicted entities that are correct), recall (fraction of gold entities recovered), and their harmonic mean F1 are computed, typically using the CoNLL evaluation script convention established by the CoNLL-2003 shared task.
Do modern neural NER systems still use BIO tagging and Viterbi decoding?
Yes, in large part. Architectures like BiLSTM-CRF, and many transformer-based token classifiers (e.g., fine-tuned BERT for NER), still output BIO tags and still use a CRF layer with Viterbi decoding on top of learned per-token feature vectors. What changes is how the emission scores are computed — instead of hand-built features and manual weight tuning, a neural network learns dense contextual representations end-to-end — but the fundamental algorithmic backbone of tagging plus constrained dynamic-programming decoding remains the same one described for classical NER.
What role do gazetteers play in classical NER systems, and what are their limits?
A gazetteer is a curated list of known entity names (cities, company names, celebrity names) used as a binary or categorical feature: "is this token, or this token sequence, present in gazetteer X?" Gazetteers are powerful because they inject external knowledge cheaply, especially for rare or ambiguous names that lack strong contextual cues. Their central limitation is coverage: gazetteers cannot recognize genuinely novel entities (a newly founded startup, a newly elected official) and can mislead the model when a common word also appears as a name (e.g., "Amazon" as a river versus a company). Robust systems combine gazetteer features with contextual and orthographic cues rather than relying on them alone.
How does entity typing interact with ambiguous words like "Washington"?
"Washington" could be a PERSON (George Washington), a LOCATION (Washington state or D.C.), or an ORGANIZATION (a sports team informally). Because BIO tagging with a CRF or neural tagger conditions on surrounding context — neighboring words, capitalization patterns, syntactic position, and often POS tags obtained via Part-of-Speech Tagging as a feature — the model can use "in Washington" (preposition + capitalized noun) versus "President Washington" (title + capitalized noun) to disambiguate. This context-sensitivity is exactly why sequence models outperform simple dictionary lookup for entity typing: the same surface string can receive different, context-appropriate tags in different sentences.