Sources grouped here: HMM.pdf, crf-tutorial.pdf, the supplied HMM and POS-tagging article, and the supplied CRF worked guide.

Core idea

HMMs and CRFs model structured outputs, such as one label per word in a sentence. An HMM is a generative model with hidden states and emissions; a linear-chain CRF directly scores complete label sequences using rich input features and normalises those scores with a partition function.

1. Sequential data and the Markov assumption

Sequential data contains an order: speech frames, words in a sentence, DNA bases, and time series. Its items are not generally independent.

For a first-order Markov process :

The next state depends only on the previous state. This is an approximation: real history may matter, but the assumption makes inference tractable.

PYQ — CT Set B, Q2(b)

Original question scan — Class Test I Set B Q2(b) with the weather sequence

Use the weather sequence S,S,S,R,R,C,C,S,S,S to predict day 11 with a Markov chain. Estimate transitions by counting the nine adjacent pairs. Of the five observed transitions leaving S, four lead to S and one to R, so , , . Day 10 is S, so the most likely day 11 is sunny, under this first-order empirical model. This is a very small sample and the estimate is uncertain.

A visible Markov chain treats the weather state as observed. An HMM instead posits hidden states and observations emitted from them. Hidden states are useful when the cause is unobserved; if the relevant state really is observable, hiding it is not required.

2. Hidden Markov Model (HMM)

An HMM contains:

  • hidden state sequence ;
  • observed sequence ;
  • first-order transitions between hidden states;
  • an observation/emission generated from each current hidden state.
flowchart LR S1["S₁: hidden state"] --> S2["S₂: hidden state"] --> ST["… → Sₜ"] S1 --> O1["O₁: observation"] S2 --> O2["O₂: observation"] ST --> OT["Oₜ: observation"]

HMM parameters

ParameterFormulaMeaning
Initial probabilityProbability that the sequence starts in state .
Transition probabilityProbability of moving from state to .
Emission probabilityProbability of observation in state .

The joint probability of a hidden path and observations is

Example: dishonest casino

The hidden state is which die is used: fair or loaded. The observation is the rolled face. A loaded die emits 6 much more often, while transition probabilities describe how often the casino changes dice.

Plain meaning

You see only the rolls, not the die. An HMM uses the observed roll pattern and its transition/emission probabilities to infer which die was likely used at each time.

3. The three HMM problems

ProblemQuestionStandard algorithm
EvaluationWhat is , the probability of the observation sequence?Forward algorithm
DecodingWhat is the most probable hidden-state sequence?Viterbi algorithm
LearningWhich parameters maximise likelihood of observed data?Baum-Welch (EM)

Forward algorithm: evaluation

Define the forward value

Recurrence:

It replaces enumeration of exponentially many state paths with dynamic programming in time for states.

Forward-backward: state marginals

The backward value is the probability of the remaining observations given the current state:

Then the posterior probability of state at time is

Marginal state versus best sequence

Picking the most likely state independently at every position is not always the same as the single most likely complete sequence.

Viterbi: best state sequence

Viterbi keeps the score of the best path ending in each state rather than summing all paths:

Store the maximising predecessor as a backpointer, choose the highest final score, then backtrack to recover the full path.

Baum-Welch: learning an HMM

Baum-Welch is EM for HMMs:

  1. Initialise , transition, and emission parameters.
  2. E-step: run forward-backward to calculate expected state and transition counts.
  3. M-step: update , , and from these expected counts.
  4. Repeat until likelihood converges.

4. HMM for part-of-speech (POS) tagging

POS tagging assigns a grammatical label to each word. Context matters: the same word can be a noun in one sentence and a verb in another.

HMM conceptPOS-tagging interpretation
Observation Word at position
Hidden state POS tag at position
Transition
Emission

This supports text-to-speech, word-sense disambiguation, information extraction, speech recognition, and machine translation. The key idea is that the word is visible, while the correct tag sequence is hidden and inferred from both word evidence and neighbouring tags.

5. From HMMs to CRFs

HMMLinear-chain CRF
Generative: models .Discriminative: models .
Must model observations/emissions.Does not need to model .
Emission commonly depends mainly on current observation.Can use rich overlapping/global features: word shape, prefixes/suffixes, surrounding words, capitalisation, dictionaries, etc.
Uses directed state-to-observation structure.Uses an undirected conditional graphical/factor structure.

An HMM-like chain is a restricted special case of a linear-chain CRF. CRFs are attractive when rich observed features are available and we care about predicting labels rather than generating the input.

6. Markov networks and CRFs

A Markov network (undirected graphical model) represents a distribution by local non-negative factors/potentials:

  • A node is a random variable.
  • An edge/factor represents a local compatibility/dependency.
  • is the partition function, the sum of the unnormalised score over all possible assignments, ensuring probabilities sum to 1.

A conditional random field (CRF) applies this idea to a conditional distribution. For fixed input , labels factorise according to a graph:

7. Linear-chain CRF

In a linear-chain CRF, each output label is connected to its neighbour . This suits sequence labelling such as POS tagging and named-entity recognition (NER).

