How the Viterbi algorithm decodes a hidden path

Short answer: The Viterbi algorithm finds the most probable sequence of hidden states for a sequence of observations in a hidden Markov model. The cell v[t][s] is the probability of the best path that emits the first t observations and ends in state s. It multiplies the best predecessor by the transition into s and by the emission of observation t from s. The time is O(T · S²) for T observations and S states. In practice the recursion is computed in log space so the product does not underflow.


What the problem actually asks

A hidden Markov model generates a state path by a Markov chain and emits an observation from each state. The joint probability of a particular path and the observed sequence is a product of transitions and emissions. The number of paths is S^T. The best path that ends in state s at time t must arrive from some state r at time t−1, and the prefix up to r must itself have been the best way to reach r. That is the DP.

Multiplying hundreds of probabilities underflows double precision. Adding logarithms turns the product into a sum and the algorithm into a longest-path computation on the same graph. The argmax is unchanged.


What the algorithm guarantees

The maximum over states of v[T][s], times the stop probability if the model has one, is the probability of the most probable path. A predecessor pointer reconstructs that path. Time is Θ(T · S²) for a dense transition matrix, and less when many transitions are structurally zero. Extra memory is the table, or two columns plus a predecessor matrix if the path is required. The algorithm returns the single best path, not the posterior probability of a state at time t. That posterior is the forward-backward algorithm.

A tie between paths is broken by the argmax convention. The algorithm assumes the Markov property and the given emission model. It does not learn the probabilities. Baum-Welch, an expectation-maximization procedure, estimates parameters.


The working steps

  1. Convert every transition and emission probability to a log, or guard the code against underflow. Set the time-1 column from the initial-state distribution times the first emission.
  2. For each later time t and each state s, set v[t][s] to the emission of the current observation from s, times the maximum over r of v[t−1][r] times the transition r→s.
  3. Store the argmax r as the predecessor of (t, s).
  4. At time T, choose the best final state. If the model has an end marker, include the transition into the end state.
  5. Walk predecessors backward to recover the path, then reverse it.

Viterbi is the maximum-probability path, a decoding. Forward-backward is the sum over paths, a posterior. Mixing them returns a probability mass from a procedure that was asked for a path, or a path from a procedure that summed. The quadratic dependence on S is the dense case. A chain with a banded transition structure should iterate only the legal edges.


Approaches that look simpler and fail

Approach Why it fails when the forward probabilities are normalized as if they were Viterbi
Sum over predecessors instead of maximizing The sum is the forward algorithm. It computes the total probability of the observations, not the best path.
Multiply raw probabilities for a long sequence The product underflows to zero and the argmax becomes noise. Logarithms keep the same argmax in range.
Normalize each column and still report the final number as a path probability Normalization changes the value. The path recovered from predecessors can stay correct if the scale is identical for every state, and the reported probability is then wrong unless the scales are saved.
Use the decoded path as the posterior marginal of a state The best path can disagree with the individually most likely state at a time. Marginals come from forward-backward.

Posterior state probabilities are forward-backward. Parameter learning is Baum-Welch. Viterbi is the max-product decoding of a hidden Markov model.


A working example

This Python fragment keeps the best predecessor, which is Viterbi, not the sum of paths. Two states, emissions that prefer state 0 on a and state 1 on b, decode ab as 0 1.

states = [0, 1]
emit = {0: {"a": 0.8, "b": 0.2}, 1: {"a": 0.2, "b": 0.8}}
trans = [[0.5, 0.5], [0.5, 0.5]]
obs = "ab"
n = len(obs)
dp = [[0.0] * 2 for _ in range(n)]
back = [[0] * 2 for _ in range(n)]
for s in states:
    dp[0][s] = 0.5 * emit[s][obs[0]]
for t in range(1, n):
    for s in states:
        options = [(dp[t - 1][p] * trans[p][s], p) for p in states]
        best, prev = max(options)
        dp[t][s] = best * emit[s][obs[t]]
        back[t][s] = prev
path = [max(states, key=lambda s: dp[-1][s])]
for t in range(n - 1, 0, -1):
    path.append(back[t][path[-1]])
path.reverse()
assert path == [0, 1]
print(*path)

Where it is used

A Viterbi decoder is the standard decoder for convolutional codes in telecommunications, including GSM and deep-space links. The same dynamic program decodes a hidden Markov model in speech and in part-of-speech tagging. Beam search keeps fewer candidates.


When you can drop this algorithm

Drop Viterbi when the quantity required is a marginal or a total likelihood. Use the forward recursions. Keep Viterbi when the output is one most probable state sequence, and compute it in log space.


Why this stays published

We publish this so a search for the Viterbi algorithm returns the max-product recurrence and the reason it is computed in log space. The Viterbi algorithm recovers the most probable hidden-state path in O(T · S²) time by keeping, for each time and state, the best predecessor times the emission.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *