Search

Search papers and lessons

Conditional Random Field

Level 3 · 13 min read

A conditional random field labels a whole sequence at once by scoring each full labelling, so neighbouring labels can depend on each other.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Classical mechanics
  • Linear algebra
  • Classical models
  • ReadReady to readNot yet

TL;DR

A conditional random field (CRF) is a model that labels every item in a sequence, such as every word in a sentence, by scoring whole labellings at once. Each labelling gets a score that adds up two kinds of evidence: how well each item fits its label, and how well each pair of neighbouring labels fits together. Dividing the exponential of that score by the sum over all labellings gives a probability. It solves the problem of labels that depend on their neighbours, which a plain per-item classifier ignores.

Builds on: Logistic Regression, Markov Chain, Partition Function · Leads to: BiLSTM-CRF tagging

Where it's used

Part-of-speech tagging and named-entity recognition. Given a sentence, a tagger must mark each word as a noun, verb, place name, person name and so on. The label of "Washington" depends on the words around it. A CRF scores whole tag sequences, so a sequence such as "determiner, noun, verb" can be preferred over one that is locally plausible but breaks grammar. Systems for extracting names from news and clinical text have used CRFs for this, often with a neural network supplying the per-word scores.

Image segmentation. A segmentation network assigns a class to every pixel. Its raw predictions are often noisy, with isolated pixels that disagree with their surroundings. A CRF on the pixel grid rewards neighbouring pixels for taking the same label, unless the image shows an edge there, which smooths the output along object boundaries. A pixel grid is a graph rather than a chain, so this CRF is inferred approximately, not with the exact forward recursion described below.

Gene and protein sequence labelling. In biology, a long DNA or protein sequence has regions with different roles, such as coding and non-coding parts. Adjacent positions are strongly related, and a model that reads the labels as a chain can use that. This is one of the classic uses in computational biology, although the exact models vary by study.

How it works

We will tag a two-word phrase, "dogs run", with one of two labels: N (noun) and V (verb). The model has two kinds of numbers. An emission score says how well a word fits a label on its own. A transition score says how well one label fits after another. Here are the numbers, chosen to be easy to add:

WordNV
"dogs" (emission)2.00.5
"run" (emission)0.51.5

The transition scores are 1.0 for going from N to V, and 0 for the other three pairs.

  1. List the labellings. With two words and two labels there are four possible sequences: (N, N), (N, V), (V, N) and (V, V). The model scores each one as a whole.
  2. Add the emission scores. For (N, V): "dogs" as N gives 2.0, and "run" as V gives 1.5. The total is 3.5. Check: the larger number 2.0 is for the more natural reading of "dogs".
  3. Add the transition scores. The pair N then V has transition 1.0, so the score of (N, V) is 3.5 + 1.0 = 4.5. The other three sequences score 2.5 for (N, N), 2.0 for (V, V) and 1.0 for (V, N). Check: the transition adds 1.0 to the pair N, V, which widens its lead over (N, N) from 1.0 to 2.0 in the score.
  4. Exponentiate and normalise. Each score becomes a positive number by taking ee to that power. The four values are about 90.02, 12.18, 7.39 and 2.72. Their sum, the partition function ZZ, is about 112.31.
  5. Read off probabilities. Dividing each value by 112.31 gives P(N, V) about 0.80, P(N, N) about 0.11, P(V, V) about 0.07 and P(V, N) about 0.02. Check: the four numbers add to 1.00.
  6. Pick the best labelling. The most probable sequence is (N, V). The model tags "dogs" as a noun and "run" as a verb, because the neighbouring pair fits and the per-word evidence agrees.
  7. Shortcut for the sum. Listing every labelling is impossible for a long sentence. Instead, add up partial sums one position at a time: first the exponentiated scores of every way to tag "dogs", then, for each label of "run", the sum over the labels of "dogs" that can precede it. For "dogs run" this needs two small sums and gives the same Z≈112.3Z \approx 112.3 as step 4. The math section and Example 2 work it through.
