Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Label the whole sequence, using any clue you like
An HMM describes how each reading is generated from the mode, so it can only use features it knows how to generate, usually just the current reading. A conditional random field (CRF) skips the generative story. It scores a whole sequence of labels from whatever features help: the current reading, its neighbours, how fast it is changing. It adds a bonus or penalty for each pair of neighbouring labels, and picks the best-scoring labelling. It is softmax regression for sequences.
| path | score | P |
|---|---|---|
| NNN | 2.00 | 0.120 |
| NNF | 2.50 | 0.198 |
| NFN | 0.40 | 0.024 |
| NFF | 2.90 | 0.295 |
| FNN | 0.00 | 0.016 |
| FNF | 0.50 | 0.027 |
| FFN | 0.40 | 0.024 |
| FFF | 2.90 | 0.295 |
Segmenting telemetry into phases, labelling each frame of a video or each word of an anomaly report, and tagging events in logs are all sequence labelling. CRFs (and CRF layers on top of neural networks) give globally consistent labels while using rich, hand-designed or learned features.
- 1. A CRF models…
- 2. Transition scores in a CRF…
- 3. A CRF is to an HMM as…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.Scoring every path by hand
There are two frames, with labels N (nominal) and F (fault). The unary scores for F are −1 (frame 1) and +2 (frame 2), and 0 for N. Keeping the same label earns +1.5.
| Path | Unary | Transition | Score | P = e^score/Z |
|---|---|---|---|---|
| N N | 0 + 0 | 1.5 | 1.5 | 0.184 |
| N F | 0 + 2 | 0 | 2.0 | 0.303 |
| F N | −1 + 0 | 0 | −1.0 | 0.015 |
| F F | −1 + 2 | 1.5 | 2.5 | 0.499 |
Z = e^1.5 + e^2 + e^−1 + e^2.5 = 24.42, so log Z = 3.195.
The best labelling is F F. Frame 1’s mild evidence against a fault is overruled by frame 2’s strong evidence plus the reward for consistency. Without the transition reward, the answer would be N F.
The steps in plain English:
- Design features for each position (current, previous and next readings; changes; flags). Each label has a weight per feature.
- Add a K × K table of transition scores.
- The probability of a labelling is the exponential of its total score, divided by the sum over all labellings (computed by the forward algorithm).
- Train: adjust weights to raise the probability of the true labellings, with an L2 penalty. The gradient is “feature counts in the true labels − expected counts under the model”.
- Decode with Viterbi (best whole path), or with forward–backward marginals (per-frame probabilities).
- 1. Score of path F F in the example?
- 2. Z sums over…
- 3. Without the transition reward, the best path is…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.The model and its training
Model: P(y | x) = exp(Σ_t wᵀφ(x, t, y_t) + Σ_t T[y_(t−1), y_t])/Z(x). The features φ may look at the whole input x, overlapping freely.
Partition function: log Z(x) by the forward recursion in log space, a_t(j) = logsumexp over i of [a_(t−1)(i) + T[i, j]] + U_t(j). The cost is O(TK²).
Conditional log-likelihood: ℓ(w, T) = Σₙ [score(yⁿ | xⁿ) − log Z(xⁿ)] − (λ/2)‖θ‖².
It is concave, so there is one global optimum. The gradient for a weight is (observed feature count) − (expected feature count under the model), with the expectations from forward–backward marginals. For transitions, the expected counts are the edge marginals ξ_t(i, j).
Optimisation: L-BFGS for small and medium problems, SGD or Adam for large ones.
Decoding: Viterbi (MAP path) or posterior marginals, as for HMMs.
import sklearn_crfsuite # CRFsuite wrapper
crf = sklearn_crfsuite.CRF(algorithm="lbfgs", c2=0.1, max_iterations=100, all_possible_transitions=True)
crf.fit(X_train, y_train) # X: list of sequences of feature dicts per position
crf.predict(X_test); crf.predict_marginals(X_test)
# neural: a CRF layer on top of a BiLSTM/transformer (e.g. torchcrf.CRF)Use it when labels in a sequence depend on each other, and you have labelled sequences plus informative, overlapping features. Prefer an HMM when labels are scarce, when you need to learn from unlabelled data, or when the generative model is close to right (exercise 2).
- 1. The CRF log-likelihood gradient is…
- 2. The CRF training objective is…
- 3. In CRFsuite, c2 is…
Level 3: Advanced
★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.Theory and comparisons
Generative versus discriminative sequence models.
- An HMM maximises P(x, y) and must model P(x | y). That restricts it to features it can generate, usually assumed independent.
- A CRF maximises P(y | x), so features can overlap and look anywhere in x, at the cost of needing labelled sequences and more data.
This mirrors naive Bayes versus logistic regression (Sutton and McCallum, 2012): with a nearly correct generative model, the HMM is as good and more data-efficient.
MEMMs and label bias. Maximum-entropy Markov models normalise locally at each step: P(y_t | y_(t−1), x). States with few outgoing transitions then pass on probability mass regardless of the observation (the label-bias problem). CRFs normalise globally over whole sequences, which fixes it (Lafferty, McCallum and Pereira, 2001).
Beyond linear chains.
- Higher-order and semi-Markov CRFs, and grid CRFs for images (dense CRFs for segmentation).
- General graphs make inference intractable, so they need approximate methods (loopy belief propagation, mean field).
Neural CRFs. A BiLSTM-CRF or transformer-CRF learns φ automatically and keeps the transition layer for structured output. This was standard for named-entity recognition before large pretrained models.
Interview questions.
- Why can a CRF use the next observation as a feature but an HMM cannot (easily)? A CRF only conditions on x, so any function of x is allowed. An HMM must generate each observation from its own state.
- What does Z cost? O(TK²) by the forward algorithm. Without dynamic programming it would be Kᵀ.
- 1. The label-bias problem affects…
- 2. A CRF can use features of the next observation because…
- 3. Grid CRFs with loops require…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.Labelling operating modes: an honest comparison
History.
- Lafferty, McCallum and Pereira (2001) introduced CRFs to fix the label bias of MEMMs (McCallum et al., 2000).
- Sha and Pereira (2003) showed fast training with L-BFGS for shallow parsing.
- CRFs dominated named-entity recognition and part-of-speech tagging through the 2000s.
- Lample et al. (2016) popularised BiLSTM-CRF models.
- Dense CRFs (Krähenbühl and Koltun, 2011) refined semantic segmentation.
Exercise 1. log Z and the Viterbi path match brute-force enumeration, and the analytic gradient matches finite differences. Trained on 10 sticky sequences, the CRF learns positive self-transition scores. Its Viterbi accuracy is 0.821, against 0.578 for unary-only decoding.
Exercise 2: idle, slew or thrust. Setup: slew and thrust share a mean rate; thrust differs only by stronger vibration. The CRF gets window and jump features; the HMM gets only the binned current reading. 2 repetitions, 15 test passes.
| Labelled training passes | HMM (supervised counts) | CRF (window + jump features) | Per-frame, no sequence model |
|---|---|---|---|
| 5 | 0.905 | 0.904 | 0.687 |
| 20 | 0.911 | 0.901 | 0.722 |
- Sequence modelling is what matters: both gain about 20 points over per-frame classification.
- The richer CRF features did not beat the HMM here. The HMM’s emission model on binned readings already captures thrust’s wider spread, and its dynamics integrate that evidence over time. The CRF adds 4 × 6 features per label, which it must learn from a few hundred frames.
- In pilot runs with a weaker vibration difference, the gap was within ±3 points either way, depending on the seed. So no consistent winner on this problem.
- Lesson: a discriminative model with fancier features is not automatically better. When a generative model fits the physics, it is as accurate and needs less data. CRFs pay off with genuinely informative, non-generative features and plenty of labelled sequences, as in text.
CRFs in AI, robotics and aerospace
- Telemetry segmentation: phase and mode labelling with hand-crafted window features.
- Text information extraction: extracting components, part numbers and failure modes from anomaly reports.
- Semantic segmentation: dense CRFs refining per-pixel labels for terrain maps.
- Neural structured prediction: CRF output layers on sequence encoders.
References
- J. Lafferty, A. McCallum, F. Pereira (2001). “Conditional random fields: probabilistic models for segmenting and labeling sequence data.” ICML.
- C. Sutton, A. McCallum (2012). “An introduction to conditional random fields.” Foundations and Trends in Machine Learning 4(4).
- F. Sha, F. Pereira (2003). “Shallow parsing with conditional random fields.” NAACL.
- G. Lample, M. Ballesteros, S. Subramanian, K. Kawakami, C. Dyer (2016). “Neural architectures for named entity recognition.” NAACL.
- P. Krähenbühl, V. Koltun (2011). “Efficient inference in fully connected CRFs with Gaussian edge potentials.” NeurIPS.