intermediate extraction-knowledge-graphs 35 min read

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 TT tokens and KK tags is a path through a trellis: KK rows of states, TT columns of positions, one state chosen per column. There are KTK^T 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:

  1. The HMM tagger scores a path by how likely it is to have generated the words, and fitting it is counting.
  2. One recursion, two semirings. Sums over paths and the best path come from the same pass.
  3. The linear-chain CRF scores a path given the words, and its likelihood is concave.
  4. A generative–discriminative pair. With word-identity features the HMM and the CRF define exactly the same conditional distributions.
  5. Decoding risk. The best path and the best tags are different answers to different losses.
  6. Local normalization. A chain of classifiers (the MEMM) cannot let later words change earlier tags.
  7. 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 x1:Tx_{1:T} for the words and z1:Tz_{1:T} for the tags.

Definition 1 (Sequence labeling with BIO tags).

A tagger maps a sentence x1:Tx_{1:T} to a tag sequence z1:T∈YTz_{1:T} \in \mathcal Y^T. For entity types EE, the BIO tag set is Y={O}∪{B-e,I-e:e∈E}\mathcal Y = \{\mathrm O\} \cup \{\mathrm{B}\text{-}e, \mathrm{I}\text{-}e : e \in E\}. An entity span opens at a B-ee tag, or at an I-ee tag that does not continue a span of type ee, and it runs while I-ee 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 ν\nu, transitions ajka_{jk} and stop probabilities aj,stopa_{j,\mathrm{stop}} with ∑kajk+aj,stop=1\sum_k a_{jk} + a_{j,\mathrm{stop}} = 1 for every tag jj, and emissions bk(w)b_k(w). It assigns

p(x1:T,z1:T)=νz1∏t=2Tazt−1zt∏t=1Tbzt(xt)  azT,stop.p(x_{1:T}, z_{1:T}) = \nu_{z_1} \prod_{t=2}^{T} a_{z_{t-1} z_t} \prod_{t=1}^{T} b_{z_t}(x_t)\; a_{z_T,\mathrm{stop}}.

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 ν^\hat\nu, a^\hat a, and b^\hat b are normalized counts: a^jk\hat a_{jk} and a^j,stop\hat a_{j,\mathrm{stop}} divide the counts of j→kj \to k and of jj ending a sentence by the number of times jj is followed by anything, and b^k(w)\hat b_k(w) divides the count of ww tagged kk by the count of kk. Adding α\alpha to every count gives the posterior mean under independent symmetric Dirichlet(α\alpha) priors on the rows. With the end state and every stop probability positive (add-α\alpha with α>0\alpha \gt 0 guarantees it), ∑T≥1νAT−1e=ν(I−A)−1e=1\sum_{T \ge 1} \nu A^{T-1} e = \nu(I - A)^{-1} e = 1, where A=(ajk)A = (a_{jk}) and e=(aj,stop)je = (a_{j,\mathrm{stop}})_j, 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: ∑kcjklog⁡ajk+cj,stoplog⁡aj,stop\sum_k c_{jk}\log a_{jk} + c_{j,\mathrm{stop}} \log a_{j,\mathrm{stop}} for each tag jj, one such sum for ν\nu, and ∑wckwlog⁡bk(w)\sum_w c_{kw} \log b_k(w) for each emission row. Each is a multinomial log-likelihood over its own probability vector, maximized by the frequencies: by Gibbs’ inequality, ∑icilog⁡qi≤∑icilog⁡(ci/∑lcl)\sum_i c_i \log q_i \le \sum_i c_i \log (c_i / \sum_l c_l) for every probability vector qq. The Dirichlet statement is conjugacy (formalStatistics multivariate-distributions, Theorem 6): the posterior of a row is Dirichlet(α+c\alpha + c), with mean (α+ci)/∑l(α+cl)(\alpha + c_i)/\sum_l(\alpha + c_l). For the last claim, every row of AA sums to 1−aj,stop1 - a_{j,\mathrm{stop}}, so whenever every stop probability is positive the spectral radius of AA is below one, the series ∑TAT−1\sum_T A^{T-1} converges to (I−A)−1(I - A)^{-1}, and (I−A)1=e(I - A)\mathbf 1 = e gives (I−A)−1e=1(I-A)^{-1}e = \mathbf 1 and ν1=1\nu \mathbf 1 = 1.

