Viterbi algorithm: Difference between revisions

Content deleted Content added
Gherson2 (talk | contribs)
Undid revision 1113840558 by Gherson2 (talk)
Tags: Undo Reverted
Rescuing 0 sources and tagging 1 as dead.) #IABot (v2.0.9.5
 
(42 intermediate revisions by 32 users not shown)
Line 1:
{{short description|Algorithm for finding the mostFinds likely sequence of hidden states}}
{{Technical|date=September 2023}}
The '''Viterbi algorithm''' is a [[dynamic programming]] [[algorithm]] for obtaining the [[Maximum a posteriori estimation|maximum a posteriori probability estimate]] of the most [[likelihood function|likely]] sequence of hidden states—called the '''Viterbi path'''—that results in a sequence of observed events, especially in the context of [[Markov information source]]s and [[hidden Markov model]]s (HMM).
 
The '''Viterbi algorithm''' is a [[dynamic programming]] [[algorithm]] that finds the most likely sequence of hidden events that would explain a sequence of observed events. The result of the algorithm is often called the '''Viterbi path'''. It is most commonly used with [[hidden Markov model]]s (HMMs). For example, if a doctor observes a patient's symptoms over several days (the observed events), the Viterbi algorithm could determine the most probable sequence of underlying health conditions (the hidden events) that caused those symptoms.
The algorithm has found universal application in decoding the [[convolutional code]]s 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]],<ref>Xavier Anguera et al., [http://www1.icsi.berkeley.edu/~vinyals/Files/taslp2011a.pdf "Speaker Diarization: A Review of Recent Research"], retrieved 19. August 2010, IEEE TASLP</ref> [[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.
 
The algorithm has found universal application in decoding the [[convolutional code]]s used in both [[Code-division multiple access|CDMA]] and [[GSM]] digital cellular, [[Dial-up Internet access|dial-up]] modems, satellite, deep-space communications, and [[802.11]] wireless LANs. It is also commonly used in [[speech recognition]], [[speech synthesis]], [[Speaker diarisation|diarization]],<ref>Xavier Anguera et al., [http://www1.icsi.berkeley.edu/~vinyals/Files/taslp2011a.pdf "Speaker Diarization: A Review of Recent Research"] {{Webarchive|url=https://web.archive.org/web/20160512200056/http://www1.icsi.berkeley.edu/~vinyals/Files/taslp2011a.pdf |date=2016-05-12 }}, retrieved 19. August 2010, IEEE TASLP</ref> [[keyword spotting]], [[computational linguistics]], and [[bioinformatics]]. For instance, in [[speech-to-text]] (speech recognition), the acoustic signal is the observed sequence, and a string of text is the "hidden cause" of that 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 [[Convolution code|convolutional codes]] over noisy digital communication links.<ref>[https://arxiv.org/abs/cs/0504020v2 29 Apr 2005, G. David Forney Jr: The Viterbi Algorithm: A Personal History]</ref> It has, however, a history of [[multiple invention]], with at least seven independent discoveries, including those by Viterbi, [[Needleman–Wunsch algorithm|Needleman and Wunsch]], and [[Wagner–Fischer algorithm|Wagner and Fischer]].<ref name="slp">{{cite book |author1=Daniel Jurafsky |author2=James H. Martin |title=Speech and Language Processing |publisher=Pearson Education International |page=246}}</ref><!-- Jurafsky and Martin specifically refer to the papers that presented the Needleman–Wunsch and Wagner–Fischer algorithms, hence the wikilinks to those--> It was introduced to [[Naturalnatural Languagelanguage Processingprocessing]] as a method of [[part-of-speech tagging]] as early as 1987.
 
''Viterbi path'' and ''Viterbi algorithm'' have become standard terms for the application of dynamic programming algorithms to maximization problems involving probabilities.<ref name="slp" />
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".<ref>{{Cite conference | doi = 10.3115/1220355.1220379| title = Efficient parsing of highly ambiguous context-free grammars with bit vectors| conference = Proc. 20th Int'l Conf. on Computational Linguistics (COLING)| pages = <!--162-->| year = 2004| last1 = Schmid | first1 = Helmut| url = http://www.aclweb.org/anthology/C/C04/C04-1024.pdf| doi-access = free}}</ref><ref>{{Cite conference| doi = 10.3115/1073445.1073461| title = A* parsing: fast exact Viterbi parse selection| conference = Proc. 2003 Conf. of the North American Chapter of the Association for Computational Linguistics on Human Language Technology (NAACL)| pages = 40–47| year = 2003| last1 = Klein | first1 = Dan| last2 = Manning | first2 = Christopher D.| url = http://ilpubs.stanford.edu:8090/532/1/2002-16.pdf| doi-access = free}}</ref><ref>{{Cite journal | doi = 10.1093/nar/gkl200| title = AUGUSTUS: Ab initio prediction of alternative transcripts| journal = Nucleic Acids Research| volume = 34| issue = Web Server issue| pages = W435–W439| year = 2006| last1 = Stanke | first1 = M.| last2 = Keller | first2 = O.| last3 = Gunduz | first3 = I.| last4 = Hayes | first4 = A.| last5 = Waack | first5 = S.| last6 = Morgenstern | first6 = B. | pmid=16845043 | pmc=1538822}}</ref> Another application is in [[Optical motion tracking|target tracking]], where the track is computed that assigns a maximum likelihood to a sequence of observations.<ref>{{cite conference |author=Quach, T.; Farooq, M. |chapter=Maximum Likelihood Track Formation with the Viterbi Algorithm |title=Proceedings of 33rd IEEE Conference on Decision and Control |date=1994 |volume=1 |pages=271–276|doi=10.1109/CDC.1994.410918}}</ref>
 
== ExtensionsAlgorithm ==
Given a hidden Markov model with a set of hidden states <math>S</math> and a sequence of <math>T</math> observations <math>o_0, o_1, \dots, o_{T-1}</math>, the Viterbi algorithm finds the most likely sequence of states that could have produced those observations. At each time step <math>t</math>, the algorithm solves the subproblem where only the observations up to <math>o_t</math> are considered.
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 variable]]s in a large number of [[graphical model]]s, e.g. [[Bayesian network]]s, [[Markov random field]]s and [[conditional random field]]s. The latent variables need, in general, to be connected in a way somewhat similar to an [[hidden Markov model]] (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]]).
 
