A conditional random field (CRF) is a discriminative undirected graphical model that defines the conditional probability of a set of output labels given an observed input, P(y | x), while modeling dependencies among the labels themselves. Among probabilistic models in artificial intelligence, it is the classic tool for structured prediction, where neighboring outputs constrain each other, as in part-of-speech tagging, named entity recognition or image segmentation.
Introduced by Lafferty, McCallum and Pereira in 2001, the CRF combines the rich, overlapping features of logistic regression with the sequence structure of a hidden Markov model. Because it never models the distribution of the input, it avoids the strong independence assumptions that generative models require.
How a conditional random field models label dependencies
A CRF assigns a score to every complete labeling of the input and normalizes those scores into probabilities. The score is a weighted sum of feature functions, each of which looks at a small group of labels (a clique) together with any part of the input. The probability is the exponential of that score divided by the partition function Z(x), the sum over all possible labelings.
In the most common form, the linear-chain CRF, each feature function sees the current label, the previous label and the whole input sequence. Two kinds of features dominate: emission-style features link a label to input properties such as the word, its suffix or capitalization, and transition features score how plausible one label is after another. The table below summarizes the main components.
| Component | Role | Typical example |
|---|---|---|
| Feature functions | Describe label and input patterns | Word ends in -ing and tag is VBG |
| Weights | Set the importance of each feature | Learned real numbers, often millions |
| Transition scores | Score adjacent label pairs | B-PER followed by I-PER is favored |
| Partition function | Normalizes scores into probabilities | Computed by the forward algorithm |
| Decoding | Finds the most likely labeling | Viterbi algorithm |
Because normalization happens over the whole sequence at once, a CRF is a globally normalized model. This property is the key to its advantage over locally normalized alternatives.
Training and inference
CRF weights are learned by maximizing the conditional log-likelihood of the training labels, usually with L2 regularization to prevent overfitting. The objective is convex for a linear-chain CRF, so optimizers such as L-BFGS or stochastic gradient descent reach the global optimum. Each gradient step requires expected feature counts, which the forward-backward algorithm computes efficiently.
Inference cost depends heavily on the graph structure, as the table below shows.
| Structure | Exact inference | Typical method |
|---|---|---|
| Linear chain | Yes, in O(nL²) time | Forward-backward and Viterbi |
| Tree-structured | Yes | Belief propagation |
| Higher-order chain | Yes, but cost grows as L to the order plus one | Extended dynamic programming |
| General graph or grid | Usually intractable | Loopy belief propagation, mean-field, graph cuts |
In the expression O(nL²), n is the sequence length and L the number of labels. For tasks with hundreds of labels, the quadratic term becomes the main computational bottleneck, and practitioners prune transitions or use beam search.
How a CRF compares with related models
The CRF sits at the intersection of discriminative classifiers and graphical models. A hidden Markov model is its generative counterpart, a maximum entropy Markov model is its locally normalized predecessor, and a Markov random field is the general undirected framework of which a CRF is the conditional version.
| Model | Type | Normalization | Key limitation |
|---|---|---|---|
| Hidden Markov model | Generative, P(x, y) | Joint | Assumes observations are independent given states |
| Maximum entropy Markov model | Discriminative, local | Per position | Suffers from label bias |
| Linear-chain CRF | Discriminative, global | Whole sequence | Slower training, quadratic in labels |
| Markov random field | Generative, undirected | Joint | Must model the input distribution |
The label bias problem is the main reason CRFs replaced maximum entropy Markov models. When each state normalizes its outgoing probabilities locally, states with few successors ignore the evidence in the observation, whereas global normalization lets later evidence override earlier choices.
Where conditional random fields are used
CRFs fit any task in which outputs are interdependent and inputs are richly described. In natural language processing they dominated named entity recognition, chunking and part-of-speech tagging for about a decade. In computer vision, dense CRFs refine semantic segmentation by encouraging nearby pixels with similar color to share a label.
In current practice the CRF often appears as a structured output layer on top of a neural encoder. A BiLSTM-CRF or a transformer with a CRF head lets the network learn features while the CRF enforces valid label transitions, for example that an I-ORG tag cannot follow an O tag in the BIO scheme. Other uses include gene prediction, shallow parsing of addresses and information extraction from documents.
- Choose a CRF when label consistency matters and data are limited.
- Add a CRF layer to a neural tagger when invalid tag sequences appear in output.
- Skip the CRF when a large pretrained transformer already yields consistent labels and speed matters more.
Limitations and practical pitfalls
The CRF is powerful but not free of costs. Training is slower than independent classifiers because every gradient step runs dynamic programming over each sequence, and models with arbitrary graph structure usually need approximate inference without accuracy guarantees.
| Problem | Cause | Remedy |
|---|---|---|
| Overfitting on sparse features | Millions of rare features | Stronger L1 or L2 regularization |
| Slow training | Many labels or long sequences | Prune transitions, use stochastic gradients |
| Gains vanish with transformers | Encoder already captures context | Measure with and without the CRF layer |
| Poor calibration on new domains | Feature distribution shift | Retrain or adapt on in-domain data |
A frequent misconception is that a CRF captures long-range dependencies. A first-order linear-chain CRF directly links only adjacent labels; longer interactions require higher-order or skip-chain variants, which raise inference cost sharply.
The short version
A conditional random field labels the parts while looking at the whole. Think of tagging each word in a sentence as a name, a place or nothing. Each word gives clues. The neighboring tags give clues too.
A CRF weighs both kinds of clues together. It then picks the most sensible set of labels for the entire sentence, not one word at a time. The key takeaway is that it keeps labels consistent with each other.
Where it makes a difference
A logistics company needs to extract street, house number, postal code and city from free-text delivery addresses entered by customers. A simple per-token classifier reaches decent accuracy but often produces impossible sequences, such as a postal code split in the middle of a street name.
The data team adds a linear-chain CRF layer on top of a small transformer encoder and trains it on about 20,000 hand-labeled addresses. The CRF learns which label transitions are plausible, so the street name now stays in one continuous block and the postal code is recognized as a unit. The share of addresses parsed without any manual correction rises noticeably, and fewer parcels are routed to the wrong depot. The added decoding cost is only a few milliseconds per address, which is negligible for the batch pipeline.