∎

One recursion, two semirings

Both training targets on this page, and both ways of decoding, are sums or maxima over the KTK^T paths. We write every model as a chain of log-potentials. A path scores

score⁡(z1:T)=∑t=1TUt(zt)+∑t=1T−1Pt(zt,zt+1),\operatorname{score}(z_{1:T}) = \sum_{t=1}^{T} U_t(z_t) + \sum_{t=1}^{T-1} P_t(z_t, z_{t+1}),

with unary terms UtU_t and pairwise terms PtP_t, and the chain’s distribution is p(z)=escore⁡(z)/Zp(z) = e^{\operatorname{score}(z)}/Z with Z=∑zescore⁡(z)Z = \sum_z e^{\operatorname{score}(z)}. For the HMM, Ut(k)=log⁡bk(xt)U_t(k) = \log b_k(x_t) (plus log⁡νk\log \nu_k at t=1t = 1 and log⁡ak,stop\log a_{k,\mathrm{stop}} at t=Tt = T) and Pt(j,k)=log⁡ajkP_t(j, k) = \log a_{jk}, so Z=p(x1:T)Z = p(x_{1:T}) and p(z)p(z) 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, a(b+c)=ab+aca(b + c) = ab + ac, and nonnegative multiplication distributes over maximum, amax⁡(b,c)=max⁡(ab,ac)a\max(b, c) = \max(ab, ac). A commutative semiring is a set with two operations, ⊕\oplus and ⊗\otimes, each associative and commutative, with ⊗\otimes distributing over ⊕\oplus. The sum-product semiring (+,×)(+, \times) and the max-product semiring (max⁡,×)(\max, \times) on the nonnegative reals are the two we need. Write ψt(k)=eUt(k)\psi_t(k) = e^{U_t(k)} and ψt,t+1(j,k)=ePt(j,k)\psi_{t,t+1}(j, k) = e^{P_t(j, k)}.

Theorem 1 (The chain distributive law).

In any commutative semiring, define α1(k)=ψ1(k)\alpha_1(k) = \psi_1(k) and, for t≥2t \ge 2,

αt(k)=ψt(k)⊗⨁jαt−1(j)⊗ψt−1,t(j,k),\alpha_t(k) = \psi_t(k) \otimes \bigoplus_{j} \alpha_{t-1}(j) \otimes \psi_{t-1,t}(j, k),

and symmetrically βT(j)=1\beta_T(j) = \mathbf 1 and βt(j)=⨁kψt,t+1(j,k)⊗ψt+1(k)⊗βt+1(k)\beta_t(j) = \bigoplus_k \psi_{t,t+1}(j, k) \otimes \psi_{t+1}(k) \otimes \beta_{t+1}(k). Write Ψ(z)=⨂tψt(zt)⊗⨂tψt,t+1(zt,zt+1)\Psi(z) = \bigotimes_t \psi_t(z_t) \otimes \bigotimes_t \psi_{t,t+1}(z_t, z_{t+1}). Then:

(a) ⨁kαT(k)=⨁zΨ(z)\bigoplus_k \alpha_T(k) = \bigoplus_{z} \Psi(z).

(b) αt(k)⊗βt(k)=⨁z:zt=kΨ(z)\alpha_t(k) \otimes \beta_t(k) = \bigoplus_{z : z_t = k} \Psi(z), the aggregate of every path through (t,k)(t, k).

(c) αt(j)⊗ψt,t+1(j,k)⊗ψt+1(k)⊗βt+1(k)=⨁z:zt=j, zt+1=kΨ(z)\alpha_t(j) \otimes \psi_{t,t+1}(j, k) \otimes \psi_{t+1}(k) \otimes \beta_{t+1}(k) = \bigoplus_{z : z_t = j,\, z_{t+1} = k} \Psi(z).

Each pass costs O(TK2)O(TK^2) operations. In (+,×)(+, \times), (a) is ZZ, and dividing (b) and (c) by ZZ gives the node marginals γt(k)=p(zt=k)\gamma_t(k) = p(z_t = k) and the edge marginals. In (max⁡,×)(\max, \times), (a) is the score of the best path (as a potential), and (b) divided by ZZ is the max-marginal μt(k)=max⁡z:zt=kp(z)\mu_t(k) = \max_{z: z_t = k} p(z).

Proof.

(a) We show by induction on tt that αt(k)=⨁z1:t−1Ψ1:t(z1:t−1,k)\alpha_t(k) = \bigoplus_{z_{1:t-1}} \Psi_{1:t}(z_{1:t-1}, k), the aggregate over prefixes ending in kk of the potentials up to tt. At t=1t = 1 there is nothing to aggregate. For the step, split the prefix into z1:t−2z_{1:t-2} and zt−1=jz_{t-1} = j. The factor ψt−1,t(j,k)⊗ψt(k)\psi_{t-1,t}(j, k) \otimes \psi_t(k) does not involve z1:t−2z_{1:t-2}, so by distributivity it comes out of the aggregate over z1:t−2z_{1:t-2}, which leaves αt−1(j)\alpha_{t-1}(j); aggregating over jj gives the recursion. At t=Tt = T, aggregate over kk too.

(b) The same induction run from the right shows βt(k)\beta_t(k) aggregates the potentials after tt over suffixes that follow kk. A path through (t,k)(t, k) is a prefix ending in kk and a suffix following kk, 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 jj, the edge, and suffix following kk. Each step of each pass aggregates KK terms for each of KK states, so O(K2)O(K^2) 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 jj 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 ⊗\otimes is addition and ⊕\oplus is a log-sum-exp or a maximum. The harness checks all three parts in (+,×)(+, \times), and (a) and the max-marginals of (b) in (max⁡,×)(\max, \times), 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 10−1010^{-10}.

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 2424 positions. Toggle the semiring. In (+,×)(+, \times) each cell shows its marginal γt(k)\gamma_t(k); in (max⁡,×)(\max, \times) it shows the max-marginal relative to the best path’s probability, which is exactly 11 along the Viterbi path. At position 99 (the lab’s t=8t = 8, counting from zero) the two views disagree: the marginal favors state 55 (0.5050.505), while the best path through state 00 beats the best path through state 55 (11 against 0.6140.614).

One recursion, two semirings: marginals or max-marginals on the trellis
semiring
s0s1s2s3s4s5s6s7a3b10a9wa1a11wa12b4b5a3b2b11wwb10b7b4b11a8a8a11b1a8048121620position t
posterior-marginal pathViterbi pathgold state
positiont = 8
s0 0.194s1 0.039s2 0.032s3 0.145s4 0.033s5 0.505s6 0.017s7 0.034
Viterbi, tags right
17 / 24
posterior decoding, tags right
19 / 24
expected tags right (Viterbi / posterior)
16.384 / 16.928
probability of the best path
0.000112

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 f(zt−1,zt,x,t)∈Rdf(z_{t-1}, z_t, x, t) \in \mathbb R^d and let F(x,z)=∑tf(zt−1,zt,x,t)F(x, z) = \sum_t f(z_{t-1}, z_t, x, t), with z0z_0 a start symbol (and an end feature at t=Tt = T). The linear-chain CRF with weights θ∈Rd\theta \in \mathbb R^d is

pθ(z∣x)=exp⁡(θ⋅F(x,z))Zθ(x),Zθ(x)=∑z′exp⁡(θ⋅F(x,z′)).p_\theta(z \mid x) = \frac{\exp\big(\theta \cdot F(x, z)\big)}{Z_\theta(x)}, \qquad Z_\theta(x) = \sum_{z'} \exp\big(\theta \cdot F(x, z')\big).

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 xx the score θ⋅F(x,z)\theta \cdot F(x, z) is a chain score, so Theorem 1 computes Zθ(x)Z_\theta(x) and every marginal.

Theorem 2 (The CRF likelihood is concave).