Two matrices of size <math>T \times \left|{S}\right|</math> are constructed:
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]].<ref>{{cite journal |author1=Qi Wang |author2=Lei Wei |author3=Rodney A. Kennedy |year=2002 |title=Iterative Viterbi Decoding, Trellis Shaping, and Multilevel Structure for High-Rate Parity-Concatenated TCM |journal=IEEE Transactions on Communications |volume=50 |pages=48–55 |doi=10.1109/26.975743}}</ref> Iterative Viterbi decoding works by iteratively invoking a modified Viterbi algorithm, reestimating the score for a filler until convergence.
* <math>P_{t,s}</math> contains the maximum probability of ending up at state <math>s</math> at observation <math>t</math>, out of all possible sequences of states leading up to it.
* <math>Q_{t,s}</math> tracks the previous state that was used before <math>s</math> in this maximum probability state sequence.
 
Let <math>\pi_s</math> and <math>a_{r,s}</math> be the initial and transition probabilities respectively, and let <math>b_{s,o}</math> be the probability of observing <math>o</math> at state <math>s</math>. Then the values of <math>P</math> are given by the recurrence relation<ref>Xing E, slide 11.</ref>
An alternative algorithm, the [[Lazy Viterbi algorithm]], has been proposed.<ref>{{cite conference|url=http://people.csail.mit.edu/jonfeld/pubs/lazyviterbi.pdf |title=A fast maximum-likelihood decoder for convolutional codes |date=December 2002 |conference= Vehicular Technology Conference |conference-url=http://www.ieeevtc.org/ |pages=371–375 |doi=10.1109/VETECF.2002.1040367}}</ref> 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 (graph)|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{{clarify|date=November 2017}} to parallelize in hardware.
<math display="block">
P_{t,s} =
\begin{cases}
\pi_s \cdot b_{s,o_t} & \text{if } t=0, \\
\max_{r \in S} \left(P_{t-1,r} \cdot a_{r,s} \cdot b_{s,o_t} \right) & \text{if } t>0.
\end{cases}
</math>
The formula for <math>Q_{t,s}</math> is identical for <math>t>0</math>, except that <math>\max</math> is replaced with [[Arg max|<math>\arg\max</math>]], and <math>Q_{0,s} = 0</math>.
The Viterbi path can be found by selecting the maximum of <math>P</math> at the final timestep, and following <math>Q</math> in reverse.
 
== Pseudocode ==
This algorithm generates a path <math> X=(x_1,x_2,\ldots,x_T) </math>, which is a sequence of states <math>x_n \in S=\{s_1,s_2,\dots,s_K\}</math> that generate the observations <math> Y=(y_1,y_2,\ldots, y_T) </math> with <math>y_n \in O=\{o_1,o_2,\dots,o_N\}</math>, where <math>N</math> is the number of possible observations in the observation space <math>O</math>.
 
'''function''' Viterbi(states, init, trans, emit, obs) '''is'''
Two 2-dimensional tables of size <math>K \times T</math> are constructed:
'''input''' states: S hidden states
* Each element <math>T_1[i,j]</math> of <math>T_1</math> stores the probability of the most likely path so far <math> \hat{X}=(\hat{x}_1,\hat{x}_2,\ldots,\hat{x}_j) </math> with <math>\hat{x}_j=s_i </math> that generates <math> Y=(y_1,y_2,\ldots, y_j)</math>.
'''input''' init: initial probabilities of each state
* Each element <math>T_2[i,j] </math> of <math>T_2 </math> stores <math>\hat{x}_{j-1} </math> of the most likely path so far <math> \hat{X}=(\hat{x}_1,\hat{x}_2,\ldots,\hat{x}_{j-1},\hat{x}_j = s_i)</math> <math>\forall j, 2\leq j \leq T </math>
'''input''' trans: S × S transition matrix
'''input''' emit: S × O emission matrix
'''input''' obs: sequence of T observations
prob ← T × S matrix of zeroes
prev ← empty T × S matrix
'''for''' '''each''' state s '''in''' states '''do'''
prob[0][s] = init[s] * emit[s][obs[0]]
'''for''' t = 1 '''to''' T - 1 '''inclusive do''' ''// t = 0 has been dealt with already''
'''for''' '''each''' state s '''in''' states '''do'''
'''for''' '''each''' state r '''in''' states '''do'''
new_prob ← prob[t - 1][r] * trans[r][s] * emit[s][obs[t]]
'''if''' new_prob > prob[t][s] '''then'''
prob[t][s] ← new_prob
prev[t][s] ← r
path ← empty array of length T
path[T - 1] ← the state s with maximum prob[T - 1][s]
'''for''' t = T - 2 '''to''' 0 '''inclusive do'''
path[t] ← prev[t + 1][path[t + 1]]
'''return''' path
'''end'''
 
The time complexity of the algorithm is <math>O(T\times\left|{S}\right|^2)</math>. If it is known which state transitions have non-zero probability, an improved bound can be found by iterating over only those <math>r</math> which link to <math>s</math> in the inner loop. Then using [[amortized analysis]] one can show that the complexity is <math>O(T\times(\left|{S}\right| + \left|{E}\right|))</math>, where <math>E</math> is the number of edges in the graph, i.e. the number of non-zero entries in the transition matrix.
The table entries <math> T_1[i,j],T_2[i,j]</math> are filled by increasing order of <math>K\cdot j+i </math>:
 
:<math>T_1[i,j]=\max_{k}{(T_1[k,j-1]\cdot A_{ki}\cdot B_{iy_j})} </math>,
:<math>T_2[i,j]=\operatorname{argmax}_{k}{(T_1[k,j-1]\cdot A_{ki} \cdot B_{iy_j})} </math>,
 
with <math>A_{ki}</math> and <math>B_{iy_j}</math> as defined below. Note that <math>B_{iy_j}</math> does not need to appear in the latter expression, as it's non-negative and independent of <math>k</math> and thus does not affect the argmax.
 
;Input:
* The [[observation space]] <math> O=\{o_1,o_2,\dots,o_N\}</math>,
* the [[state space]] <math> S=\{s_1,s_2,\dots,s_K\} </math>,
* an array of initial probabilities <math> \Pi = (\pi_1,\pi_2,\dots,\pi_K)</math> such that <math> \pi_i </math> stores the probability that <math> x_1 = s_i </math>,
* a sequence of observations <math> Y=(y_1,y_2,\ldots, y_T) </math> such that <math> y_t=o_i </math> if the observation at time <math> t </math> is <math> o_i </math>,
* [[Stochastic matrix|transition matrix]] <math> A </math> of size <math> K\times K </math> such that <math> A_{ij} </math> stores the [[transition probability]] of transiting from state <math> s_i </math> to state <math> s_j </math>,
* [[Hidden Markov model|emission matrix]] <math> B </math> of size <math> K\times N </math> such that <math> B_{ij} </math> stores the probability of observing <math> o_j </math> from state <math> s_i </math>.
 
;Output
* The most likely hidden state sequence <math> X=(x_1,x_2,\ldots,x_T) </math>
'''function''' ''VITERBI''<math>(O,S,\Pi,Y,A,B):X</math>
'''for''' each state <math>i=1,2,\ldots,K</math> '''do'''
<math>T_1[i,1]\leftarrow\pi_i\cdot B_{iy_1}</math>
<math>T_2[i,1]\leftarrow 0</math>
'''end for'''
'''for''' each observation <math>j = 2,3,\ldots,T</math> '''do'''
'''for''' each state <math>i =1,2,\ldots,K</math> '''do'''
{{nowrap|<math>T_1[i,j] \gets \max_{k}{(T_1[k,j-1]\cdot A_{ki} \cdot B_{iy_j})} </math>}}
{{nowrap|<math>T_2[i,j] \gets \arg\max_{k}{(T_1[k,j-1]\cdot A_{ki} \cdot B_{iy_j}) } </math>}}
'''end for'''
'''end for'''
{{nowrap|<math>z_T \gets \arg\max_{k}{(T_1[k,T])} </math>}}
<math>x_T\leftarrow s_{z_T}</math>
'''for''' <math>j=T,T-1,\ldots,2</math> '''do'''
<math>z_{j-1}\leftarrow T_2[z_j,j]</math>
<math>x_{j-1}\leftarrow s_{z_{j-1}}</math>
'''end for'''
'''return''' <math>X</math>
'''end function'''
 
Restated in a succinct near-[[Python (programming language)|Python]]:
'''function''' ''viterbi''<math>(O, S, \Pi, Tm, Em): best\_path </math> Tm: transition matrix Em: emission matrix
<math>trellis \leftarrow matrix(length(S), length(O))</math> To hold probability of each state given each observation
<math>pointers \leftarrow matrix(length(S), length(O))</math> To hold backpointer to best prior state
'''for''' s '''in''' <math>range(length(S))</math>: Determine each hidden state's probability at time 0…
<math>trellis[s, 0] \leftarrow \Pi[s] * Em[s, O[0]]</math>
'''for''' o '''in''' <math>range(1, length(O))</math>: …and after, tracking each state's most likely prior state, k
'''for''' s '''in''' <math>range(length(S))</math>:
<math>k \leftarrow \arg\max(k\ \mathsf{in}\ trellis[k, o-1] * Tm[k, s] * Em[s, o])</math>
<math>trellis[s, o] \leftarrow trellis[k, o-1] * Tm[k, s] * Em[s, o]</math>
<math>pointers[s, o] \leftarrow k</math>
<math>best\_path \leftarrow list()</math>
<math>k \leftarrow \arg\max(k\ \mathsf{in}\ trellis[k, length(O)-1] )</math> Find k of best final state
'''for''' o '''in''' <math>range(length(O)-1, -1, -1)</math>: Backtrack from last observation
<math>best\_path.insert(0, S[k])</math> Insert previous state on most likely path
<math>k \leftarrow pointers[k, o]</math> Use backpointer to find best previous state
'''return''' ''best_path''
 
;Explanation:
Suppose we are given a [[hidden Markov model]] (HMM) with state space <math>S</math>, initial probabilities <math>\pi_i</math> of being in state <math>i</math> and transition probabilities <math>a_{i,j}</math> of transitioning from state <math>i</math> to state <math>j</math>. Say, we observe outputs <math>y_1,\dots, y_T</math>. The most likely state sequence <math>x_1,\dots,x_T</math> that produces the observations is given by the recurrence relations<ref>Xing E, slide 11.</ref>
 
:<math>
\begin{align}
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{align}
</math>
 
Here <math>V_{t,k}</math> is the probability of the most probable state sequence <math>\mathrm{P}\big(x_1,\dots,x_t,y_1,\dots, y_t\big)</math> responsible for the first <math>t</math> observations that have <math>k</math> as its final state. The Viterbi path can be retrieved by saving back pointers that remember which state <math>x</math> was used in the second equation. Let <math>\mathrm{Ptr}(k,t)</math> be the function that returns the value of <math>x</math> used to compute <math>V_{t,k}</math> if <math>t > 1</math>, or <math>k</math> if <math>t=1</math>. Then
 
:<math>
\begin{align}
x_T &= \arg\max_{x \in S} (V_{T,x}), \\
x_{t-1} &= \mathrm{Ptr}(x_t,t).
\end{align}
</math>
 
Here we're using the standard definition of [[arg max]].
 
The complexity of this implementation is <math>O(T\times\left|{S}\right|^2)</math>. 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 <math>k</math> to <math>j</math>). Then using [[amortized analysis]] one can show that the complexity is <math>O(T\times(\left|{S}\right| + \left|{E}\right|))</math>, where <math>E</math> is the number of edges in the graph.
 
== Example ==
ConsiderA adoctor villagewishes whereto alldetermine villagerswhether arepatients eitherare healthy or have a fever,. andThe only theinformation villagethe doctor can determineobtain whether each has a fever. The doctor diagnoses feveris by asking patients how they feel. The villagerspatients may only answerreport that they either feel normal, dizzy, or cold.
 
TheIt doctoris believesbelieved that the health condition of the patients operates as a discrete [[Markov chain]]. There are two states, "Healthyhealthy" and "Feverfever", but the doctor cannot observe them directly; they are ''hidden'' from the doctor. On each day, there is a certainthe chance that a patient will telltells the doctor "I feel normal", "I feel cold", or "I feel dizzy", dependingdepends only on the patient's health condition on that day.
 
The ''observations'' (normal, cold, dizzy) along with athe ''hidden'' statestates (healthy, fever) form a hidden Markov model (HMM),. andFrom canpast beexperience, representedthe asprobabilities followsof inthis themodel [[Pythonhave (programmingbeen language)|Pythonestimated programming language]]as:
<pre>
<syntaxhighlight lang="python">
obsinit = ({"normalHealthy": 0.6, "coldFever",: "dizzy")0.4}
trans = {
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_pemit = {
"Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1},
"Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6},
}
</pre>
</syntaxhighlight>
In this piece of code, <code>start_pinit</code> represents the doctor's belief about whichhow statelikely the HMMpatient is into whenbe thehealthy patientinitially. first visits (all the doctor knows isNote that the patient tends to be healthy). The particular probability distribution used here is not the equilibrium one, which iswould (given the transition probabilities) approximatelybe <code>{'Healthy': 0.57, 'Fever': 0.43}</code> according to the transition probabilities. The transition probabilities <code>transition_ptrans</code> representsrepresent the change of the health condition in the underlying Markov chain. In this example, a patient who is healthy today has only a 30% chance of having a fever tomorrow. The emission probabilities <code>emit_pemit</code> representsrepresent how likely each possible observation (normal, cold, or dizzy) is, given the underlying condition (healthy or fever). A patient who is healthy has a 50% chance of feeling normal; one who has a fever has a 60% chance of feeling dizzy.
 
[[File:An example of HMM.png|thumb|center|300px|Graphical representation of the given HMM]]
 
A particular patient visits three days in a row, and thereports doctor discovers that the patient feelsfeeling normal on the first day, cold on the second day, and dizzy on the third day. 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.
 
Firstly, the probabilities of being healthy or having a fever on the first day are calculated. The probability that a patient will be healthy on the first day and report feeling normal is <math>0.6 \times 0.5 = 0.3</math>. Similarly, the probability that a patient will have a fever on the first day and report feeling normal is <math>0.4 \times 0.1 = 0.04</math>.
<syntaxhighlight lang="python" line="1">
def viterbi(obs, states, start_p, trans_p, emit_p):
V = [{}]
for st in states:
V[0] [st] = {"prob": start_p[st] * emit_p[st] [obs[0]], "prev": None}
# Run Viterbi when t > 0
for t in range(1, len(obs)):
V.append({})
for st in states:
max_tr_prob = V[t - 1] [states[0]] ["prob"] * trans_p[states[0]] [st]
prev_st_selected = states[0]
for prev_st in states[1:]:
tr_prob = V[t - 1] [prev_st] ["prob"] * trans_p[prev_st] [st]
if tr_prob > max_tr_prob:
max_tr_prob = tr_prob
prev_st_selected = prev_st
 
The probabilities for each of the following days can be calculated from the previous day directly. For example, the highest chance of being healthy on the second day and reporting to be cold, following reporting being normal on the first day, is the maximum of <math>0.3 \times 0.7 \times 0.4 = 0.084</math> and <math>0.04 \times 0.4 \times 0.4 = 0.0064</math>. This suggests it is more likely that the patient was healthy for both of those days, rather than having a fever and recovering.
max_prob = max_tr_prob * emit_p[st] [obs[t]]
V[t] [st] = {"prob": max_prob, "prev": prev_st_selected}
 
The rest of the probabilities are summarised in the following table:
for line in dptable(V):
print(line)
 
{| class="wikitable"
opt = []
|-
max_prob = 0.0
! Day !! 1 best_st!! =2 None!! 3
|-
# Get most probable state and its backtrack
! Observation
for st, data in V[-1].items():
| Normal || Cold || Dizzy
if data["prob"] > max_prob:
|-
max_prob = data["prob"]
! Healthy
best_st = st
| '''0.3'''|| '''0.084'''|| 0.00588
opt.append(best_st)
|-
previous = best_st
! Fever
| 0.04 || 0.027 || '''0.01512'''
|}
 
From the table, it can be seen that the patient most likely had a fever on the third day. Furthermore, there exists a sequence of states ending on "fever", of which the probability of producing the given observations is 0.01512. This sequence is precisely (healthy, healthy, fever), which can be found be tracing back which states were used when calculating the maxima (which happens to be the best guess from each day but will not always be). In other words, given the observed activities, the patient was most likely to have been healthy on the first day and also on the second day (despite feeling cold that day), and only to have contracted a fever on the third day.
# Follow the backtrack till the first observation
for t in range(len(V) - 2, -1, -1):
opt.insert(0, V[t + 1] [previous] ["prev"])
previous = V[t + 1] [previous] ["prev"]
 
The operation of Viterbi's algorithm can be visualized by means of a [[Trellis diagram#Trellis diagram|trellis diagram]]. The Viterbi path is essentially the shortest path through this trellis.
print ("The steps of states are " + " ".join(opt) + " with highest probability of %s" % max_prob)
 
== Extensions ==
def dptable(V):
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 variable]]s in a large number of [[graphical model]]s, e.g. [[Bayesian network]]s, [[Markov random field]]s and [[conditional random field]]s. The latent variables need, in general, to be connected in a way somewhat similar to a [[hidden Markov model]] (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]]).
# Print a table of steps from dictionary
yield " " * 5 + " ".join(("%3d" % i) for i in range(len(V)))
for state in V[0]:
yield "%.7s: " % state + " ".join("%.7s" % ("%lf" % v[state] ["prob"]) for v in V)
</syntaxhighlight>
The function <code>viterbi</code> takes the following arguments: <code>obs</code> is the sequence of observations, e.g. <code>['normal', 'cold', 'dizzy']</code>; <code>states</code> is the set of hidden states; <code>start_p</code> is the start probability; <code>trans_p</code> are the transition probabilities; and <code>emit_p</code> are the emission probabilities. For simplicity of code, we assume that the observation sequence <code>obs</code> is non-empty and that <code>trans_p[i] [j]</code> and <code>emit_p[i] [j]</code> is defined for all states i,j.
 
