# Viterbi algorithm

The Viterbi algorithm is a dynamic programming algorithm for finding the most likely sequence of hidden states—called the Viterbi path—that results in a sequence of observed events, especially in the context of Markov information sources and hidden Markov models (HMM).

The algorithm has found universal application in decoding the convolutional codes used in both CDMA and GSM digital cellular, dial-up modems, satellite, deep-space communications, and 802.11 wireless LANs. It is now also commonly used in speech recognition, speech synthesis, diarization, keyword spotting, computational linguistics, and bioinformatics. For example, in speech-to-text (speech recognition), the acoustic signal is treated as the observed sequence of events, and a string of text is considered to be the "hidden cause" of the acoustic signal. The Viterbi algorithm finds the most likely string of text given the acoustic signal.

## History

The Viterbi algorithm is named after Andrew Viterbi, who proposed it in 1967 as a decoding algorithm for convolutional codes over noisy digital communication links. It has, however, a history of multiple invention, with at least seven independent discoveries, including those by Viterbi, Needleman and Wunsch, and Wagner and Fischer.

"Viterbi path" and "Viterbi algorithm" have become standard terms for the application of dynamic programming algorithms to maximization problems involving probabilities. For example, in statistical parsing a dynamic programming algorithm can be used to discover the single most likely context-free derivation (parse) of a string, which is commonly called the "Viterbi parse". Another application is in target tracking, where the track is computed that assigns a maximum likelihood to a sequence of observations.

## Extensions

A generalization of the Viterbi algorithm, termed the max-sum algorithm (or max-product algorithm) can be used to find the most likely assignment of all or some subset of latent variables in a large number of graphical models, e.g. Bayesian networks, Markov random fields and conditional random fields. The latent variables need in general to be connected in a way somewhat similar to an HMM, with a limited number of connections between variables and some type of linear structure among the variables. The general algorithm involves message passing and is substantially similar to the belief propagation algorithm (which is the generalization of the forward-backward algorithm).

With the algorithm called iterative Viterbi decoding one can find the subsequence of an observation that matches best (on average) to a given hidden Markov model. This algorithm is proposed by Qi Wang et al. to deal with turbo code. Iterative Viterbi decoding works by iteratively invoking a modified Viterbi algorithm, reestimating the score for a filler until convergence.

An alternative algorithm, the Lazy Viterbi algorithm, has been proposed. For many applications of practical interest, under reasonable noise conditions, the lazy decoder (using Lazy Viterbi algorithm) is much faster than the original Viterbi decoder (using Viterbi algorithm). While the original Viterbi algorithm calculates every node in the trellis of possible outcomes, the Lazy Viterbi algorithm maintains a prioritized list of nodes to evaluate in order, and the number of calculations required is typically fewer (and never more) than the ordinary Viterbi algorithm for the same result. However, it is not so easy[clarification needed] to parallelize in hardware.

## Pseudocode

This algorithm generates a path $X=(x_{1},x_{2},\ldots ,x_{T})$ , which is a sequence of states $x_{n}\in S=\{s_{1},s_{2},\dots ,s_{K}\}$ that generate the observations $Y=(y_{1},y_{2},\ldots ,y_{T})$ with $y_{n}\in O=\{o_{1},o_{2},\dots ,o_{N}\}$ , where $N$ is the number of possible observations in the observation space $O$ .

Two 2-dimensional tables of size $K\times T$ are constructed:

• Each element $T_{1}[i,j]$ of $T_{1}$ stores the probability of the most likely path so far ${\hat {X}}=({\hat {x}}_{1},{\hat {x}}_{2},\ldots ,{\hat {x}}_{j})$ with ${\hat {x}}_{j}=s_{i}$ that generates $Y=(y_{1},y_{2},\ldots ,y_{j})$ .
• Each element $T_{2}[i,j]$ of $T_{2}$ stores ${\hat {x}}_{j-1}$ of the most likely path so far ${\hat {X}}=({\hat {x}}_{1},{\hat {x}}_{2},\ldots ,{\hat {x}}_{j-1},{\hat {x}}_{j}=s_{i})$ for $\forall j,2\leq j\leq T$ The table entries $T_{1}[i,j],T_{2}[i,j]$ are filled by increasing order of $K\cdot j+i$ :

$T_{1}[i,j]=\max _{k}{(T_{1}[k,j-1]\cdot A_{ki}\cdot B_{iy_{j}})}$ ,
$T_{2}[i,j]=\operatorname {argmax} _{k}{(T_{1}[k,j-1]\cdot A_{ki}})$ ,