For training pairs (xi,zi)i≤n(x_i, z_i)_{i \le n}, let ℓ(θ)=1n∑ilog⁡pθ(zi∣xi)\ell(\theta) = \frac1n \sum_i \log p_\theta(z_i \mid x_i). Then

∇ℓ(θ)=1n∑i(F(xi,zi)−Eθ[F(xi,Z)∣xi]),∇2ℓ(θ)=−1n∑iCov⁡θ[F(xi,Z)∣xi]⪯0.\nabla \ell(\theta) = \frac1n \sum_i \Big(F(x_i, z_i) - \mathbb E_\theta\big[F(x_i, Z) \mid x_i\big]\Big), \qquad \nabla^2 \ell(\theta) = -\frac1n \sum_i \operatorname{Cov}_\theta\big[F(x_i, Z) \mid x_i\big] \preceq 0.

So ℓ\ell is concave, and for every λ>0\lambda \gt 0 the penalized objective ℓ(θ)−λ2∥θ∥2\ell(\theta) - \frac\lambda2 \|\theta\|^2 is strictly concave, with exactly one maximizer if it has one. The expectation decomposes over Theorem 1’s node and edge marginals.

Proof.

log⁡pθ(zi∣xi)=θ⋅F(xi,zi)−log⁡Zθ(xi)\log p_\theta(z_i \mid x_i) = \theta \cdot F(x_i, z_i) - \log Z_\theta(x_i). Differentiating log⁡Zθ(x)=log⁡∑zeθ⋅F(x,z)\log Z_\theta(x) = \log \sum_z e^{\theta\cdot F(x, z)} gives ∑zpθ(z∣x)F(x,z)\sum_z p_\theta(z \mid x) F(x, z), the conditional mean of FF. Differentiating that mean once more gives ∑zpθ(z∣x)FF⊤−(∑zpθF)(∑zpθF)⊤\sum_z p_\theta(z \mid x) F F^\top - \big(\sum_z p_\theta F\big)\big(\sum_z p_\theta F\big)^\top, 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 ℓ\ell is negative semidefinite and ℓ\ell is concave by the second-order condition (formalML convex-analysis, Theorem 3). Subtracting λ2∥θ∥2\frac\lambda2\|\theta\|^2 subtracts λI\lambda I from the Hessian, which makes it negative definite, and a strictly concave function has at most one maximizer. Finally, FF is a sum of terms each involving at most zt−1z_{t-1} and ztz_t, so its mean is a sum of expectations under the edge marginals pθ(zt−1,zt∣x)p_\theta(z_{t-1}, z_t \mid x).

