Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hidden Markov models: Viterbi, forward-backward and Baum-Welch

ProblemModel a sequence of observations produced by an unseen Markov chain; find the most likely hidden path, the probability of each hidden state, and the model’s parameters from data
Devised byAndrew Viterbi (1967), the decoding algorithm; Leonard Baum, Ted Petrie, George Soules and Norman Weiss (1966–1970), the forward-backward and re-estimation algorithms; Lawrence Rabiner (1989), the tutorial and scaling
AccuracyViterbi and forward-backward are exact; Baum-Welch increases the likelihood at every iteration and converges to a local maximum
Cost time for a sequence of steps and states, per pass
Read firstDynamic programming, Gaussian mixture models
APIviterbi_path, HiddenMarkovModel (new, random, sample, viterbi, log_likelihood, posteriors, baum_welch), BaumWelchResult

Overview

In a hidden Markov model (HMM), a system moves between a few hidden states according to a Markov chain, and at each step emits an observation whose distribution depends only on the current state. The observations are seen; the states are not. Examples include speech, where phonemes are hidden and acoustic frames observed; genes, where coding and non-coding regions are hidden and bases observed; and decoding, where transmitted bits are hidden and received signals observed. Three questions arise, each with a dynamic-programming answer:

  • the most likely hidden path (Viterbi);
  • the probability of the observations and of each state at each time (forward-backward);
  • the parameters that best explain the observations (Baum-Welch).

Where it is used

Hidden Markov models describe sequences generated by a state that cannot be observed directly.

  • Speech recognition. For decades, acoustic models were HMMs: states are sounds, observations are spectral features.
  • Bioinformatics. Gene finding and protein profile models decode the hidden structure of a sequence.
  • Activity and fault detection. Inferring a machine’s health state, or a person’s activity, from sensor readings.
  • Communications and tracking. The Viterbi algorithm is the same one used to decode convolutional codes; the forward algorithm evaluates sequence likelihoods.

History

Leonard Baum and colleagues at the Institute for Defense Analyses developed the statistical theory of probabilistic functions of Markov chains between 1966 and 1970, including the forward-backward procedure and the re-estimation algorithm that bears Baum and Lloyd Welch’s names, an instance of what Dempster, Laird and Rubin (1977) would call EM. Andrew Viterbi (1967) devised his algorithm to decode convolutional codes; it is used in every mobile phone, and G. David Forney (1973) recognised it as a shortest-path search through a trellis. James Baker and Frederick Jelinek’s groups applied HMMs to speech recognition in the 1970s, and Lawrence Rabiner’s 1989 tutorial made them standard. Richard Durbin, Sean Eddy, Anders Krogh and Graeme Mitchison’s Biological Sequence Analysis (1998) brought them to genomics, along with the dishonest casino example used here.

The idea

The model

A discrete HMM with states and symbols has an initial distribution , a transition matrix , and an emission matrix . A path and observations have joint probability

In the occasionally dishonest casino (Durbin et al.), a croupier usually rolls a fair die but sometimes switches to a loaded one that shows six half the time. The switch probabilities are 0.05 per roll from fair to loaded and 0.1 back. We see only the rolls.

The Viterbi algorithm

The first question to ask of an HMM is decoding: given the observations, what is the most likely sequence of hidden states? There are possible paths, far too many to try. But the principle of optimality applies. Because each state depends only on the one before it, the best path that ends in state at time must consist of the best path to some state at time , followed by the step from to . So it is enough to keep, for each state, the best path ending there.

Let be the highest log probability of any path ending in state at time , together with the observations up to then. It starts as and is updated by

The first term chooses the best predecessor of ; the second accounts for emitting the observed symbol from . The maximising is stored as a back-pointer. At the end, the state with the largest is the last state of the best path, and following the back-pointers from it recovers the whole path. Each of the steps examines transitions, so the cost is instead of .

Working with logarithms turns the products of probabilities into sums and avoids underflow: probabilities of long sequences fall below the smallest f64 within a few hundred steps. The library’s viterbi_path takes the scores as closures, so the same code decodes HMMs, trellis codes or any other chain of choices.

The forward-backward algorithm

Two further questions have the same structure. What is the total probability of the observations, summed over all possible paths? And what is the probability that the chain was in a particular state at a particular time, given all the observations?

Forward. Define the forward variables : the probability of the observations so far, with the chain in state now. They obey the Viterbi recurrence with the maximum replaced by a sum, since we now add up over all predecessors instead of choosing the best:

At the end, : the sum over all paths, at a cost of .

Backward. The backward variables are the probability of the remaining observations, given the state now. They are computed from the end:

Combining them. The probability of all the observations together with state at time is the product : the past and present, times the future. Dividing by the total gives the posterior probability of each state at each time,

Figure 13.7. The dishonest casino.

The posterior probability of the loaded die rises during the loaded stretches. The Viterbi path finds the long ones and misses the short runs near the start, where a few rolls are not enough evidence against the strong prior to stay fair. The two decoders answer different questions. Viterbi gives the single most likely sequence; taking the most likely state at each time (posterior decoding) maximises the expected number of correct labels, though the resulting sequence may be impossible as a whole:

Table 13.8. Accuracy of Viterbi and posterior decoding.

decoder (100 sequences of 300 rolls)fraction of rolls labelled correctly
always guess fair0.660
Viterbi path (most likely sequence)0.802
posterior decoding (most likely state at each roll)0.827

Baum-Welch

When the parameters are unknown, EM estimates them from the observations alone. The E-step computes, by forward-backward, the expected number of times each state starts the sequence, each transition is taken (), and each symbol is emitted from each state. The M-step sets each probability to its normalised expected count. As for Gaussian mixtures, the likelihood never decreases, but the method only finds a local maximum:

Figure 13.8. Baum-Welch from random starts.

All five random starts move quickly to a plateau, a nearly symmetric model in which the two states are almost identical. They then stay there for dozens to over a thousand iterations, until the symmetry breaks and the likelihood climbs to the level of the true model. One start had not escaped after 2000 iterations. Several starts, and patience, are needed. The best run recovers the casino:

Table 13.9. HMM parameters estimated by Baum-Welch.

parametertrueBaum-Welch (best of five starts)
P(fair → loaded)0.0500.047
P(loaded → fair)0.1000.097
P(sixfair)0.167
P(sixloaded)0.500
P(oneloaded)0.100
total log-likelihood-34818.0-34815.7 (converged after 1455 iterations)

The learned model’s likelihood is slightly higher than the true model’s, as expected of a maximum-likelihood fit to a finite sample. EM cannot know which state is “fair”; the learned states are matched to the true ones by their probability of a six.

Scaling

Forward and backward probabilities underflow for long sequences. Rabiner’s remedy normalises to sum to one at each step, with scale factor , and divides by the same factors. Then , , and , all without leaving the range of f64. The library uses scaling in Baum-Welch and log-sum-exp in log_likelihood and posteriors.

Algorithm

For a sequence of observations and a model with states.

Viterbi decoding.

  1. Initialise for every state .
  2. For and every state : find the state maximising ; store it as the back-pointer ; set to that maximum plus .
  3. The last state of the best path is .
  4. Trace back: for , set .

Forward-backward.

  1. Forward pass: compute , then from for . After each step, divide by its sum and keep .
  2. The log-likelihood is .
  3. Backward pass: set and compute from for , dividing by the same factors.
  4. The posterior of state at time is the product of the scaled and .

Both cost operations and storage.

Baum-Welch training, from starting parameters. Repeat:

  1. E-step. Run the scaled forward-backward pass on every training sequence, and accumulate three tables of expected counts: how often each state starts a sequence (); how often each transition is taken (); and how often each state emits each symbol ( summed over the times at which that symbol was observed).
  2. M-step. Divide each table by its row sums, so that each row is a probability distribution: these are the new , and .
  3. Test. Stop when the log-likelihood improves by less than the relative tolerance, or at the iteration limit.

Implementation

    let mut score: Vec<f64> = (0..n).map(|s| log_initial[s] + log_emission(s, 0)).collect();
    let mut back: Vec<Vec<usize>> = Vec::with_capacity(steps);
    for t in 1..steps {
        let mut next = vec![f64::NEG_INFINITY; n];
        let mut from = vec![0usize; n];
        for to in 0..n {
            let (best_from, best) = (0..n).map(|f| (f, score[f] + log_transition(f, to))).fold((0, f64::NEG_INFINITY), |b, c| if c.1 > b.1 { c } else { b });
            next[to] = best + log_emission(to, t);
            from[to] = best_from;
        }
        back.push(from);
        score = next;
    }
    let (mut state, best) = score.iter().enumerate().fold((0, f64::NEG_INFINITY), |b, (s, &v)| if v > b.1 { (s, v) } else { b });
    let mut path = vec![0; steps];
    path[steps - 1] = state;
    for t in (1..steps).rev() {
        state = back[t - 1][state];
        path[t - 1] = state;
    }
            for o in sequences {
                let (alpha, beta, scale) = model.scaled_forward_backward(o);
                if scale.iter().any(|&c| c <= 0.0) {
                    return Err(ErrorsJSL::RuntimeError("A training sequence has zero probability under the model."));
                }
                log_likelihood += scale.iter().map(|c| c.ln()).sum::<f64>();
                for t in 0..o.len() {
                    // γ_t(s) = α̂_t(s) β̂_t(s) (already normalised by the scaling).
                    for s in 0..n {
                        let gamma = alpha[t][s] * beta[t][s];
                        if t == 0 {
                            initial[s] += gamma;
                        }
                        emissions[[s, o[t]]] += gamma;
                    }
                    if t + 1 < o.len() {
                        for f in 0..n {
                            for to in 0..n {
                                transitions[[f, to]] += alpha[t][f] * model.transition[[f, to]] * model.emission[[to, o[t + 1]]] * beta[t + 1][to] / scale[t + 1];
                            }
                        }
                    }
                }
            }
  • Each Viterbi step is a full scan, so time grows as :

Table 13.10. Viterbi time against the number of states.

