Purpose
Viterbi finds the single most likely hidden-state sequence q1∗,q2∗,…,qT∗ given an observation sequence o1,o2,…,oT. It is a dynamic programming algorithm: at each timestep, for each state, it stores the best path probability reaching that state and a backpointer.
Components
δj(t): the probability of the most likely path reaching state j at time t, accounting for observations o1 through ot.
ψj(t): the backpointer — which state at t−1 produced the best path to state j at time t.
Algorithm
Initialisation (t=1)
For each state j:
δj(1)=πj⋅bj(o1)ψj(1)=0
Recursion (t=2,3,…,T)
For each state j:
δj(t)=maxi[δi(t−1)⋅aij⋅bj(ot)]
ψj(t)=argmaxi[δi(t−1)⋅aij]
Note: bj(ot) is the same for all i, so it can be pulled outside the max. The argmax is over δi(t−1)⋅aij only.
Termination (t=T)
Best path probability: P∗=maxiδi(T)
Final state: qT∗=argmaxiδi(T)
Backtracking (t=T−1 down to 1)
qt∗=ψqt+1∗(t+1)
Read the backpointer chain backwards to reconstruct the optimal state sequence.
Trellis Layout
Draw a grid: rows = states, columns = timesteps. Fill each cell with δj(t) and ψj(t). Circle the maximum in each column. Draw arrows from each cell to its backpointer source. After termination, trace arrows backwards from the final state.
Log-Space Implementation
In practice, use log-probabilities to prevent underflow:
δj(t)=maxi[δi(t−1)+logaij+logbj(ot)]
Products become sums. The argmax result is identical. For exam purposes, you can work in either space — log is safer for long sequences.
Worked Example: 2-State Model, 3 Timesteps
Given: S={1,2}, V={A,B}, observations = [A,B]
π=[0.6,0.4]A=[0.70.40.30.6]B=[0.50.90.50.1]
t=1, observation A
δ1(1)=0.6×0.5=0.30ψ1(1)=0
δ2(1)=0.4×0.9=0.36ψ2(1)=0
Best at t=1: state 2, δ=0.36.
t=2, observation B
For state 1:
δ1(2)=max[0.30×0.7×0.5,0.36×0.4×0.5]=max[0.105,0.072]=0.105
ψ1(2)=1
For state 2:
δ2(2)=max[0.30×0.3×0.1,0.36×0.6×0.1]=max[0.009,0.0216]=0.0216
ψ2(2)=2
Best at t=2: state 1, δ=0.105.
Termination and Backtrack
P∗=max(0.105,0.0216)=0.105, final state q2∗=1.
Backpointer: ψ1(2)=1, so q1∗=1.
Optimal path: [1,1].
Summary
| Step | Formula |
|---|
| Init | δj(1)=πj⋅bj(o1) |
| Recursion | δj(t)=maxi[δi(t−1)⋅aij⋅bj(ot)] |
| Backpointer | ψj(t)=argmaxi[δi(t−1)⋅aij] |
| Termination | P∗=maxiδi(T), qT∗=argmaxiδi(T) |
| Backtrack | qt∗=ψqt+1∗(t+1) |
| Log form | Sums instead of products, avoids underflow |
Past paper questions: y2022p3q9, y2024p3q8, y2025p3q9