Core ML2001intermediate12 min read

Conditional Random Fields: Probabilistic Models for Segmenting and Labeling Sequence Data

حقول مارکوف العشوائية الشرطية: نماذج احتمالية لتجزئة البيانات التسلسلية ووسمها

Lafferty, J. · McCallum, A. · Pereira, F. — ICML

The problem

By 2001, — assigning a tag to every element in a (like part-of-speech tags to words) — relied on two imperfect families. Generative models like HMMs assumed observations were independent given the state and couldn't use overlapping, arbitrary features of the input. Discriminative directed models like MEMMs could use rich features but suffered from the problem: states with few outgoing transitions effectively ignored the input, because per-state made transitions compete only against each other rather than against the entire label space.

The contribution

Conditional Random Fields (CRFs): undirected graphical models that define P(y|x) — the conditional of an entire label sequence y given the full observation sequence x — using a single global normalization. This solves the label bias problem because every transition competes against all other transitions globally. CRFs combine the best of both worlds: they use arbitrary, overlapping features of the input (like discriminative models) while maintaining consistent global sequence-level probabilities (avoiding label bias). For linear chains, exact uses the , and the algorithm finds the best label sequence — the same dynamic programming tools as HMMs, just with different potential functions.

The impact

CRFs became the dominant framework for structured prediction in NLP for over a decade. They powered state-of-the-art systems for , POS tagging, shallow parsing, and . The BiLSTM-CRF architecture — neural features fed into a CRF output — remained the gold standard for sequence labeling well into the deep learning era. CRFs also extended beyond NLP into (DeepLab for ) and bioinformatics. Even today, CRF layers appear inside modern architectures like ELMo and BERT-based taggers whenever label dependencies matter.

Imagine you're assembling a jigsaw puzzle of a sentence, where each piece is a word and each piece must be painted one color — its part-of-speech tag. An HMM paints each piece while blindfolded, seeing only the current piece's shape and guessing from the previous piece's color. A MEMM removes the blindfold, but paints each piece independently at its own little table — if a table has only one paint jar, it always uses that jar regardless of what the piece looks like.

A CRF seats you at one long table with the entire puzzle spread out. You see every piece at once and choose colors for the whole sequence together, so a color choice at position 5 can be influenced by the shape of the piece at position 50. The entire coloring is scored globally, and the best one wins.

The problem: when local decisions ruin global consistency

Sequence labeling is one of the most fundamental tasks in NLP: given a sentence, assign a tag to every word. Is "bank" a noun or a verb? Is "Washington" a person or a place? The answer depends on context — and crucially, on what the neighboring tags are.

Before CRFs, two approaches dominated:

Hidden Markov Models are generative: they model the joint probability P(x, y) of observations and labels. But HMMs make a strong independence assumption — each observation depends only on its own label. This means you can't use features like "the previous word is 'the'" or "this word is capitalized AND the next word is a verb." Real language is full of such overlapping, correlated cues.

Maximum Entropy Markov Models (MEMMs) fix the problem: they're discriminative and can use arbitrary features. But they introduce a worse problem — label bias. Because each state normalizes its outgoing transitions independently, states with fewer successors effectively ignore the input. Imagine a highway exit with only one ramp: no matter what the road sign says, you take that ramp. The model's predictions become disconnected from the actual observations.

Open in Lab
Watch how the MEMM ignores the observation when a state has only one successor. The CRF considers the full sequence and gets it right.
The demo wakes as you arrive…

The idea: one global score for the whole sequence

The key insight of CRFs is deceptively simple: instead of making a local decision at each position and normalizing per state, define a single score for the entire label sequence and normalize once over all possible label sequences. This is the difference between a locally normalized model (MEMM) and a globally normalized model (CRF).

A CRF defines the conditional probability of a label sequence y given an observation sequence x as:

P(y∣x)=1Z(x)exp⁡ ⁣(∑t=1T∑kλkfk(yt−1,yt,x,t))P(\mathbf{y} | \mathbf{x}) = \frac{1}{Z(\mathbf{x})} \exp\!\left(\sum_{t=1}^{T} \sum_{k} \lambda_k f_k(y_{t-1}, y_t, \mathbf{x}, t)\right)
The CRF probability — one global normalization for the entire sequence — f_k are feature functions that look at the current label y_t, the previous label y_{t-1}, and the entire observation x. λ_k are learned weights. Z(x) is the partition function that sums over all possible label sequences — the single global normalizer that makes this a valid probability.

Think of it like a panel of judges scoring an ice skating routine. An HMM judge scores each element in isolation. An MEMM judge watches the full routine but writes each score on a separate card that's immediately finalized. A CRF judge watches the full routine, writes a single score for the whole performance, and that score reflects how well all the elements fit together.

Feature functions: the eyes of the model

The power of CRFs lies in their feature functions. Each fk(yt−1,yt,x,t)f_k(y_{t-1}, y_t, \mathbf{x}, t) is a binary or real-valued function that captures a specific pattern. For example:

  • "Is the current word capitalized AND the label is PROPER-NOUN?" → 1 or 0
  • "Is the previous label DETERMINER and the current label NOUN?" → 1 or 0
  • "Does the current word end in '-ing' AND the label is VERB?" → 1 or 0
  • "Is the current word in a gazetteer of city names AND the label is LOCATION?" → 1 or 0

Each feature has a learned λk\lambda_k. Positive weights encourage patterns; negative weights discourage them. The total score for a label sequence is the weighted sum of all features fired across all positions — and the Z(x) ensures these scores become valid probabilities.

This is exactly what makes CRFs strictly more powerful than HMMs for feature-rich tasks: you can throw in any feature you can compute from the input, without worrying about independence assumptions.

Open in Lab
Toggle features on and off to see how they change the CRF's label scores. Notice how overlapping features give richer signal than any single feature alone.
The demo wakes as you arrive…

Label bias: the flaw CRFs were built to fix

The label bias problem is subtle but devastating. In an MEMM, each state normalizes its outgoing transition probabilities to sum to 1. This sounds harmless, but consider a state with only one outgoing transition: that transition gets probability 1.0 no matter what the observation is. The model literally cannot use the input to change its mind at that state.

More generally, states with fewer outgoing transitions have an unfair advantage: their probability mass doesn't get split as many ways. The result is that the globally optimal path can be dominated by these "low-branching" states, even when the input evidence strongly contradicts them.

CRFs solve this by removing per-state normalization entirely. The score of a label sequence is an unnormalized sum of feature weights; only the final division by Z(x) turns scores into probabilities. Every transition competes against every other possible label sequence globally, so no state can hoard probability mass.

Generative vs. discriminative: where CRFs sit

There is a clean parallel between pairs of models. is the discriminative counterpart of Naive Bayes: both handle single classifications, but logistic regression models P(y|x) directly while Naive Bayes models the joint P(x,y).

CRFs extend this parallel to sequences. An HMM is Naive Bayes stretched over a chain: generative, with independence assumptions. A linear-chain CRF is logistic regression stretched over a chain: discriminative, with no independence assumptions on the input.

Just as logistic regression consistently outperforms Naive Bayes when you have enough data, CRFs consistently outperform HMMs on feature-rich sequence labeling tasks.

Open in Lab
Click each model to see its properties. Notice the parallel: Naive Bayes → Logistic Regression mirrors HMM → CRF.
The demo wakes as you arrive…

The partition function: making scores into probabilities

The partition function Z(x)Z(\mathbf{x}) is the denominator that turns raw scores into valid probabilities. It sums the exponentiated scores over every possible label sequence:

Z(x)=∑y′exp⁡ ⁣(∑t=1T∑kλkfk(yt−1′,yt′,x,t))Z(\mathbf{x}) = \sum_{\mathbf{y'}} \exp\!\left( \sum_{t=1}^{T} \sum_k \lambda_k f_k(y'_{t-1}, y'_t, \mathbf{x}, t)\right)
The partition function — summing over all possible label sequences — If there are L possible labels and T positions, the naive sum has L^T terms — astronomically large. But for linear-chain CRFs, the forward-backward algorithm computes Z(x) in O(T × L²) time using dynamic programming, exactly as in HMMs.

Think of the partition function as a normalizing constant that answers: "across every conceivable way to label this sentence, what is the total unnormalized weight?" Once you know that total, you can say what fraction belongs to any particular labeling.

Computing Z(x) efficiently is essential: it appears in both the probability computation and the during . The forward algorithm builds it up position by position, reusing intermediate results — each position needs only the accumulated scores from the previous position, times the local potential.

Open in Lab
Watch the forward algorithm accumulate scores position by position. The final sum across all ending states gives Z(x).
The demo wakes as you arrive…

Inference: finding the best label sequence

Two inference problems matter in CRFs:

1. Computing marginals — "what is the probability that position t has label j?" This is needed for the gradient during training. The forward-backward algorithm, a message-passing scheme over the linear chain, solves this in O(T × L²) time.

2. Finding the best sequence — "which complete label sequence has the highest probability?" The Viterbi algorithm answers this, again in O(T × L²). It's the same dynamic programming idea: walk forward through the chain, and at each position keep only the best-scoring partial path ending in each label. Then trace back to recover the full best sequence.

Both algorithms are direct adaptations of the HMM versions. The only difference is the potential functions: HMMs use P(xt∣yt)×P(yt∣yt−1)P(x_t|y_t) \times P(y_t|y_{t-1}), while CRFs use exp⁡(∑kλkfk(yt−1,yt,x,t))\exp(\sum_k \lambda_k f_k(y_{t-1}, y_t, \mathbf{x}, t)).

Open in Lab
Step through the Viterbi algorithm on a short sentence. At each position, the best incoming path is kept (solid) and others are pruned (dashed).
The demo wakes as you arrive…

Training: maximum conditional likelihood

CRF training maximizes the conditional log-likelihood of the correct label sequences in the training data. For a training pair (x,y)(\mathbf{x}, \mathbf{y}), the objective is:

L(λ)=∑t∑kλkfk(yt−1,yt,x,t)−log⁡Z(x)\mathcal{L}(\boldsymbol{\lambda}) = \sum_{t} \sum_{k} \lambda_k f_k(y_{t-1}, y_t, \mathbf{x}, t) - \log Z(\mathbf{x})
Conditional log-likelihood — what CRF training maximizes — The first term rewards the correct labeling's score; the second term (log Z) penalizes all other possible labelings. The gradient has a beautiful form: observed feature counts minus expected feature counts under the model. When the model perfectly matches the data, the gradient is zero.

The gradient takes a clean, intuitive form: ∂L∂λk=∑tfk(yt−1,yt,x,t)⏟observed count−∑t∑y′,y′′fk(y′,y′′,x,t) P(y′,y′′∣x)⏟expected count\frac{\partial \mathcal{L}}{\partial \lambda_k} = \underbrace{\sum_t f_k(y_{t-1}, y_t, \mathbf{x}, t)}_{\text{observed count}} - \underbrace{\sum_t \sum_{y', y''} f_k(y', y'', \mathbf{x}, t)\, P(y', y'' | \mathbf{x})}_{\text{expected count}} This is a recurring theme in : the gradient pushes the model's expected statistics toward the empirical statistics. Training converges when the model's predictions match reality on average.

The original paper used iterative scaling for ; modern implementations use L-BFGS or , which converge much faster in practice.

The same idea in code

Linear-chain CRF — forward algorithm and Viterbi decodingpython

Simplified to show the idea — not the real implementation.

import numpy as np

def crf_forward(emissions, transitions):
    """Forward algorithm: compute log Z(x).
    emissions:   (T, L) — score for each label at each position
    transitions: (L, L) — score for label i → label j
    Returns: log Z(x), the log partition function.
    """
    T, L = emissions.shape
    alpha = emissions[0]                  # initialize with first position
    for t in range(1, T):
        # alpha[i] + transitions[i,j] + emissions[t,j] for all (i,j)
        alpha = np.logaddexp.reduce(
            alpha[:, None] + transitions + emissions[t][None, :],
            axis=0
        )
    return np.logaddexp.reduce(alpha)      # sum over final states

def crf_viterbi(emissions, transitions):
    """Viterbi: find the best label sequence.
    Returns: best score, best label sequence (as list of ints).
    """
    T, L = emissions.shape
    scores = emissions[0]
    backpointers = []
    for t in range(1, T):
        candidates = scores[:, None] + transitions + emissions[t][None, :]
        scores = candidates.max(axis=0)
        backpointers.append(candidates.argmax(axis=0))
    # Trace back
    best = [scores.argmax()]
    for bp in reversed(backpointers):
        best.append(bp[best[-1]])
    return scores.max(), list(reversed(best))

# Example: 3 positions, 2 labels
emissions = np.array([[1.0, 0.5], [0.3, 1.2], [0.8, 0.1]])
transitions = np.array([[0.7, 0.3], [0.4, 0.6]])
log_Z = crf_forward(emissions, transitions)
best_score, best_path = crf_viterbi(emissions, transitions)
print(f"log Z(x) = {log_Z:.3f}")
print(f"Best path: {best_path}, score: {best_score:.3f}")

HMM vs. MEMM vs. CRF: side by side

Open in Lab
Compare the three models' predictions on the same sentence. Toggle the observation to see how each model responds.
The demo wakes as you arrive…

Why CRFs changed everything

CRFs became the dominant approach for structured prediction in NLP for well over a decade. Almost every winning system for named entity recognition, , shallow parsing, and information extraction from 2001 to 2015 used a CRF — either standalone with handcrafted features, or as an output layer on top of neural feature extractors.

The BiLSTM-CRF architecture deserves special mention. By feeding learned neural representations from a bidirectional LSTM into a CRF output layer, researchers got the best of both worlds: deep features from the and consistent sequential predictions from the CRF. This architecture dominated NER benchmarks for years.

Beyond NLP, CRFs extended to computer vision — most notably in DeepLab, where a CRF refines pixel-level predictions from a to produce sharp, coherent segmentation boundaries. In bioinformatics, CRFs model gene structure and protein secondary structure.

Even in the era of large language models, the CRF idea lives on. Whenever a system needs structured, consistent output labels — not just independent per-token predictions — the CRF principle of global normalization remains relevant.

  1. 2001

    CRF paper published (ICML)

    Lafferty, McCallum, and Pereira introduce CRFs, solving the label bias problem and establishing the global normalization principle for sequence labeling.

  2. 2003

    CRFs dominate NLP benchmarks

    CRFs with handcrafted features become state-of-the-art for NER, POS tagging, and shallow parsing. CRFsuite and Mallet become standard tools.

  3. 2011

    CRFs enter computer vision

    Dense CRFs applied to semantic segmentation, later integrated into DeepLab. Pixel labels are treated as a random field conditioned on the image.

  4. 2015

    BiLSTM-CRF architecture

    Huang, Xu, and Yu combine bidirectional LSTMs with a CRF output layer, creating the dominant architecture for neural sequence labeling.

  5. 2018

    ELMo + CRF

    Peters et al. show that deep contextualized word representations (ELMo) fed into a BiLSTM-CRF achieve new state-of-the-art across multiple NLP tasks.

The CRF graphical model at a glance

Open in Lab
Click any node to see how it connects to features and neighboring labels. The undirected edges reflect the CRF's global scoring — no arrows, no direction bias.
The demo wakes as you arrive…

CitationLafferty, McCallum, Pereira. Conditional Random Fields: Probabilistic Models for Segmenting and Labeling Sequence Data. ICML, 2001.

Terms in this paper