Sequence Labeling: From HMMs to Linear-Chain CRFs
One recursion in two semirings tags a sequence. From the hidden Markov model to the conditional random field, the family of conditionals does not change; what changes is what the estimator optimizes and what the features can see.
Overview & Motivation
An information-extraction system reads “Solenne Power guided to 4 percent growth in the first quarter” and has to mark Solenne Power as an organization, 4 percent as a percentage, and the first quarter as a date. Each of those is a span of tokens, and the standard trick turns spans into one tag per token. With BIO tags, a token is O (outside every entity), B-type (it begins an entity), or I-type (it continues one). The sentence above becomes
solenne/B-ORG power/I-ORG guided/O to/O percent/B-PERCENT growth/O in/O the/B-DATE first/I-DATE quarter/I-DATE.
The B is not decoration: “Boston, Massachusetts” tokenizes to two adjacent places, B-GPE B-GPE, and without it the two spans would merge.
A tagging of a sentence with tokens and tags is a path through a trellis: rows of states, columns of positions, one state chosen per column. There are paths, so every method on this page is a way to score paths and then find good ones without enumerating them. We take that in order:
- The HMM tagger scores a path by how likely it is to have generated the words, and fitting it is counting.
- One recursion, two semirings. Sums over paths and the best path come from the same pass.
- The linear-chain CRF scores a path given the words, and its likelihood is concave.
- A generative–discriminative pair. With word-identity features the HMM and the CRF define exactly the same conditional distributions.
- Decoding risk. The best path and the best tags are different answers to different losses.
- Local normalization. A chain of classifiers (the MEMM) cannot let later words change earlier tags.
- The structured perceptron learns the scores directly, with a mistake bound.
Then we measure all of it where the Bayes tagger is known exactly, and on the finance corpus.
The HMM tagger
We write for the words and for the tags.
Definition 1 (Sequence labeling with BIO tags).
A tagger maps a sentence to a tag sequence . For entity types , the BIO tag set is . An entity span opens at a B- tag, or at an I- tag that does not continue a span of type , and it runs while I- tags follow.
The hidden Markov model of formalStatistics’ hidden-markov-models (its Definition 3) becomes a tagger once the hidden states are the tags. We add one ingredient, an end state, so that the model is a distribution over sentences of every length.
Definition 2 (The HMM tagger).
An HMM tagger has a start distribution , transitions and stop probabilities with for every tag , and emissions . It assigns
Read the product from left to right. The tags form a bigram language model, the n-gram topic’s model over tags instead of words, and each word is drawn from its tag alone, as naive Bayes draws a document’s words from its class. Supervised training is then what those topics already do.
Proposition 1 (The HMM tagger is counting).
Given tagged sentences, the maximum-likelihood , , and are normalized counts: and divide the counts of and of ending a sentence by the number of times is followed by anything, and divides the count of tagged by the count of . Adding to every count gives the posterior mean under independent symmetric Dirichlet() priors on the rows. With the end state and every stop probability positive (add- with guarantees it), , where and , so the model is a distribution over sentences of every length.
Proof.
Take logs. The log-likelihood is a sum of separate terms, one per row: for each tag , one such sum for , and for each emission row. Each is a multinomial log-likelihood over its own probability vector, maximized by the frequencies: by Gibbs’ inequality, for every probability vector . The Dirichlet statement is conjugacy (formalStatistics multivariate-distributions, Theorem 6): the posterior of a row is Dirichlet(), with mean . For the last claim, every row of sums to , so whenever every stop probability is positive the spectral radius of is below one, the series converges to , and gives and .
One recursion, two semirings
Both training targets on this page, and both ways of decoding, are sums or maxima over the paths. We write every model as a chain of log-potentials. A path scores
with unary terms and pairwise terms , and the chain’s distribution is with . For the HMM, (plus at and at ) and , so and is the posterior of the tags.
Now notice that a sum over paths and a maximum over paths have the same structure. Multiplication distributes over addition, , and nonnegative multiplication distributes over maximum, . A commutative semiring is a set with two operations, and , each associative and commutative, with distributing over . The sum-product semiring and the max-product semiring on the nonnegative reals are the two we need. Write and .
Theorem 1 (The chain distributive law).
In any commutative semiring, define and, for ,
and symmetrically and . Write . Then:
(a) .
(b) , the aggregate of every path through .
(c) .
Each pass costs operations. In , (a) is , and dividing (b) and (c) by gives the node marginals and the edge marginals. In , (a) is the score of the best path (as a potential), and (b) divided by is the max-marginal .
Proof.
(a) We show by induction on that , the aggregate over prefixes ending in of the potentials up to . At there is nothing to aggregate. For the step, split the prefix into and . The factor does not involve , so by distributivity it comes out of the aggregate over , which leaves ; aggregating over gives the recursion. At , aggregate over too.
(b) The same induction run from the right shows aggregates the potentials after over suffixes that follow . A path through is a prefix ending in and a suffix following , chosen independently, and its potential is the product of the two parts. Distributivity turns the aggregate of products over independent choices into the product of the two aggregates.
(c) is (b) with the path pinned at two adjacent positions: prefix ending in , the edge, and suffix following . Each step of each pass aggregates terms for each of states, so per position.
∎One proof covers both semirings, and formalStatistics’ forward recursion (its Theorem 5), forward–backward smoothing (Theorem 7), and Viterbi decoding (Theorem 8) are the HMM’s potentials run through it. Viterbi’s back-pointers record which attained each maximum, so the best path itself, not only its score, comes out of the max pass. In code everything runs in log space, where is addition and is a log-sum-exp or a maximum. The harness checks all three parts in , and (a) and the max-marginals of (b) in , against brute-force enumeration of every path on random chains, some with forbidden tags and transitions, and pins the sum-product pass on Topic 12’s HMM against that topic’s forward–backward to .
The Trellis tab draws one sequence from that HMM with its emissions blended toward uniform noise (the well-specified world described below), eight states over positions. Toggle the semiring. In each cell shows its marginal ; in it shows the max-marginal relative to the best path’s probability, which is exactly along the Viterbi path. At position (the lab’s , counting from zero) the two views disagree: the marginal favors state (), while the best path through state beats the best path through state ( against ).
Each cell is the marginal γₜ(k), the probability that the tag at t is k. Posterior decoding takes each column's darkest cell (Theorem 4(b)). At t = 8 the two semirings disagree: the marginal favors s5, the best path runs through s0.
The linear-chain CRF
The HMM spends its parameters explaining the words, which a tagger is given. The conditional random field of Lafferty, McCallum, and Pereira (2001) models only the tags given the words.
Definition 3 (The linear-chain CRF).
Fix a feature map and let , with a start symbol (and an end feature at ). The linear-chain CRF with weights is
A feature may look at the whole sentence: the current word, its suffix, the words two to the left and two to the right. It can depend on at most two adjacent tags, which is what keeps the model a chain. For fixed the score is a chain score, so Theorem 1 computes and every marginal.
Theorem 2 (The CRF likelihood is concave).
For training pairs , let . Then
So is concave, and for every the penalized objective is strictly concave, with exactly one maximizer if it has one. The expectation decomposes over Theorem 1’s node and edge marginals.
Proof.
. Differentiating gives , the conditional mean of . Differentiating that mean once more gives , the conditional covariance. This is the multivariate, conditional form of formalStatistics exponential-families, Theorem 1. A covariance matrix is positive semidefinite, so the Hessian of is negative semidefinite and is concave by the second-order condition (formalML convex-analysis, Theorem 3). Subtracting subtracts from the Hessian, which makes it negative definite, and a strictly concave function has at most one maximizer. Finally, is a sum of terms each involving at most and , so its mean is a sum of expectations under the edge marginals .
At the optimum without a penalty, the gradient condition says the model’s expected feature counts equal the observed ones: the moment-matching condition of logistic regression in the linear text classifiers topic, now with expectations taken over paths. We fit by trust-region Newton’s method with exact Hessian-vector products, which we obtain by the complex step, , through a log-sum-exp that shifts by the real part’s maximum. On the experiment grids we use L-BFGS stopped at gradient , which lands within of the Newton solution with identical decodes, a gap the harness checks at one configuration ( in the next-state world).
A generative–discriminative pair
The HMM and the CRF look like different models. With the simplest features they are not.
Theorem 3 (HMMs and indicator CRFs give the same conditionals).
Call a CRF an indicator CRF if its features are indicators of each transition , each tag–word pair , each start tag, and each end tag, with weights , , , and . Over a finite vocabulary, the set of conditionals of HMM taggers (Definition 2) with positive parameters equals the set of conditionals of indicator CRFs. (A zero probability would need the weight ; every real-weighted CRF gives every path positive probability.)
(a) An HMM’s conditional is the indicator CRF with , , , .
(b) Conversely, given any real weights, let and , pick any larger than the spectral radius , and let , where is the vector of the . Then , and the HMM
has the same conditional as the CRF, for every sentence of every length.
Proof.
(a) The HMM’s log-joint is , which is the indicator CRF’s score with those weights. Dividing the joint by gives the CRF’s normalization.
(b) has positive entries, so for the Neumann series converges and has positive entries, and is positive. Each emission row sums to one by the choice of . For the transitions, the -th row of reads ; dividing by gives . Now multiply the HMM’s factors along a path. The factors of telescope:
with . Each in a numerator cancels the denominator of the next factor, the last against ; each cancels its emission’s denominator. What remains is , where is the CRF’s. The constant depends on but not on , so conditioning on removes it, and is the CRF’s.
∎Sutton and McCallum (2012, §2.3) prove direction (a) and call the converse “more complicated.” Smith and Johnson (2007, Corollary 2) prove the equivalence for features that pair a transition with the word it emits, by renormalizing weighted grammars; the construction above is the direct proof for our features. The harness builds the HMM of (b) for random weights, checks that it is a valid HMM, and checks its conditional against the CRF’s on every path to .
Corollary 1 (Same family, two estimators).
On indicator features, fitting an HMM by joint maximum likelihood and fitting a CRF by conditional maximum likelihood search the same set of conditionals. They differ in the criterion: the CRF minimizes the conditional log-loss of the tags on the training data, the HMM the joint log-loss of words and tags. As , the CRF’s conditional log-loss converges to the smallest the family allows, so it is at most the HMM’s, with equality when the data come from an HMM.
This is the linear text classifiers topic’s naive Bayes and logistic regression story, now for sequences; formalML’s naive-bayes (Section 7) has the classifier version of Ng and Jordan’s comparison. The geometry is one set of conditionals and two estimators landing at different points of it. Where the HMM is right, both land at the truth, and the HMM, whose estimates are counts, gets there faster. Where the HMM is wrong, the CRF lands closer in the metric it optimizes, and a CRF with richer features leaves the family altogether.
The harness measures both regimes in worlds where the Bayes tagger is exact, built on Topic 12’s HMM: eight states in two regimes, tokens per sequence, emissions blended with uniform noise. In the well-specified world the data come from that HMM. In the next-state world each word is drawn, with probability , from the emission row of the next state, so an HMM is wrong, and a CRF that sees the previous word can capture much of the dependence; the exact conditional also couples the two tags with the word between them, which no per-tag feature does. The true model’s conditional is still a chain, with each word’s emission folded into the edge it straddles, so Theorem 1 gives the Bayes tagger exactly. The CRFs are fit at , which on the mean objective is MAP estimation under a standard normal prior on ; the HMM’s smoothing is tuned on validation data.
| world, n | HMM | CRF, words | CRF, ±1 word | Bayes |
|---|---|---|---|---|
| well-specified, 10 | ||||
| well-specified, 1000 | ||||
| next-state, 10 | ||||
| next-state, 1000 |
The table gives test token accuracy; the CRF on words alone is the indicator CRF, the conditional family of HMMs with an end state (the fitted HMM, on sequences of one length, has none). On this training draw, in the well-specified world the HMM leads at and the two tie at , in accuracy and in conditional log-loss ( nats per token each, against the Bayes tagger’s ). In the next-state world the window CRF leads at every . The indicator CRF trails the HMM in accuracy there, against at , but beats it in conditional log-loss, against nats: Corollary 1 is a statement about the criterion each estimator optimizes, and accuracy is not that criterion. The HMM’s is chosen from , and it picks the top edge, , at every in both worlds. Past the edge, validation picks at and and at in the next-state world; then the HMM’s log-loss falls below the indicator CRF’s at , so the CRF’s log-loss win holds from on ( against ). Every accuracy ordering is unchanged. The Learning curves tab plots every , in accuracy or log-loss.
Decoding risk
The trellis offers two answers: the single best path, and the best tag at each position. They answer different questions.
Theorem 4 (What each decoder minimizes).
Let be a distribution over tag sequences with node marginals .
(a) The Viterbi path minimizes the expected sequence loss .
(b) The posterior-marginal (or minimum-Bayes-risk) decoding minimizes the expected Hamming loss , the expected number of wrong tags.
Proof.
(a) The expected sequence loss of is , smallest when is largest. (b) By linearity of expectation the expected Hamming loss is , a sum of terms each depending on one , so it is minimized position by position.
∎Token accuracy is one minus the Hamming loss divided by , so the Bayes tagger for token accuracy is posterior-marginal decoding, not Viterbi. In the well-specified world, the true model decoded by posterior marginals tags of test tokens correctly and decoded by Viterbi . On the trellis sequence, Viterbi gets of tags right and posterior decoding ; their expected numbers of correct tags are and . formalStatistics shows that the posterior-marginal path can even be impossible, with a zero-probability transition. Theorem 4 says when that is still the right answer: when what we count is tags, not sentences. Every learned tagger on this page is nevertheless decoded by Viterbi, as is standard, except the posterior-decoded MEMMs of the next section’s table; the Bayes reference is reported both ways.
Local normalization and label bias
Before the CRF there was a cheaper discriminative tagger: train a classifier for each tag given the previous tag and the words, and chain the classifiers.
Definition 4 (The MEMM).
A maximum-entropy Markov model (McCallum, Freitag, and Pereira 2000) is , each factor a softmax logistic regression on features of . It has lookahead if the factor at depends on only through .
Each factor is trained as an ordinary classifier on the gold previous tag, so an MEMM needs no forward–backward pass to train. It pays for that in what its marginals can see.
Proposition 2 (An MEMM's past ignores its future).
For an MEMM with lookahead and every , : the marginal of the first tags depends on no word after position .
Proof.
. Sum out first: only the last factor involves it, and it is a distribution over , so it sums to one. Then sum out , and so on down to . What remains is , and by the lookahead assumption each of those factors depends on only through .
∎This is label bias in its cleanest form (Lafferty, McCallum, and Pereira 2001): a locally normalized tagger passes on all of a state’s probability whatever the later words say, so the evidence of a later word cannot reach an earlier tag. Smith and Johnson (2007, Theorem 2) show that MEMMs represent strictly fewer conditionals than HMMs. Sutton and McCallum (2012, §5.1.3) add the practical caveat: copying later words into each factor’s features, a lookahead , buys back exactly words, which Proposition 2 makes precise.
Corollary 2 (A ceiling for posterior decoding).
An MEMM with lookahead , decoded by posterior marginals, has expected token accuracy at most that of the Bayes rule .
Proof.
By Proposition 2 the MEMM’s marginal for , and hence its decision at , is a function of . Among all functions of , the Bayes rule maximizes the probability of a correct tag at each .
∎Remark.
Corollary 2 is about posterior decoding, and it does not extend to Viterbi. The later factors of an MEMM sum to one over their tags, but their maximum is not constant, so the best path through still depends on how peaked the later factors are, and so on later words. That is label bias in Lafferty and colleagues’ original, Viterbi form.
Both halves are visible in the simulated worlds. Each MEMM sees two words to the left, with lookahead or , and is trained on sequences:
| world, lookahead | ceiling | MEMM, posterior | MEMM, Viterbi |
|---|---|---|---|
| well-specified, 0 | |||
| well-specified, 1 | |||
| next-state, 0 | |||
| next-state, 1 |
The “ceiling” column is Corollary 2’s lagged Bayes rule, computed exactly on prefix chains. Every posterior-decoded MEMM sits below its ceiling, and in the well-specified world the causal MEMM decoded by Viterbi () rises above it (), as the remark allows. The CRF, whose marginals see the whole sentence, is bounded only by the full Bayes rule, there. One word of lookahead recovers about two-thirds of the gap, . In a chain the influence of a word on a tag tends to shrink with their distance, so the nearest future word carries most of what the future says; that is a picture, not a theorem proved here. The CRF vs. MEMM tab shows Proposition 2 on a sentence.
The structured perceptron
The CRF fits probabilities. Collins (2002) asked for less: weights under which the gold path outscores every other path, found by correcting mistakes.
Algorithm 1 (The structured perceptron).
Start at . For each training pair in turn, decode by Viterbi; if , update . Repeat for several epochs. The averaged perceptron returns the average of over every step.
Theorem 5 (The perceptron's mistake bound).
Suppose some unit vector separates the training data with margin , for every and every , and every difference has norm at most . Then the perceptron makes at most mistakes, however many epochs it runs.
Proof.
Let be the weights before the -th mistake, , and suppose that mistake happens on pair with decoded path . Then with . First, , so . Second, , because won the decoding, so . So . Since is a unit vector, , so .
∎The proof uses the decoder only through one fact, that it returned a path scoring at least as high as the gold one, so the bound holds for any exact decoder. Collins’s Theorem 2 extends it to data that are not separable, and averaging, which every simulated-world and finance tagger here uses, is his practical recommendation; the Perceptron tab runs the plain perceptron. The Perceptron tab runs the theorem on data labeled by a teacher, at six margins: mistakes trend up from to as falls from to (not at every step: , then ), while the bound rises from to . It holds every time, and it is loose by a factor of to , as worst-case bounds are.
Tagging entities in filings
Where this sits
The tagger on this page has two parts: a chain over tags and a scorer for each position. The chain, and with it every algorithm here, stays when the scorer changes. The next topic, named-entity recognition, replaces the hand-built features with a contextual encoder’s states and keeps the CRF on top. It also takes up what this page left aside: span-level evaluation, decoding constrained to valid BIO sequences, and names held out by design. A chain is the simplest graphical model; Theorem 1’s semiring argument is the one that sum-product and max-product message passing generalize to trees.
Honest caveats
Implementation
The companion notebook (notebookPath) imports sequence_labeling_hmm_crf.py, which owns every number on this page. It imports the n-gram topic’s module and the linear text classifiers topic’s module, whose softmax logistic regression fits every MEMM factor and whose finance corpus supplies the entity spans, and the masked-LM topic’s module for its HMM, sampler, and forward–backward pass. Its harness checks:
- Theorem 1 in both semirings, and the max-marginals, against enumeration of every path;
- Proposition 1’s counts and length law;
- Theorem 2’s gradient and Hessian-vector products against complex-step derivatives, and its unique optimum from two starts;
- Theorem 3 in both directions on random weights, sentences, and lengths;
- Proposition 2 and Theorem 4 on random chains, and Corollary 2 against lagged Bayes rules;
- Theorem 5 at every margin of the sweep;
- every comparison this page states, in both worlds and on the finance documents.
The laboratory reads its data from a JSON file that one of the harness’s tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
Connections
- Its eight-state hidden Markov model is this page's simulated world, and its scaled forward-backward pass is the reference our semiring recursion is pinned against to 10^-10. contextual-embeddings-masked-lm
- Viterbi is exact max-product search because a chain's state is its last tag; beam search is what remains when a decoder carries its whole prefix as state and no recombination is possible. beam-search-decoding
References & Further Reading
- paper Conditional Random Fields: Probabilistic Models for Segmenting and Labeling Sequence Data — John Lafferty, Andrew McCallum, and Fernando C. N. Pereira (2001) Proceedings of the 18th ICML, 282–89. The linear-chain CRF and the label bias problem of locally normalized taggers
- paper Maximum Entropy Markov Models for Information Extraction and Segmentation — Andrew McCallum, Dayne Freitag, and Fernando Pereira (2000) Proceedings of the 17th ICML, 591–98. The MEMM: a Markov chain whose transitions are log-linear classifiers of the observation
- paper Weighted and Probabilistic Context-Free Grammars Are Equally Expressive — Noah A. Smith and Mark Johnson (2007) Computational Linguistics 33, no. 4: 477–91. Corollary 2: HMMs and chain random fields with Mealy features give the same conditionals; Theorem 2: MEMMs give strictly fewer
- paper An Introduction to Conditional Random Fields — Charles Sutton and Andrew McCallum (2012) Foundations and Trends in Machine Learning 4, no. 4: 267–373. Section 2.3 (an HMM's conditional is a CRF; the converse is 'more complicated'), Section 5.1.3 (MEMMs and label bias)
- paper Discriminative Training Methods for Hidden Markov Models: Theory and Experiments with Perceptron Algorithms — Michael Collins (2002) Proceedings of EMNLP 2002, 1–8. Theorem 1 (the separable mistake bound), Theorem 2 (the non-separable bound), Section 2.5 (averaging)
- paper Conditional Structure versus Conditional Estimation in NLP Models — Dan Klein and Christopher D. Manning (2002) Proceedings of EMNLP 2002. Separates the model's conditional structure from conditional estimation, and names observation bias in MEMMs
- paper On Discriminative vs. Generative Classifiers: A Comparison of Logistic Regression and Naive Bayes — Andrew Y. Ng and Michael I. Jordan (2002) Advances in Neural Information Processing Systems 14, 841–48. The generative–discriminative pair, of which Theorem 3 is the sequence version
- paper A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition — Lawrence R. Rabiner (1989) Proceedings of the IEEE 77, no. 2: 257–86. The forward–backward and Viterbi recursions in their classical form