states N (1000 steps)Viterbi time (ms)ns per step per N²
20.0511.7
80.264.1
323.173.1
12851.093.1
  • A row of expected counts that is zero (a state never visited) keeps its old probabilities instead of dividing by zero.
  • BaumWelchResult::log_likelihood records the likelihood at the start of each iteration; the returned model has been re-estimated once more. (The documentation said “after each iteration” before this chapter was written.)

In practice

//! Hidden Markov models: the occasionally dishonest casino, decoded with Viterbi and learned by Baum-Welch.

use lib_jsl_machine_learning::supervised::classification::HiddenMarkovModel;
use ndarray::arr2;

fn main() {
    // State 0 is a fair die, state 1 a loaded one that shows six half the time.
    let fair = [1.0 / 6.0; 6];
    let loaded = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5];
    let casino = HiddenMarkovModel::new(vec![0.5, 0.5], arr2(&[[0.95, 0.05], [0.1, 0.9]]), arr2(&[fair, loaded])).unwrap();
    let (states, rolls) = casino.sample(60, 4);
    let (path, log_p) = casino.viterbi(&rolls).unwrap();
    let show = |v: &[usize]| v.iter().map(|s| s.to_string()).collect::<String>();
    println!("rolls   {}", rolls.iter().map(|r| (r + 1).to_string()).collect::<String>());
    println!("truth   {}", show(&states));
    println!("Viterbi {}  (log probability {log_p:.1})", show(&path));
    println!("log-likelihood of the rolls {:.1}", casino.log_likelihood(&rolls).unwrap());

    // Learn the parameters back from 20 000 rolls, starting from a random model.
    let sequences: Vec<Vec<usize>> = (0..40).map(|k| casino.sample(500, 100 + k).1).collect();
    let fit = HiddenMarkovModel::random(2, 6, 2).unwrap().baum_welch(&sequences, 2000, 1e-9).unwrap();
    println!("Baum-Welch: {} iterations, converged {}", fit.log_likelihood.len(), fit.converged);
    println!("transition\n{:.3}\nemission\n{:.3}", fit.model.transition(), fit.model.emission());
}
rolls   666626666434466624362264346161126244366536465666542441311645
truth   111111100000111111111111111111111000011111111111100000000000
Viterbi 111111111111111111111111111111111111111111111111000000000000  (log probability -103.5)
log-likelihood of the rolls -98.8
Baum-Welch: 188 iterations, converged true
transition
[[0.894, 0.106],
 [0.054, 0.946]]
emission
[[0.108, 0.096, 0.090, 0.099, 0.103, 0.504],
 [0.163, 0.168, 0.171, 0.165, 0.168, 0.164]]

Viterbi bridges the two short fair stretches inside the loaded period: switching out and back costs more probability than the few rolls justify. The learned model has numbered its states the other way round, with state 0 loaded. The probability of the most likely path (−103.5) is a small part of the total over all paths (−98.8).

Strengths

  • Exact, efficient inference for sequences; the same dynamic programme serves decoding, likelihoods and posteriors.
  • Unsupervised training from observations alone; a principled probabilistic model.

Weaknesses

  • The Markov assumption: the state carries all memory, and state durations are geometrically distributed.
  • Baum-Welch finds local maxima, can stall on plateaus, and needs the number of states fixed in advance.
  • Discrete emissions only in this implementation.

Exercises

  1. Show that the number of operations in the forward algorithm is , while summing over paths directly costs .
  2. Show that posterior decoding can produce a path with probability zero under the model, and construct an example.
  3. Derive the Baum-Welch update for the transition matrix from the expected complete-data log-likelihood.
  4. Show that the expected time spent in the loaded state per visit is rolls, and that durations are geometric.
  5. Extend the model to Gaussian emissions and derive the M-step for the means and variances.
Hints and answers
  1. Each of the time steps does an matrix-vector product, so . Summing over all state paths, each costing , gives .
  2. Posterior decoding picks the most probable state at each time separately. If has probability zero but the marginal probabilities favour at both times 1 and 2 (because the two likely paths are and ), the decoded path has probability zero.
  3. Maximise subject to each row of summing to 1; the Lagrange condition gives .
  4. The state is left with probability each step, so the duration is geometric with and mean .
  5. Weighting each observation by , the M-step gives and .

Further reading

  • L. R. Rabiner, “A tutorial on hidden Markov models and selected applications in speech recognition”, Proceedings of the IEEE 77 (1989) 257–286.
  • A. J. Viterbi, “Error bounds for convolutional codes and an asymptotically optimum decoding algorithm”, IEEE Transactions on Information Theory 13 (1967) 260–269.
  • G. D. Forney, “The Viterbi algorithm”, Proceedings of the IEEE 61 (1973) 268–278.
  • R. Durbin, S. Eddy, A. Krogh and G. Mitchison, Biological Sequence Analysis, Cambridge University Press, 1998, chapter 3.
  • L. E. Baum, T. Petrie, G. Soules and N. Weiss, “A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains”, Annals of Mathematical Statistics 41 (1970) 164–171.