flowchart LR
  S([start]) -->|"dogs N: 2.0"| D1["dogs = N"]
  S -->|"dogs V: 0.5"| D2["dogs = V"]
  D1 -->|"run N: +0.5, N to N: 0"| R1["run = N, total 2.5"]
  D1 -->|"run V: +1.5, N to V: +1.0"| R2["run = V, total 4.5"]
  D2 -->|"run N: +0.5, V to N: 0"| R3["run = N, total 1.0"]
  D2 -->|"run V: +1.5, V to V: 0"| R4["run = V, total 2.0"]

The diagram shows the four labellings as paths through two positions. Each path's total is its labelling score from step 3. Step 4 turns those totals into probabilities.

Two things are worth noticing. Here the transition only widens the margin, because the emissions alone already favour (N, V). In a sentence where the per-word evidence disagrees, the transition is what decides the labels together, and that is the coupling a per-item classifier cannot express. And the four sequences were listed by hand, which is impossible for a long sentence. Step 7 shows how the sum in step 4 is computed quickly.

The math

Let x=(x1,…,xT)\mathbf{x} = (x_1, \dots, x_T) be the sequence of inputs, for example words, and let y=(y1,…,yT)\mathbf{y} = (y_1, \dots, y_T) be a labelling, one label per position. Define the score of a labelling as

s(x,y)=∑t=1Te(yt,x,t)+∑t=2TA(yt−1,yt)s(\mathbf{x}, \mathbf{y}) = \sum_{t=1}^{T} e(y_t, \mathbf{x}, t) + \sum_{t=2}^{T} A(y_{t-1}, y_t)

where e(yt,x,t)e(y_t, \mathbf{x}, t) is the emission score for label yty_t at position tt, and A(a,b)A(a, b) is the transition score for going from label aa to label bb. The probability of a labelling is

P(y∣x)=exp⁡(s(x,y))Z(x),Z(x)=∑y′exp⁡(s(x,y′))P(\mathbf{y} \mid \mathbf{x}) = \frac{\exp\big(s(\mathbf{x}, \mathbf{y})\big)}{Z(\mathbf{x})}, \qquad Z(\mathbf{x}) = \sum_{\mathbf{y}'} \exp\big(s(\mathbf{x}, \mathbf{y}')\big)

The sum for ZZ runs over every possible labelling. ZZ is the partition function from the prerequisite lesson, here for one input sequence.

Step 2 in symbols (emissions). Emission scores are usually linear in features, e(y,x,t)=wy⊤ϕ(x,t)e(y, \mathbf{x}, t) = \mathbf{w}_y^\top \phi(\mathbf{x}, t), where ϕ(x,t)\phi(\mathbf{x}, t) is a feature vector describing the input at position tt. This is the same weighted sum that logistic regression uses, applied separately for each label.

Step 3 in symbols (transitions). The transition scores form a table AA with one row for each previous label and one column for each next label. The worked example used A(N,V)=1.0A(\mathrm{N}, \mathrm{V}) = 1.0 and 00 for the other entries. Because AA is learned, the same table is used at every position.

Step 4 in symbols (normalisation). For the two-word example, the sum has 22=42^2 = 4 terms. For TT words and LL labels it has LTL^T terms, which is huge for real sentences. This is the main computational difficulty, and it is handled in step 7.

Step 7 in symbols (forward recursion). Define αt(y)\alpha_t(y) as the sum of exp⁡\exp of the scores of all partial labellings of the first tt words that end in label yy. Then

