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.

Key takeaways
  • 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.
The core insight

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 KK entity types, the BIO scheme produces 2K+12K+1 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 w1,…,wnw_1, \dots, w_n, an NER system must produce a tag sequence t1,…,tnt_1, \dots, t_n over the BIO tag set. This is scored by a probabilistic sequence model. Two classical families dominate: 1. Hidden Markov Model (HMM) — generative, defines P(w1n,t1n)=∏iP(ti∣ti−1)P(wi∣ti)P(w_1^n, t_1^n) = \prod_i P(t_i \mid t_{i-1}) P(w_i \mid t_i). 2. Linear-chain Conditional Random Field (CRF) — discriminative, defines

P(t1n∣w1n)=1Z(w1n)exp⁡(∑i=1n∑kλkfk(ti−1,ti,w1n,i))P(t_1^n \mid w_1^n) = \frac{1}{Z(w_1^n)} \exp\left(\sum_{i=1}^{n} \sum_k \lambda_k f_k(t_{i-1}, t_i, w_1^n, i)\right)

where fkf_k are arbitrary feature functions (word identity, capitalization, prefixes/suffixes, gazetteer membership, POS tag, previous tag) and ZZ 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 (ti−1,ti)(t_{i-1}, t_i) 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

t^1n=arg⁡max⁡t1n  score(t1n,w1n).\hat{t}_1^n = \arg\max_{t_1^n} \; \text{score}(t_1^n, w_1^n).

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 −∞-\infty, 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 λk\lambda_k has the classic form

∂log⁡P(t∗∣w)∂λk=∑ifk(ti−1∗,ti∗,w,i)  −  EP(t∣w)[∑ifk(ti−1,ti,w,i)],\frac{\partial \log P(t^{*} \mid w)}{\partial \lambda_k} = \sum_i f_k(t^*_{i-1}, t^*_i, w, i) \;-\; \mathbb{E}_{P(t \mid w)}\left[\sum_i f_k(t_{i-1}, t_i, w, i)\right],

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.

Figure
BIO tagging pipeline: sentence → tag sequence → extracted spans
Sentence MarieCuriewon theNobelPrize inStockholm Viterbi trellis (best path highlighted) O B-PER I-PER B-LOC I-LOC B-MISC I-MISC Extracted spans PER: "Marie Curie" MISC: "Nobel Prize" LOC: "Stockholm"

Complexity & correctness

Time complexity of decoding. With nn tokens and ∣T∣|T| tags, the Viterbi recurrence fills an n×∣T∣n \times |T| table, and computing each cell requires examining all ∣T∣|T| predecessor tags, giving O(n⋅∣T∣2)O(n \cdot |T|^2) time. With BIO's 2K+12K+1 tags, this is O(nK2)O(n K^2) — 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 O(n⋅∣T∣)O(n \cdot |T|) for the δ\delta and ψ\psi tables (or O(∣T∣)O(|T|) 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 δ[i][t]\delta[i][t] as the score of the best tag sequence for w1,…,wiw_1, \dots, w_i that ends in tag tt. Because the total sequence score decomposes as a sum of terms that each depend only on (ti−1,ti)(t_{i-1}, t_i) and the input, any optimal sequence ending in tag tt at position ii must, when restricted to positions 1,…,i−11, \dots, i-1, be an optimal sequence ending in some tag tprevt_{\text{prev}} at position i−1i-1 — 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

δ[i][t]=max⁡tprev(δ[i−1][tprev]+trans(tprev,t)+emit(t,w,i)).\delta[i][t] = \max_{t_{\text{prev}}} \Big(\delta[i-1][t_{\text{prev}}] + \text{trans}(t_{\text{prev}}, t) + \text{emit}(t, w, i)\Big).

Enforcing illegal transitions (I-LOC after O) as −∞-\infty 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 ii: the base case (i=1i=1) 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 O(nK2)O(n K^2) 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:

PositionTokenCandidate tagScoreBest predecessor
1YuriO1.0START
1YuriB-PER4.5START
1YuriB-LOC2.0START
2GagarinO0.5(from any)
2GagarinI-PER6.0B-PER (from pos 1)
2GagarinB-PER1.5O
3visitedO5.0I-PER (from pos 2)
4ParisO0.5O
4ParisB-LOC4.0O

Running the Viterbi recurrence:

  • δ[1][B-PER]=4.5\delta[1][\text{B-PER}] = 4.5 dominates δ[1][O]=1.0\delta[1][O]=1.0 and δ[1][B-LOC]=2.0\delta[1][\text{B-LOC}]=2.0.
  • δ[2][I-PER]=δ[1][B-PER]+trans(B-PER→I-PER)+emit=6.0\delta[2][\text{I-PER}] = \delta[1][\text{B-PER}] + \text{trans}(\text{B-PER}\to\text{I-PER}) + \text{emit} = 6.0, 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).
  • δ[3][O]=δ[2][I-PER]+trans(I-PER→O)+emit=11.0\delta[3][O] = \delta[2][\text{I-PER}] + \text{trans}(\text{I-PER}\to O) + \text{emit} = 11.0, clearly best since "visited" is not an entity token and O is reachable from any tag.
  • δ[4][B-LOC]=δ[3][O]+trans(O→B-LOC)+emit=15.0\delta[4][\text{B-LOC}] = \delta[3][O] + \text{trans}(O \to \text{B-LOC}) + \text{emit} = 15.0, beating staying in O (which would give roughly 11.511.5).

Backtracing from the highest final score gives the path:

B-PER→I-PER→O→B-LOC\text{B-PER} \to \text{I-PER} \to O \to \text{B-LOC}

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

PitfallWhy it happensFix
Illegal BIO transitions (e.g., O → I-LOC)Training data sparsity lets the model assign nonzero score to impossible transitionsHard-constrain the transition matrix so illegal pairs score −∞-\infty
Token-level accuracy used to judge NER qualityO tags dominate most sentences, inflating accuracy triviallyUse entity-level (span + type) precision/recall/F1, e.g. CoNLL scoring
Confusing IOB1 and IOB2 conventionsB is only mandatory before a same-type entity in IOB1 but always mandatory in IOB2State the tagging convention explicitly; convert consistently before training/scoring
Tokenization mismatch with entity boundariesMulti-word entities split incorrectly by a tokenizer (e.g., hyphenated names)Align tokenizer and gold annotation boundaries before tagging
Gazetteer overfittingMemorizing a fixed name list fails on unseen or novel entitiesCombine gazetteers with contextual/orthographic features, not as the sole signal
Nested or overlapping entities ignoredFlat 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
JD
John D. Lafferty
1957– · Statistical machine learning, Carnegie Mellon University and University of Chicago

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.

History
1991
— Lexico-Semantic Pattern work and MUC conferences establish named-entity extraction as a formal task.
1996
— MUC-6 formally defines the "named entity" task with PERSON, ORGANIZATION, LOCATION, and other categories.
2001
— Lafferty, McCallum, and Pereira publish Conditional Random Fields, replacing MEMMs' label-bias-prone architecture.
2003
— CoNLL-2003 shared task establishes the standard PER/ORG/LOC/MISC benchmark still used to compare NER systems.
2011
onward — Neural sequence taggers (BiLSTM-CRF and successors) adopt the same BIO-and-Viterbi decoding backbone atop learned representations.

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 P(w,t)P(w, t) 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 P(t∣w)P(t \mid w) and can freely combine arbitrary, overlapping features of the entire observed sentence at every position, since there is no need to model how ww 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.

Before this

Where this leads