with $A_{ki}$ and $B_{iy_{j}}$ as defined below. Note that $B_{iy_{j}}$ does not need to appear in the latter expression, as it's non-negative and independent of $k$ and thus does not affect the argmax.

Input
• The observation space $O=\{o_{1},o_{2},\dots ,o_{N}\}$ ,
• the state space $S=\{s_{1},s_{2},\dots ,s_{K}\}$ ,
• an array of initial probabilities $\Pi =(\pi _{1},\pi _{2},\dots ,\pi _{K})$ such that $\pi _{i}$ stores the probability that $x_{1}=s_{i}$ ,
• a sequence of observations $Y=(y_{1},y_{2},\ldots ,y_{T})$ such that $y_{t}=i$ if the observation at time $t$ is $o_{i}$ ,
• transition matrix $A$ of size $K\times K$ such that $A_{ij}$ stores the transition probability of transiting from state $s_{i}$ to state $s_{j}$ ,
• emission matrix $B$ of size $K\times N$ such that $B_{ij}$ stores the probability of observing $o_{j}$ from state $s_{i}$ .
Output
• The most likely hidden state sequence $X=(x_{1},x_{2},\ldots ,x_{T})$ function VITERBI$(O,S,\Pi ,Y,A,B):X$ for each state $i=1,2,\ldots ,K$ do
$T_{1}[i,1]\leftarrow \pi _{i}\cdot B_{iy_{1}}$ $T_{2}[i,1]\leftarrow 0$ end for
for each observation $j=2,3,\ldots ,T$ do
for each state $i=1,2,\ldots ,K$ do
$T_{1}[i,j]\gets \max _{k}{(T_{1}[k,j-1]\cdot A_{ki}\cdot B_{iy_{j}})}$ $T_{2}[i,j]\gets \arg \max _{k}{(T_{1}[k,j-1]\cdot A_{ki}\cdot B_{iy_{j}})}$ end for
end for
$z_{T}\gets \arg \max _{k}{(T_{1}[k,T])}$ $x_{T}\leftarrow s_{z_{T}}$ for $j=T,T-1,\ldots ,2$ do
$z_{j-1}\leftarrow T_{2}[z_{j},j]$ $x_{j-1}\leftarrow s_{z_{j-1}}$ end for
return $X$ end function

Explanation

Suppose we are given a hidden Markov model (HMM) with state space $S$ , initial probabilities $\pi _{i}$ of being in state $i$ and transition probabilities $a_{i,j}$ of transitioning from state $i$ to state $j$ . Say, we observe outputs $y_{1},\dots ,y_{T}$ . The most likely state sequence $x_{1},\dots ,x_{T}$ that produces the observations is given by the recurrence relations

{\begin{aligned}V_{1,k}&=\mathrm {P} {\big (}y_{1}\ |\ k{\big )}\cdot \pi _{k},\\V_{t,k}&=\max _{x\in S}\left(\mathrm {P} {\big (}y_{t}\ |\ k{\big )}\cdot a_{x,k}\cdot V_{t-1,x}\right).\end{aligned}} Here $V_{t,k}$ is the probability of the most probable state sequence $\mathrm {P} {\big (}x_{1},\dots ,x_{t},y_{1},\dots ,y_{t}{\big )}$ responsible for the first $t$ observations that have $k$ as its final state. The Viterbi path can be retrieved by saving back pointers that remember which state $x$ was used in the second equation. Let $\mathrm {Ptr} (k,t)$ be the function that returns the value of $x$ used to compute $V_{t,k}$ if $t>1$ , or $k$ if $t=1$ . Then

{\begin{aligned}x_{T}&=\arg \max _{x\in S}(V_{T,x}),\\x_{t-1}&=\mathrm {Ptr} (x_{t},t).\end{aligned}} Here we're using the standard definition of arg max.

The complexity of this implementation is $O(T\times \left|{S}\right|^{2})$ . A better estimation exists if the maximum in the internal loop is instead found by iterating only over states that directly link to the current state (i.e. there is an edge from $k$ to $j$ ). Then using amortized analysis one can show that the complexity is $O(T\times (\left|{S}\right|+\left|{E}\right|))$ , where $E$ is the number of edges in the graph.

## Example

Consider a village where all villagers are either healthy or have a fever and only the village doctor can determine whether each has a fever. The doctor diagnoses fever by asking patients how they feel. The villagers may only answer that they feel normal, dizzy, or cold.

The doctor believes that the health condition of his patients operates as a discrete Markov chain. There are two states, "Healthy" and "Fever", but the doctor cannot observe them directly; they are hidden from him. On each day, there is a certain chance that the patient will tell the doctor he is "normal", "cold", or "dizzy", depending on their health condition.

