Forward-backward algorithm

On this page 7

The forward-backward algorithm is a dynamic programming procedure that computes, for every time step of an observed sequence, the posterior probability of each hidden state in a hidden Markov model (HMM). It combines a forward pass that accumulates evidence from the past with a backward pass that accumulates evidence from the future, so each state estimate uses the entire observation sequence.

Among probabilistic models for sequential data, the algorithm is the standard method for exact inference in HMMs. It reduces a sum over an exponential number of hidden paths to a computation that grows only linearly with sequence length, and it supplies the expected statistics that the Baum-Welch algorithm needs to learn HMM parameters.

What the forward-backward algorithm computes

An HMM is defined by an initial state distribution, a transition matrix between N hidden states and an emission model that gives the probability of each observation in each state. Given observations o1 to oT, the algorithm answers the smoothing question: how likely was the system to be in state i at time t, given everything that was observed?

Enumerating all hidden paths would require summing over N to the power T sequences, which is infeasible even for modest lengths. The forward-backward algorithm exploits the Markov property, namely that the next state depends only on the current one, to reuse partial results and achieve a cost of order N squared times T.

The algorithm produces three related quantities, summarized in the table below.

QuantityDefinitionTypical use
Sequence likelihoodProbability of all observations under the modelModel comparison and classification
State posterior (gamma)Probability of state i at time t given all dataSmoothing and per-step labeling
Transition posterior (xi)Probability of moving from i to j at time tExpected counts for parameter learning
Main outputs of the algorithm

How the forward and backward passes work

The forward variable alpha at time t and state i is the joint probability of the observations up to t and of being in state i at t. It starts from the initial distribution weighted by the first emission and is updated recursively: each new alpha sums the previous alphas multiplied by the transition probabilities, then multiplies by the emission probability of the current observation.

The backward variable beta at time t and state i is the probability of the future observations from t+1 to T given state i at time t. It is initialized to one at the final step and computed in reverse, summing over next states weighted by transitions and future emission probabilities.

Multiplying alpha and beta for the same time and state, then dividing by the sequence likelihood, yields the state posterior. The transition posterior combines alpha at t, the transition probability, the emission at t+1 and beta at t+1. The steps are listed below in order.

  1. Initialize alpha at the first time step from the initial distribution and first emission.
  2. Run the forward recursion through all time steps.
  3. Initialize beta at the last time step to one.
  4. Run the backward recursion from the end to the start.
  5. Combine alpha and beta to obtain gamma and xi for every time step.

Complexity and numerical stability

The algorithm runs in time proportional to N squared times T and stores alpha and beta tables of size N times T. For long sequences, memory can become the binding constraint, and checkpointing schemes trade extra computation for a smaller memory footprint.

A practical issue is numerical underflow. Alpha and beta are products of many probabilities below one, so they shrink exponentially and fall below the range of floating-point numbers after a few hundred steps. Implementations therefore use per-step scaling or computation in the log domain with the log-sum-exp operation.

ApproachHow it worksMain consideration
Unscaled recursionRaw products of probabilitiesUnderflows on realistic sequence lengths
Scaling factorsNormalize alpha at each step and reuse factors for betaFast; log-likelihood equals the sum of log factors
Log-space computationStore log probabilities and use log-sum-expRobust but slower due to exponentials
CheckpointingStore alpha only at selected stepsLower memory, extra recomputation
Implementation choices and their properties

Relation to Viterbi, Baum-Welch and other inference methods

The forward-backward algorithm is often confused with neighboring procedures. The key distinction is that it computes marginal posteriors, whereas the Viterbi algorithm finds the single most probable path. The per-step most likely states from forward-backward may form a sequence that the model itself considers impossible, which is why the two methods answer different questions.

The comparison below places the algorithm among related methods in the same family of probabilistic models.

AlgorithmQuestion answeredCore operation
Forward algorithmLikelihood of the sequence or filtered stateSum over past states
Forward-backwardSmoothed posterior of each stateSum over past and future
Viterbi algorithmMost probable hidden state sequenceMaximization instead of summation
Baum-Welch algorithmMaximum likelihood HMM parametersExpectation maximization using forward-backward
Belief propagationMarginals in general tree-structured graphsMessage passing that generalizes forward-backward
Forward-backward compared with related algorithms

In graphical-model terms, the algorithm is sum-product belief propagation on a chain. The same two-pass structure appears in the Kalman smoother for linear Gaussian state-space models and in the inference routines of linear-chain conditional random fields.

Practical applications and limitations

The algorithm underpins classical speech recognition with HMM acoustic models, gene finding and sequence alignment with profile HMMs in bioinformatics, part-of-speech tagging, activity recognition from sensor data and regime detection in financial time series. In each case, smoothed posteriors provide calibrated per-step uncertainty rather than a single hard label.

Its limitations follow from the HMM assumptions. It requires a finite discrete state space of manageable size, since cost grows with N squared. It needs the full sequence in advance, so pure online applications use the forward pass alone or fixed-lag smoothing. Finally, the posteriors are only as good as the model: misspecified transitions or emissions produce confident but wrong estimates.

In everyday language

Imagine guessing the weather each day from what a friend did. You cannot see the weather. You only know whether they walked, shopped or cleaned the house.

The forward-backward algorithm makes the best guess for each day. It reads the diary from the start, then from the end. Each day’s guess then uses clues from both earlier and later days. This works better than judging one day alone. It also does the job quickly, without checking every possible weather story one by one.

Seen in the real world

A bioinformatics team analyzes a bacterial genome of about 5 million base pairs to locate protein-coding genes. They use an HMM with hidden states for coding regions, noncoding regions and gene boundaries, and emission probabilities learned from known genes of related species.

Running the forward-backward algorithm in log space gives, for every base, the posterior probability that it lies inside a coding region. Instead of a single yes or no label, the researchers obtain a confidence profile along the genome. Regions with posteriors near 0.5 are flagged for manual review or laboratory validation.

The team also runs Viterbi decoding for a clean gene annotation, then compares both outputs. Disagreements highlight ambiguous gene boundaries, which helps the team concentrate costly experimental work on the few hundred sites where the model is genuinely uncertain.