α1(y)=exp⁡(e(y,x,1)),αt(y)=exp⁡(e(y,x,t))∑y′αt−1(y′) exp⁡(A(y′,y))\alpha_1(y) = \exp\big(e(y, \mathbf{x}, 1)\big), \qquad \alpha_t(y) = \exp\big(e(y, \mathbf{x}, t)\big) \sum_{y'} \alpha_{t-1}(y')\, \exp\big(A(y', y)\big)

and Z(x)=∑yαT(y)Z(\mathbf{x}) = \sum_y \alpha_T(y). The cost is about TL2T L^2 operations, not LTL^T.

Learning. Training maximises the log-likelihood of the correct labelling y⋆\mathbf{y}^\star for each training sequence, log⁡P(y⋆∣x)=s(x,y⋆)−log⁡Z(x)\log P(\mathbf{y}^\star \mid \mathbf{x}) = s(\mathbf{x}, \mathbf{y}^\star) - \log Z(\mathbf{x}). Its gradient with respect to a weight is the feature count of the correct labelling minus the expected feature count under the model. The expectation is computed with a backward pass that mirrors the forward recursion. This is the same pattern as maximum likelihood for other exponential-family models, with Gradient Descent as the optimiser.

Worked examples

Example
Example 1: score one labelling (tiny)

Use the table from "How it works". Score the labelling (V, N) for "dogs run".

  1. Emission for "dogs" as V: 0.5.
  2. Emission for "run" as N: 0.5.
  3. Sum of emissions: 0.5 + 0.5 = 1.0.
  4. Transition from V to N: 0 (the table gives 1.0 only for N to V).
  5. Total score: 1.0 + 0 = 1.0.

The score is 1.0, the lowest of the four, which fits the intuition that a verb followed by a noun is the least likely reading in this table.

Example
Example 2: the partition function by forward recursion (standard)

Compute ZZ for "dogs run" without listing all four labellings.

  1. Start: α1(N)=exp⁡(2.0)≈7.389\alpha_1(\mathrm{N}) = \exp(2.0) \approx 7.389.
  2. Start: α1(V)=exp⁡(0.5)≈1.649\alpha_1(\mathrm{V}) = \exp(0.5) \approx 1.649.
  3. Position 2 for N: the emission is 0.5, so the prefactor is exp⁡(0.5)≈1.649\exp(0.5) \approx 1.649.
  4. Inside the bracket for N: the previous label N has transition 0 to N, and V has transition 0 to N. So the bracket is 7.389⋅1+1.649⋅1=9.0387.389 \cdot 1 + 1.649 \cdot 1 = 9.038.
  5. So α2(N)=1.649×9.038≈14.90\alpha_2(\mathrm{N}) = 1.649 \times 9.038 \approx 14.90.
  6. Position 2 for V: the emission is 1.5, so the prefactor is exp⁡(1.5)≈4.482\exp(1.5) \approx 4.482.
  7. Inside the bracket for V: from N the transition is 1.0, so the term is 7.389⋅e1.0≈7.389×2.718=20.097.389 \cdot e^{1.0} \approx 7.389 \times 2.718 = 20.09. From V the transition is 0, so the term is 1.6491.649. The bracket is 20.09+1.649=21.7420.09 + 1.649 = 21.74.
  8. So α2(V)=4.482×21.74≈97.4\alpha_2(\mathrm{V}) = 4.482 \times 21.74 \approx 97.4.
  9. Z=α2(N)+α2(V)≈14.90+97.4=112.3Z = \alpha_2(\mathrm{N}) + \alpha_2(\mathrm{V}) \approx 14.90 + 97.4 = 112.3.

This matches the brute-force sum in "How it works". At position 2 the recursion needed two bracket sums, instead of listing all four full sequences.

Example
Example 3: tagging 'the dog barks' (realistic)

Tag three words with DET (determiner), N (noun) and V (verb). Emission scores:

WordDETNV
"the"2.00-1.0
"dog"-1.02.00.5
"barks"-1.00.52.0

Transitions: DET to N is 1.0, N to V is 1.0, and all other pairs are 0.

  1. Take the labelling DET, N, V. Emissions: 2.0 + 2.0 + 2.0 = 6.0.
  2. Transitions: DET to N gives 1.0, N to V gives 1.0. Total transitions 2.0.
  3. Score: 6.0 + 2.0 = 8.0.
  4. Check that no labelling can beat this. Each word's best emission is 2.0, so emissions are at most 6.0, and there are only two transitions, each at most 1.0, so transitions are at most 2.0. The maximum possible is 8.0, which DET, N, V achieves.
  5. Compare DET, N, N: emissions 2.0 + 2.0 + 0.5 = 4.5, transitions 1.0 + 0 = 1.0, score 5.5.
  6. So the most probable tagging is DET, N, V: "the" is a determiner, "dog" a noun, "barks" a verb.

Try it: Suppose the transition from N to V is changed to -2.0, and everything else stays the same. Which labelling now has the highest score? Answer: DET, N, N. Its score is still 5.5. DET, N, V drops to 6.0 + (1.0 - 2.0) = 5.0, and DET, N, N wins because the penalty on the N to V step makes "barks" a noun instead.

Common mistakes and tradeoffs

It is tempting to think a CRF is a neural network. In fact it is a log-linear model: a weighted sum of features, a normalising constant and no hidden layers. It is often placed on top of a feedforward or recurrent network, which supplies the emission scores, and the CRF adds the transition table and the whole-sequence normalisation. The two parts do different jobs.

It is tempting to think you can tag each word with a softmax and get the same result. In fact an independent Softmax per word cannot enforce that a determiner is followed by a noun, because each decision ignores the others. The CRF normalises once over whole sequences, which is what lets transitions matter.

It is tempting to think that the sum over all labellings is hopeless. In fact the forward recursion makes it cost roughly TL2T L^2 operations, and the same trick gives the most probable sequence through the Viterbi algorithm.

When to use it. Use a CRF when the labels of neighbouring items are strongly linked and the output must be a consistent sequence or grid, such as tagging, segmentation or chunking.

When not to use it. If each item can be labelled independently, a per-item classifier is simpler and faster. A CRF also makes training slower, because every step needs the forward and backward passes. Very large models that already read the whole sequence, such as transformers, can learn the label dependencies themselves, and a separate CRF layer may add little.

Alternatives. A Hidden Markov Model models the same chain generatively, which is easier to train with counts but restricts the features. Greedy per-item decoding is the cheapest alternative, and Belief Propagation generalises the forward and backward idea to graphs that are not chains, such as the factor graphs that a pixel-grid CRF would use.

History

Hidden Markov models, which describe labelled sequences generatively, were the standard sequence model for speech and text in the 1980s and 1990s. Their limits were that the features had to be simple and that each observation depended only on its own state.

In 2001, John Lafferty, Andrew McCallum and Fernando Pereira introduced conditional random fields for labelling sequences. Their key point was that a discriminative model, which models the labels given the input, could use overlapping features of the whole input without needing to model the input itself. The model caught on in language processing because it gave better accuracy than hidden Markov models on tagging tasks, and because training was a convex problem with a clear optimum.

Neural networks later supplied the emission scores, and a CRF layer became a common output layer on top of recurrent networks for named-entity tagging.

Recap

  • A CRF scores each full labelling by adding per-item emission scores and per-pair transition scores.
  • Probabilities come from exponentiating the score and dividing by the partition function ZZ, the sum over all labellings.
  • The forward recursion computes ZZ in about TL2T L^2 steps, which makes exact training and decoding practical.
  • Training maximises the log-likelihood, whose gradient is the difference between the correct and expected features.
  • Read next: the BiLSTM-CRF paper, which puts a CRF layer on top of a neural tagger, and the Viterbi algorithm for decoding.

Check yourself

QuestionIn one sentence, what does a CRF add that a per-item classifier does not?Show answer

It scores whole labellings, including transition scores between neighbouring labels, and normalises over all of them. This lets the choice of one label affect the others, so the output can be a consistent sequence.

QuestionUsing the table from 'How it works', with transitions N to V = 1.0 and 0 elsewhere, what is the score of (N, N) for 'dogs run'?Show answer

Emissions: 2.0 for 'dogs' as N, plus 0.5 for 'run' as N, total 2.5. Transition N to N is 0. The score is 2.5.

QuestionWhy does the forward recursion make the partition function practical, when the number of labellings grows as L to the power T?Show answer

It sums partial scores position by position, reusing the sums for earlier positions. Each position needs only L values, and each value needs L products, so the total cost is about T times L squared rather than L to the power T. Without this reuse, the sum over all labellings would be too slow for real sentences.

QuestionA tagger built from a strong transformer already reads the whole sentence. Should you add a CRF output layer? Give a reason for your answer.Show answer

Not necessarily. The transformer can learn label dependencies from context, so a CRF may add little, and it costs extra training time. Test the tagger with and without the CRF on held-out data, and keep it only if it improves the consistency of the output or the accuracy.

Sources