The observations (normal, cold, dizzy) along with a hidden state (healthy, fever) form a hidden Markov model (HMM), and can be represented as follows in the Python programming language:

obs = ('normal', 'cold', 'dizzy')
states = ('Healthy', 'Fever')
start_p = {'Healthy': 0.6, 'Fever': 0.4}
trans_p = {
'Healthy' : {'Healthy': 0.7, 'Fever': 0.3},
'Fever' : {'Healthy': 0.4, 'Fever': 0.6}
}
emit_p = {
'Healthy' : {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1},
'Fever' : {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6}
}


In this piece of code, start_p represents the doctor's belief about which state the HMM is in when the patient first visits (all he knows is that the patient tends to be healthy). The particular probability distribution used here is not the equilibrium one, which is (given the transition probabilities) approximately {'Healthy': 0.57, 'Fever': 0.43}. The transition_p represents the change of the health condition in the underlying Markov chain. In this example, there is only a 30% chance that tomorrow the patient will have a fever if he is healthy today. The emission_p represents how likely each possible observation, normal, cold, or dizzy is given their underlying condition, healthy or fever. If the patient is healthy, there is a 50% chance that he feels normal; if he has a fever, there is a 60% chance that he feels dizzy.

The patient visits three days in a row and the doctor discovers that on the first day he feels normal, on the second day he feels cold, on the third day he feels dizzy. The doctor has a question: what is the most likely sequence of health conditions of the patient that would explain these observations? This is answered by the Viterbi algorithm.

 1 def viterbi(obs, states, start_p, trans_p, emit_p):
2     V = [{}]
3     for st in states:
4         V[st] = {"prob": start_p[st] * emit_p[st][obs], "prev": None}
5     # Run Viterbi when t > 0
6     for t in range(1, len(obs)):
7         V.append({})
8         for st in states:
9             max_tr_prob = V[t-1][states]["prob"]*trans_p[states][st]
10             prev_st_selected = states
11             for prev_st in states[1:]:
12                 tr_prob = V[t-1][prev_st]["prob"]*trans_p[prev_st][st]
13                 if tr_prob > max_tr_prob:
14                     max_tr_prob = tr_prob
15                     prev_st_selected = prev_st
16
17             max_prob = max_tr_prob * emit_p[st][obs[t]]
18             V[t][st] = {"prob": max_prob, "prev": prev_st_selected}
19
20     for line in dptable(V):
21         print (line)
22
23     opt = []
24     max_prob = 0.0
25     previous = None
26     # Get most probable state and its backtrack
27     for st, data in V[-1].items():
28         if data["prob"] > max_prob:
29             max_prob = data["prob"]
30             best_st = st
31     opt.append(best_st)
32     previous = best_st
33
34     # Follow the backtrack till the first observation
35     for t in range(len(V) - 2, -1, -1):
36         opt.insert(0, V[t + 1][previous]["prev"])
37         previous = V[t + 1][previous]["prev"]
38
39     print ('The steps of states are ' + ' '.join(opt) + ' with highest probability of %s' % max_prob)
40
41 def dptable(V):
42     # Print a table of steps from dictionary
43     yield " ".join(("%12d" % i) for i in range(len(V)))
44     for state in V:
45         yield "%.7s: " % state + " ".join("%.7s" % ("%f" % v[state]["prob"]) for v in V)


The function viterbi takes the following arguments: obs is the sequence of observations, e.g. ['normal', 'cold', 'dizzy']; states is the set of hidden states; start_p is the start probability; trans_p are the transition probabilities; and emit_p are the emission probabilities. For simplicity of code, we assume that the observation sequence obs is non-empty and that trans_p[i][j] and emit_p[i][j] is defined for all states i,j.

In the running example, the forward/Viterbi algorithm is used as follows:

viterbi(obs,
states,
start_p,
trans_p,
emit_p)


The output of the script is

\$ python viterbi_example.py
0          1          2
Healthy: 0.30000 0.08400 0.00588
Fever: 0.04000 0.02700 0.01512
The steps of states are Healthy Healthy Fever with highest probability of 0.01512


This reveals that the observations ['normal', 'cold', 'dizzy'] were most likely generated by states ['Healthy', 'Healthy', 'Fever']. In other words, given the observed activities, the patient was most likely to have been healthy both on the first day when he felt normal as well as on the second day when he felt cold, and then he contracted a fever the third day.

The operation of Viterbi's algorithm can be visualized by means of a trellis diagram. The Viterbi path is essentially the shortest path through this trellis.