∎

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, ∇2ℓ v=Im⁡∇ℓ(θ+ihv)/h\nabla^2\ell\, v = \operatorname{Im} \nabla \ell(\theta + ihv)/h, through a log-sum-exp that shifts by the real part’s maximum. On the experiment grids we use L-BFGS stopped at gradient 10−610^{-6}, which lands within 10−410^{-4} of the Newton solution with identical decodes, a gap the harness checks at one configuration (n=100n = 100 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 j→kj \to k, each tag–word pair (k,w)(k, w), each start tag, and each end tag, with weights θjk\theta_{jk}, μkw\mu_{kw}, sks_k, and ηk\eta_k. Over a finite vocabulary, the set of conditionals p(z∣x)p(z \mid x) of HMM taggers (Definition 2) with positive parameters equals the set of conditionals of indicator CRFs. (A zero probability would need the weight −∞-\infty; every real-weighted CRF gives every path positive probability.)

(a) An HMM’s conditional is the indicator CRF with θjk=log⁡ajk\theta_{jk} = \log a_{jk}, μkw=log⁡bk(w)\mu_{kw} = \log b_k(w), sk=log⁡νks_k = \log \nu_k, ηk=log⁡ak,stop\eta_k = \log a_{k,\mathrm{stop}}.

(b) Conversely, given any real weights, let Sk=∑weμkwS_k = \sum_w e^{\mu_{kw}} and Mjk=eθjkSkM_{jk} = e^{\theta_{jk}} S_k, pick any cc larger than the spectral radius ρ(M)\rho(M), and let h=(cI−M)−1eηh = (cI - M)^{-1} e^{\eta}, where eηe^{\eta} is the vector of the eηje^{\eta_j}. Then h>0h \gt 0, and the HMM

bk(w)=eμkwSk,ajk=Mjk hkc hj,aj,stop=eηjc hj,νk∝eskSkhkb_k(w) = \frac{e^{\mu_{kw}}}{S_k}, \qquad a_{jk} = \frac{M_{jk}\, h_k}{c\, h_j}, \qquad a_{j,\mathrm{stop}} = \frac{e^{\eta_j}}{c\, h_j}, \qquad \nu_k \propto e^{s_k} S_k h_k

has the same conditional as the CRF, for every sentence of every length.

Proof.

(a) The HMM’s log-joint is log⁡νz1+∑tlog⁡azt−1zt+∑tlog⁡bzt(xt)+log⁡azT,stop\log\nu_{z_1} + \sum_t \log a_{z_{t-1}z_t} + \sum_t \log b_{z_t}(x_t) + \log a_{z_T,\mathrm{stop}}, which is the indicator CRF’s score with those weights. Dividing the joint by p(x)=∑zp(x,z)p(x) = \sum_z p(x, z) gives the CRF’s normalization.

(b) MM has positive entries, so for c>ρ(M)c \gt \rho(M) the Neumann series (cI−M)−1=∑m≥0Mm/cm+1(cI - M)^{-1} = \sum_{m \ge 0} M^m / c^{m+1} converges and has positive entries, and hh is positive. Each emission row sums to one by the choice of SkS_k. For the transitions, the jj-th row of (cI−M)h=eη(cI - M)h = e^{\eta} reads c hj=∑kMjkhk+eηjc\,h_j = \sum_k M_{jk} h_k + e^{\eta_j}; dividing by c hjc\,h_j gives ∑kajk+aj,stop=1\sum_k a_{jk} + a_{j,\mathrm{stop}} = 1. Now multiply the HMM’s factors along a path. The factors of hh telescope:

νz1∏t≥2azt−1zt azT,stop∏tbzt(xt)=esz1Sz1hz1N⋅∏t≥2eθzt−1ztSzthztc hzt−1⋅eηzTc hzT⋅∏teμztxtSzt,\nu_{z_1} \prod_{t \ge 2} a_{z_{t-1}z_t} \, a_{z_T,\mathrm{stop}} \prod_t b_{z_t}(x_t) = \frac{e^{s_{z_1}} S_{z_1} h_{z_1}}{N} \cdot \prod_{t \ge 2} \frac{e^{\theta_{z_{t-1}z_t}} S_{z_t} h_{z_t}}{c\, h_{z_{t-1}}} \cdot \frac{e^{\eta_{z_T}}}{c\, h_{z_T}} \cdot \prod_t \frac{e^{\mu_{z_t x_t}}}{S_{z_t}},

with N=∑keskSkhkN = \sum_k e^{s_k} S_k h_k. Each hzth_{z_t} in a numerator cancels the denominator of the next factor, the last against azT,stopa_{z_T,\mathrm{stop}}; each SztS_{z_t} cancels its emission’s denominator. What remains is escore⁡(z)/(NcT)e^{\operatorname{score}(z)}/(N c^{T}), where score⁡\operatorname{score} is the CRF’s. The constant depends on TT but not on zz, so conditioning on xx removes it, and p(z∣x)p(z \mid x) 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 10−1210^{-12}.

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 n→∞n \to \infty, 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, 2424 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 0.50.5, 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 λ=1/n\lambda = 1/n, which on the mean objective is MAP estimation under a standard normal prior on θ\theta; the HMM’s smoothing α\alpha is tuned on validation data.

world, nHMMCRF, wordsCRF, ±1 wordBayes
well-specified, 100.7380.7380.7250.7250.7080.7080.7820.782
well-specified, 10000.7760.7760.7760.7760.7730.7730.7820.782
next-state, 100.4860.4860.4790.4790.4960.4960.6200.620
next-state, 10000.5400.5400.5340.5340.5910.5910.6200.620

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 n=10n = 10 and the two tie at n=1000n = 1000, in accuracy and in conditional log-loss (0.5830.583 nats per token each, against the Bayes tagger’s 0.5800.580). In the next-state world the window CRF leads at every nn. The indicator CRF trails the HMM in accuracy there, 0.5340.534 against 0.5400.540 at n=1000n = 1000, but beats it in conditional log-loss, 1.0361.036 against 1.0401.040 nats: Corollary 1 is a statement about the criterion each estimator optimizes, and accuracy is not that criterion. The HMM’s α\alpha is chosen from {1,0.1,0.01}\{1, 0.1, 0.01\}, and it picks the top edge, 11, at every nn in both worlds. Past the edge, validation picks 33 at n=100n = 100 and 300300 and 1010 at n=1000n = 1000 in the next-state world; then the HMM’s log-loss falls below the indicator CRF’s at n=300n = 300, so the CRF’s log-loss win holds from n=1000n = 1000 on (1.0361.036 against 1.0391.039). Every accuracy ordering is unchanged. The Learning curves tab plots every nn, 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 p(z∣x)p(z \mid x) be a distribution over tag sequences with node marginals γt\gamma_t.

(a) The Viterbi path z∗=arg⁡max⁡zp(z∣x)z^\ast = \arg\max_z p(z \mid x) minimizes the expected sequence loss E[1{z^≠z}]\mathbb E[\mathbf 1\{\hat z \ne z\}].

(b) The posterior-marginal (or minimum-Bayes-risk) decoding z^t=arg⁡max⁡kγt(k)\hat z_t = \arg\max_k \gamma_t(k) minimizes the expected Hamming loss E[∑t1{z^t≠zt}]\mathbb E\big[\sum_t \mathbf 1\{\hat z_t \ne z_t\}\big], the expected number of wrong tags.

Proof.

(a) The expected sequence loss of z^\hat z is 1−p(z^∣x)1 - p(\hat z \mid x), smallest when p(z^∣x)p(\hat z \mid x) is largest. (b) By linearity of expectation the expected Hamming loss is ∑t(1−γt(z^t))\sum_t \big(1 - \gamma_t(\hat z_t)\big), a sum of terms each depending on one z^t\hat z_t, so it is minimized position by position.

∎

Token accuracy is one minus the Hamming loss divided by TT, 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 0.7820.782 of test tokens correctly and decoded by Viterbi 0.7760.776. On the trellis sequence, Viterbi gets 1717 of 2424 tags right and posterior decoding 1919; their expected numbers of correct tags are 16.38416.384 and 16.92816.928. 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 p(z∣x)=∏tp(zt∣zt−1,x)p(z \mid x) = \prod_{t} p(z_t \mid z_{t-1}, x), each factor a softmax logistic regression on features of xx. It has lookahead ww if the factor at tt depends on xx only through x1:t+wx_{1:t+w}.

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 ww and every tt, p(z1:t∣x)=p(z1:t∣x1:t+w)p(z_{1:t} \mid x) = p(z_{1:t} \mid x_{1:t+w}): the marginal of the first tt tags depends on no word after position t+wt + w.

Proof.

p(z1:t∣x)=∑zt+1:T∏s≤Tp(zs∣zs−1,x)p(z_{1:t} \mid x) = \sum_{z_{t+1:T}} \prod_{s \le T} p(z_s \mid z_{s-1}, x). Sum out zTz_T first: only the last factor involves it, and it is a distribution over zTz_T, so it sums to one. Then sum out zT−1z_{T-1}, and so on down to zt+1z_{t+1}. What remains is ∏s≤tp(zs∣zs−1,x)\prod_{s \le t} p(z_s \mid z_{s-1}, x), and by the lookahead assumption each of those factors depends on xx only through x1:s+w⊆x1:t+wx_{1:s+w} \subseteq x_{1:t+w}.

∎

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 w>0w \gt 0, buys back exactly ww words, which Proposition 2 makes precise.

Corollary 2 (A ceiling for posterior decoding).

An MEMM with lookahead ww, decoded by posterior marginals, has expected token accuracy at most that of the Bayes rule z^t=arg⁡max⁡kp(zt=k∣x1:t+w)\hat z_t = \arg\max_k p(z_t = k \mid x_{1:t+w}).

Proof.

By Proposition 2 the MEMM’s marginal for ztz_t, and hence its decision at tt, is a function of x1:t+wx_{1:t+w}. Among all functions of x1:t+wx_{1:t+w}, the Bayes rule maximizes the probability of a correct tag at each tt.

∎

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 (t,k)(t, k) 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 00 or 11, and is trained on 1,0001{,}000 sequences:

world, lookaheadceilingMEMM, posteriorMEMM, Viterbi
well-specified, 00.7430.7430.7350.7350.7580.758
well-specified, 10.7690.7690.7630.7630.7650.765
next-state, 00.5880.5880.5740.5740.5630.563
next-state, 10.6100.6100.5930.5930.5800.580

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 (0.7580.758) rises above it (0.7430.743), as the remark allows. The CRF, whose marginals see the whole sentence, is bounded only by the full Bayes rule, 0.7820.782 there. One word of lookahead recovers about two-thirds of the gap, 0.7690.769. 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 θ=0\theta = 0. For each training pair (xi,zi)(x_i, z_i) in turn, decode z^=arg⁡max⁡zθ⋅F(xi,z)\hat z = \arg\max_z \theta \cdot F(x_i, z) by Viterbi; if z^≠zi\hat z \ne z_i, update θ←θ+F(xi,zi)−F(xi,z^)\theta \leftarrow \theta + F(x_i, z_i) - F(x_i, \hat z). Repeat for several epochs. The averaged perceptron returns the average of θ\theta over every step.

Theorem 5 (The perceptron's mistake bound).

Suppose some unit vector uu separates the training data with margin γ>0\gamma \gt 0, u⋅(F(xi,zi)−F(xi,z))≥γu \cdot \big(F(x_i, z_i) - F(x_i, z)\big) \ge \gamma for every ii and every z≠ziz \ne z_i, and every difference has norm at most RR. Then the perceptron makes at most R2/γ2R^2/\gamma^2 mistakes, however many epochs it runs.

Proof.

Let θk\theta_k be the weights before the kk-th mistake, θ1=0\theta_1 = 0, and suppose that mistake happens on pair ii with decoded path z^\hat z. Then θk+1=θk+Δ\theta_{k+1} = \theta_k + \Delta with Δ=F(xi,zi)−F(xi,z^)\Delta = F(x_i, z_i) - F(x_i, \hat z). First, u⋅θk+1=u⋅θk+u⋅Δ≥u⋅θk+γu \cdot \theta_{k+1} = u \cdot \theta_k + u \cdot \Delta \ge u \cdot \theta_k + \gamma, so u⋅θk+1≥kγu \cdot \theta_{k+1} \ge k\gamma. Second, ∥θk+1∥2=∥θk∥2+2 θk⋅Δ+∥Δ∥2≤∥θk∥2+R2\|\theta_{k+1}\|^2 = \|\theta_k\|^2 + 2\,\theta_k \cdot \Delta + \|\Delta\|^2 \le \|\theta_k\|^2 + R^2, because z^\hat z won the decoding, so θk⋅Δ≤0\theta_k \cdot \Delta \le 0. So ∥θk+1∥2≤kR2\|\theta_{k+1}\|^2 \le kR^2. Since uu is a unit vector, kγ≤u⋅θk+1≤∥θk+1∥≤k Rk\gamma \le u \cdot \theta_{k+1} \le \|\theta_{k+1}\| \le \sqrt k\, R, so k≤R2/γ2k \le R^2/\gamma^2.

∎

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 33 to 2121 as γ\gamma falls from 0.3150.315 to 0.0410.041 (not at every step: 1313, then 1111), while the bound rises from 867867 to 50,70050{,}700. It holds every time, and it is loose by a factor of 121121 to 2,4142{,}414, 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