flowchart LR X1["x₁: word/features"] --- Y1["y₁: label"] --- Y2["y₂: label"] --- Y3["…"] --- YT["yₜ: label"] X2["x₂: word/features"] --- Y2 XT["xₜ: word/features"] --- YT

Score and conditional probability

A CRF gives a score to a whole label sequence:

  • is an emission/local feature score for assigning label at position .
  • is a transition score for adjacent labels.

Then

Partition function: what it does

is the sum of exponentiated scores of all label sequences. It is the normalising bridge between arbitrary real-valued scores and probabilities.

Small worked partition function

For two words and labels (person) and (location), suppose sequence scores are:

SequenceScore
12.718
320.086
01
12.718

Therefore . The four normalised probabilities sum to 1.

Directly listing sequences costs for labels and positions. The forward algorithm calculates efficiently in .

8. CRF inference: forward-backward, Viterbi, and belief propagation

GoalLinear-chain CRF methodResult
Calculate and label/edge marginalsForward-backwardSum over all paths efficiently.
Predict the best complete label sequenceViterbiMaximum-scoring sequence + backpointers.
General graph with no simple chain/tree structureBelief propagation or an approximationMarginals/messages between factors and variables.

Viterbi recurrence for a CRF

At each position and current label, keep only the best predecessor and its score, then backtrack from the best final label.

For Riya lives in Kolkata, a CRF can prefer

because word-level scores favour Riya B-PER and Kolkata B-LOC, while transition scores favour valid neighbouring-label patterns. It does not choose each label independently.

Belief propagation

Belief propagation passes local messages through a factor graph to compute marginals.

  • On a tree, it is exact.
  • Forward-backward is belief propagation specialised to a chain.
  • On graphs with cycles, loopy belief propagation is approximate and may not converge, but is often useful in practice.

9. Training CRFs

For labelled sequence training data, CRFs maximise conditional log likelihood, usually with regularisation.

The central training result is:

Interpretation:

  • If the correct training labels use a feature more often than the model expects, increase its weight.
  • If the model expects a feature more often than observed, decrease its weight.

Small expected-count example

Suppose the feature is “word Kolkata has label B-LOC.” In two training sentences it occurs twice, so its observed count is 2.

  • Current CRF marginal for sentence 1: .
  • Current CRF marginal for sentence 2: .

Expected count .

With gradient ascent and learning rate :

The positive update increases the model’s preference for this feature.

Important distinction

Viterbi finds the best single sequence for prediction. Forward-backward obtains and marginal probabilities needed for expected feature counts during training.

Optimisation and regularisation

  • L2 regularisation penalises large weights and reduces overfitting.
  • L1 regularisation encourages sparse weights/features.
  • Gradient methods and quasi-Newton methods such as L-BFGS can optimise the conditional log likelihood.
  • Training is more expensive than one prediction because forward-backward is repeatedly run for every training sequence and optimisation step.

Teacher walkthrough: decoding “Riya lives in Kolkata”

Let the possible labels be P (person), O (outside), L (location). The token score tuples, in P/O/L order, are Riya , lives , in and Kolkata . The transition-score rows are P , O and L , with zero start and end scores.

Viterbi stores the best prefix score ending at each label. The rows are , , and . For example, the last L score is . Backtracking the stored predecessors yields P, O, O, L. The partition function is shared by all paths for this sentence, so the most probable path also has the highest unnormalized score.

Teacher walkthrough: learning from observed minus expected counts

For “Sohan Kolkata”, consider P/L labels, first-token scores , second-token scores , and a P→L transition score of 1, with all other transitions zero. The scores of PP, PL, LP, LL are . Therefore and . For gold path PL, the observed count of P→L is 1 and its expected count is ; the unregularized log-likelihood gradient is . With learning rate 0.1 the transition weight rises by about . A token feature for Kolkata=L fires in PL and LL, so its expected count is . In longer chains forward–backward obtains these marginals without enumerating all paths.

PYQ — CT Set B, question 2(c)

Original question scan — Class Test I Set B Q2(c)

State applications of CRFs and how they differ from HMMs. CRFs are used for sequence labelling such as named-entity recognition, part-of-speech tagging and segmentation. An HMM specifies a joint distribution over hidden states and observations; a linear-chain CRF models the conditional distribution of labels given the observed sequence and can use overlapping input features. Both can use Viterbi for best-path decoding.

10. HMM versus CRF: final comparison

AspectHMMLinear-chain CRF
Model typeGenerativeDiscriminative
Distribution
Input featuresRestricted by emission modelCan use rich, overlapping/global input features
NormalisationTransition/emission probabilities are locally normalisedOne sequence-level partition function
DecodingViterbiViterbi with CRF scores
TrainingBaum-Welch/EM when states are hiddenObserved minus expected feature counts
Final revision

HMM: hidden states + initial, transition, and emission probabilities.
Forward / Viterbi / Baum-Welch: evaluate / decode / learn an HMM.
CRF: score whole label sequences using rich features.
Partition function: sum of over every sequence.
CRF learning: observed feature counts minus expected feature counts.