With an 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]].<ref>{{cite journal |author1=Qi Wang |author2=Lei Wei |author3=Rodney A. Kennedy |year=2002 |title=Iterative Viterbi Decoding, Trellis Shaping, and Multilevel Structure for High-Rate Parity-Concatenated TCM |journal=IEEE Transactions on Communications |volume=50 |pages=48–55 |doi=10.1109/26.975743}}</ref> Iterative Viterbi decoding works by iteratively invoking a modified Viterbi algorithm, reestimating the score for a filler until convergence.
In the running example, the forward/Viterbi algorithm is used as follows:
 
An alternative algorithm, the [[Lazy Viterbi algorithm]], has been proposed.<ref>{{cite conference |date=December 2002 |title=A fast maximum-likelihood decoder for convolutional codes |url=http://people.csail.mit.edu/jonfeld/pubs/lazyviterbi.pdf |conference=Vehicular Technology Conference |pages=371–375 |doi=10.1109/VETECF.2002.1040367 |conference-url=http://www.ieeevtc.org/}}</ref> 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 (graph)|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{{clarify|date=November 2017}} to parallelize in hardware.
<syntaxhighlight lang="python">
viterbi(obs,
states,
start_p,
trans_p,
emit_p)
 
== Soft output Viterbi algorithm ==
</syntaxhighlight>
 
{{Unreferenced section|date=September 2023}}
The output of the script is
 
<syntaxhighlight lang="console">
$ 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
</syntaxhighlight>
 
This reveals that the observations <code>['normal', 'cold', 'dizzy']</code> were most likely generated by states <code>['Healthy', 'Healthy', 'Fever']</code>. In other words, given the observed activities, the patient was most likely to have been healthy on the first day and also on the second day (despite feeling cold that day), and only to have contracted a fever on the third day.
 
The operation of Viterbi's algorithm can be visualized by means of a
[[Trellis diagram#Trellis diagram|trellis diagram]]. The Viterbi path is essentially the shortest
path through this trellis.
 
== Soft output Viterbi algorithm ==
The '''soft output Viterbi algorithm''' ('''SOVA''') is a variant of the classical Viterbi algorithm.
 
Line 224 ⟶ 139:
 
== References ==
{{Reflist}}
<references />
 
== General references ==
* {{cite journal |doi=10.1109/TIT.1967.1054010 |author=Viterbi AJ |title=Error bounds for convolutional codes and an asymptotically optimum decoding algorithm |journal=IEEE Transactions on Information Theory |volume=13 |issue=2 |pages=260–269 |date=April 1967 }} (note: the Viterbi decoding algorithm is described in section IV.) Subscription required.
* {{cite book |vauthors=Feldman J, Abou-Faycal I, Frigo M |title=Proceedings IEEE 56th Vehicular Technology Conference |chapter=A Fastfast Maximummaximum-Likelihoodlikelihood Decoderdecoder for Convolutionalconvolutional Codescodes |journaltitle=Proceedings IEEE 56th Vehicular Technology Conference |volume=1 |pages=371–375 |year=2002 |doi=10.1109/VETECF.2002.1040367|isbn=978-0-7803-7467-6 |citeseerx=10.1.1.114.1314 |s2cid=9783963 }}
* {{cite journal |doi=10.1109/PROC.1973.9030 |author=Forney GD |title=The Viterbi algorithm |journal=Proceedings of the IEEE |volume=61 |issue=3 |pages=268–278 |date=March 1973 }} Subscription required.
* {{Cite book | last1=Press | first1=WH | last2=Teukolsky | first2=SA | last3=Vetterling | first3=WT | last4=Flannery | first4=BP | year=2007 | title=Numerical Recipes: The Art of Scientific Computing | edition=3rd | publisher=Cambridge University Press | ___location=New York | isbn=978-0-521-88068-8 | chapter=Section 16.2. Viterbi Decoding | chapter-url=http://apps.nrbook.com/empanel/index.html#pg=850 | access-date=2011-08-17 | archive-date=2011-08-11 | archive-url=https://web.archive.org/web/20110811154417/http://apps.nrbook.com/empanel/index.html#pg=850 | url-status=dead }}
* {{cite journal |author=Rabiner LR |title=A tutorial on hidden Markov models and selected applications in speech recognition |journal=Proceedings of the IEEE |volume=77 |issue=2 |pages=257–286 |date=February 1989 |doi=10.1109/5.18626|citeseerx=10.1.1.381.3454 |s2cid=13618539 }} (Describes the forward algorithm and Viterbi algorithm for HMMs).
* Shinghal, R. and [[Godfried Toussaint|Godfried T. Toussaint]], "Experiments in text recognition with the modified Viterbi algorithm," ''IEEE Transactions on Pattern Analysis and Machine Intelligence'', Vol. PAMI-l, April 1979, pp.&nbsp;184–193.
* Shinghal, R. and [[Godfried Toussaint|Godfried T. Toussaint]], "The sensitivity of the modified Viterbi algorithm to the source statistics," ''IEEE Transactions on Pattern Analysis and Machine Intelligence'', vol. PAMI-2, March 1980, pp.&nbsp;181–185.
Line 246 ⟶ 161:
* [https://github.com/xukmin/viterbi C++]
* [http://pcarvalho.com/forward_viterbi/ C#]
* [http://www.cs.stonybrook.edu/~pfodor/viterbi/Viterbi.java Java] {{Webarchive|url=https://web.archive.org/web/20140504055101/http://www.cs.stonybrook.edu/~pfodor/viterbi/Viterbi.java |date=2014-05-04 }}
* [https://adrianulbona.github.io/hmm/ Java 8]
* [https://juliahub.com/ui/Packages/HMMBase/8HxY5/ Julia (HMMBase.jl)]
* [https://metacpan.org/module/Algorithm::Viterbi Perl]
* [http://www.cs.stonybrook.edu/~pfodor/viterbi/viterbi.P Prolog] {{Webarchive|url=https://web.archive.org/web/20120502010115/http://www.cs.stonybrook.edu/~pfodor/viterbi/viterbi.P |date=2012-05-02 }}
* [https://hackage.haskell.org/package/hmm-0.2.1.1/docs/src/Data-HMM.html#viterbi Haskell]
* [https://github.com/nyxtom/viterbi Go]
* [http://tuvalu.santafe.edu/~simon/styled-8/ SFIHMM]{{Dead link|date=August 2025 |bot=InternetArchiveBot |fix-attempted=yes }} includes code for Viterbi decoding.
 
[[Category:Eponymous algorithms of mathematics]]
[[Category:Error detection and correction]]
[[Category:Dynamic programming]]