Foundations to Frontier
Tests
D. Classical Machine Learning › D3 Probabilistic and Bayesian Classifiers

Hidden Markov Models: Forward–Backward, Viterbi, Baum–Welch

A hidden Markov model explains a sequence of observations by a hidden state that evolves as a Markov chain, each state emitting observations from its own distribution. Three algorithms make HMMs useful: the forward–backward algorithm computes the probability of the data and the posterior of each hidden state; the Viterbi algorithm finds the single most likely state sequence; and Baum–Welch (EM) learns the parameters from unlabelled sequences. All run in O(TK²) time by dynamic programming. This page covers the model, the three algorithms with scaling and log-space arithmetic, posterior versus Viterbi decoding, EM's guarantees and pitfalls, and continuous-emission and explicit-duration variants. In the exercises you implement all three and check them against brute force; then you decode a spacecraft's operating mode from a noisy sensor and learn the model without labels.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A hidden state you only see through noise

A spacecraft is idle, slewing or thrusting, but telemetry only gives a noisy vibration level. Modes don’t flicker: once slewing, it keeps slewing for a while. A hidden Markov model (HMM) says exactly this. A hidden state moves from step to step with given probabilities, and each state produces observations with its own probabilities. With it, you can work out the most likely sequence of modes, how sure you are at each moment, and even learn the model from unlabelled data.

Hidden Markov model: decode the mode from noisy readings
true modesensor levelper-stepViterbi
■ idle■ slew■ thrust
accuracy: per-step 62% (65 switches) · Viterbi 92% (3 switches) · true switches: 3
Per-step decoding picks whichever mode best explains each single reading, so it flickers whenever readings overlap. Viterbi finds the single most probable whole sequence, trading a few unlikely readings against fewer mode changes. Stickiness 0.34 means 'no memory' (same as per-step); about 0.97 matches how the data were generated.
Why engineers care

Mode estimation, fault onset detection, activity recognition from IMUs, speech, gene finding and target tracking with discrete manoeuvre modes are all HMMs. The core idea, combining a model of how states change with a model of what they look like, is the discrete cousin of the Kalman filter.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In an HMM, the hidden state…
  2. 2. Decoding without memory (per step) tends to…
  3. 3. Which algorithm finds the single most likely state sequence?

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

The forward algorithm by hand

Two hidden states (0, 1) and three observation symbols, with

  • π = (0.6, 0.4);
  • A = [[0.7, 0.3], [0.4, 0.6]];
  • B = [[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]].

Observations: 0, 1, 2, 2.

t Observation α_t(0) α_t(1)
1 0 0.6·0.5 = 0.300 0.4·0.1 = 0.040
2 1 (0.300·0.7 + 0.040·0.4)·0.4 = 0.0904 (0.300·0.3 + 0.040·0.6)·0.3 = 0.0342
3 2 … …

Here α_t(k) = P(observations up to t, state k at t). Summing α at the final step gives P(all observations) = 0.013358, the same as adding up all 16 possible state paths by brute force.

Viterbi replaces the sum over previous states with a max (and remembers which previous state won). For these observations it gives the path 0, 0, 1, 1.

The steps in plain English:

  1. Forward: sweep left to right. Each state’s score is (sum over previous states of score × transition) × emission.
  2. Backward: sweep right to left with the analogous recursion. Forward × backward, normalised, gives the probability of each state at each time.
  3. Viterbi: sweep left to right with max instead of sum, keeping back-pointers, then trace back the best path.
  4. Baum–Welch: with the current parameters, run forward–backward to get expected state and transition counts, re-estimate π, A and B from those counts, and repeat.
  5. Work in logs, or rescale each step, to avoid underflow on long sequences.
📝 Quick check (Level 1)
0/3 answered
  1. 1. α₁(0) for π₀ = 0.6, B₀(0) = 0.5?
  2. 2. Viterbi uses which operation where forward uses a sum?
  3. 3. Baum–Welch learns parameters from…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

The algorithms

Model: P(s, o) = π(s₁)B(s₁, o₁) ∏ₜ A(s_(t−1), s_t)B(s_t, o_t).

Forward: α₁(k) = πₖB(k, o₁), and α_t(j) = [Σᵢ α_(t−1)(i)A(i, j)]·B(j, o_t). Then P(o) = Σₖ α_T(k).

Backward: β_T(k) = 1, and β_t(i) = Σⱼ A(i, j)B(j, o_(t+1))β_(t+1)(j).

Posteriors:

  • γ_t(k) = α_t(k)β_t(k)/P(o);
  • ξ_t(i, j) = α_t(i)A(i, j)B(j, o_(t+1))β_(t+1)(j)/P(o).

Scaling. Normalise α_t to sum to 1 and keep the scale factor c_t. Then log P(o) = Σ log c_t, and β is divided by the same factors.

Viterbi: δ_t(j) = maxᵢ [δ_(t−1)(i) + log A(i, j)] + log B(j, o_t), with back-pointers. Cost O(TK²).

Baum–Welch (EM):

  • E-step: compute γ and ξ;
  • M-step: π = γ₁; A(i, j) ∝ Σₜ ξ_t(i, j); B(k, m) ∝ Σ over t with o_t = m of γ_t(k).

The likelihood never decreases, but EM finds only a local maximum, and the state labels are arbitrary (permutation symmetry).

from hmmlearn import hmm
model = hmm.CategoricalHMM(n_components=3, n_iter=100, random_state=0).fit(np.concatenate(seqs).reshape(-1, 1), lengths=[len(s) for s in seqs])
states = model.predict(obs.reshape(-1, 1))            # Viterbi
post = model.predict_proba(obs.reshape(-1, 1))        # forward–backward marginals
# continuous emissions: hmm.GaussianHMM(n_components=3, covariance_type="full")

Use it when the data are sequences with a small number of discrete regimes that persist, and you need decoding, smoothing or unsupervised segmentation. Consider CRFs (D3.37) for rich discriminative features, explicit-duration HMMs when durations are not geometric, and RNNs or transformers for long-range structure with lots of data.

🐍 Exercise 1: forward–backward, Viterbi and Baum–Welch
Implement the scaled forward and backward recursions, state posteriors, log-space Viterbi and Baum–Welch for discrete emissions; check the forward probability and Viterbi path against brute-force enumeration, that EM never decreases the likelihood, and that Baum–Welch recovers the generating parameters up to a relabelling of states.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The forward algorithm's cost is…
  2. 2. With scaling, log P(o) equals…
  3. 3. Baum–Welch guarantees…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

Theory and pitfalls

Two kinds of “best” decoding:

  • Posterior (marginal) decoding, argmaxₖ γ_t(k), maximises the expected number of correct states. It can produce impossible paths, such as a transition with probability 0.
  • Viterbi maximises the probability of the whole path, so it always gives a valid, smoother sequence.

In exercise 2 the marginals were slightly more accurate (0.955 against 0.948), while Viterbi was smoother (5.8 switches against 7.2).

Durations. A self-transition probability a implies geometric durations with mean 1/(1 − a). Real modes often have minimum or typical durations. Explicit-duration (semi-Markov) HMMs model them, at a higher cost.

EM pitfalls:

  • local optima: use several random restarts or sensible initialisation (for example, sticky transitions, or emissions from k-means);
  • label switching: learned state 2 may be true state 0;
  • zero counts that freeze parameters: use smoothing or Dirichlet priors;
  • overfitting K: choose it with BIC or held-out likelihood.

Relatives:

  • the Kalman filter is the continuous-state, linear-Gaussian counterpart, with forward = filter and forward–backward = RTS smoother;
  • switching linear dynamical systems combine both;
  • CRFs (D3.37) are the discriminative counterpart for labelling.

Interview questions.

  • Why does naive per-step classification chatter? Each step is classified independently. The HMM’s transition probabilities penalise switches, so isolated ambiguous readings get absorbed.
  • How do you pick the number of hidden states? Use BIC or AIC, cross-validated log-likelihood, or domain knowledge of the modes.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Mean duration of a state with self-transition 0.95?
  2. 2. Posterior-marginal decoding can produce…
  3. 3. The continuous-state analogue of forward–backward is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Inferring a spacecraft’s operating mode

History.

  • Baum and colleagues (1966–1972) developed HMMs and the Baum–Welch algorithm.
  • Viterbi (1967) introduced his algorithm for decoding convolutional codes, and it is still used in deep-space communication links.
  • Rabiner’s 1989 tutorial made HMMs the foundation of speech recognition for two decades.
  • Durbin et al. (1998) brought them to biological sequence analysis.
  • HMMs are used in robotics for activity and terrain recognition, and in aerospace for mode estimation and fault onset detection.

Exercise 1. The forward probability 0.013358 equals the brute-force sum over all 16 paths, and the Viterbi path (0, 0, 1, 1) equals the brute-force best. Over 40 iterations, Baum–Welch raises the log-likelihood from −2511 to −2181, never decreasing, and recovers the emission matrix to within 0.1 after relabelling the states.

Exercise 2: mode inference. Setup: three modes (idle, slew, thrust) with self-transition 0.97 and overlapping emission distributions; 10 test passes of 300 steps (about 8 true mode switches each). Baum–Welch learns from 20 unlabelled passes.

Decoder Accuracy Switches per pass
Per-step most likely mode (no memory) 0.665 128.1
Posterior marginals (forward–backward) 0.955 7.2
Viterbi (true parameters) 0.948 5.8
Viterbi (Baum–Welch parameters, no labels) 0.953 6.0
  • Memoryless decoding is useless here: 2 in 3 correct, and 16 times too many mode switches.
  • Adding the dynamics lifts accuracy to about 95%, with switch counts close to the truth.
  • Marginals are slightly more accurate; Viterbi is smoother (it slightly under-counts short manoeuvres).
  • Unsupervised Baum–Welch learns the model from unlabelled telemetry (emission error 0.007) and decodes as well as the true parameters. That makes it practical when labelled mode data are scarce.
🐍 Exercise 2 (research): decoding spacecraft modes
Simulate sticky idle/slew/thrust modes observed through a quantised, overlapping sensor; compare per-step, posterior-marginal and Viterbi decoding by accuracy and number of mode switches, and decode with parameters learned by Baum–Welch from unlabelled passes.

HMMs in AI, robotics and aerospace

  • Mode and fault-onset estimation from telemetry.
  • Activity and terrain recognition from IMU sequences on rovers and legged robots.
  • Communications: Viterbi decoding of convolutional codes on deep-space links.
  • Speech and sequence labelling: the classic HMM applications, now often hybridised with neural networks.

References

  1. L. R. Rabiner (1989). “A tutorial on hidden Markov models and selected applications in speech recognition.” Proceedings of the IEEE 77(2).
  2. L. E. Baum, T. Petrie, G. Soules, N. Weiss (1970). “A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains.” Annals of Mathematical Statistics 41(1).
  3. A. J. Viterbi (1967). “Error bounds for convolutional codes and an asymptotically optimum decoding algorithm.” IEEE Transactions on Information Theory 13(2).
  4. R. Durbin, S. Eddy, A. Krogh, G. Mitchison (1998). Biological Sequence Analysis. Cambridge University Press.
  5. K. P. Murphy (2012). Machine Learning: A Probabilistic Perspective, chapter 17. MIT Press.