SLIDE 10 Viterbi Algorithm – Probability Matrix
Fill table entry by entry
for j in range(1, n):
For every column (except the first)
for i in range(0, 3):
For every row
eprob = emission_probs[i, int(seq2[j])]
Probability to observe
tprob1 = transition_probs[0,i] seq2[j] while the state is i
Different probabilities
tprob2 = transition_probs[1,i]
to transition to i
tprob3 = transition_probs[2,i] x = [probs[0, j-1] * tprob1 * eprob,
Store the three
probs[1, j-1] * tprob2 * eprob,
probabilities in variable x
probs[2, j-1] * tprob3 * eprob] smax = np.amax(x)
Compute largest probability
probs[i, j] = smax
Store it in matrix
Digital Medicine I: Introduction to Programming – HMMs Autumn 2019 Böckenhauer, Komm 30 / 42
Viterbi Algorithm – Tracing Matrix
Tracing “arrows” in table Additionally store which value was used for the maximum Create matrix to store walk through the table. . .
probs = np.zeros((3, n)) back = np.zeros((3, n)) Same size as probability matrix
Add in loop. . .
smax = np.amax(x) Compute largest probability probs[i, j] = smax Store value imax = np.argmax(x) Compute corresponding index back[i, j] = imax Store index
Digital Medicine I: Introduction to Programming – HMMs Autumn 2019 Böckenhauer, Komm 31 / 42
Viterbi Algorithm – Tracing Matrix
Now run backwards through matrix back Compute largest probability in last column Correspondingly output H, O, or S Then consider the value at the corresponding position at back If there is a “0, ” step from line 0 (upper-left) If there is a “1, ” step from line 1 (mid-left) If there is a “2, ” step from line 2 (lower-left) Continue in column to the left and line back[i, j]
Digital Medicine I: Introduction to Programming – HMMs Autumn 2019 Böckenhauer, Komm 32 / 42
Viterbi Algorithm – Tracing Matrix
Resulting state sequence as vector
result = ["X"] * n
Search maximum entry in last column
x = [probs[0, n-1], probs[1, n-1], probs[2, n-1]] imax = np.argmax(x)
The last entry of the result has to be correspondingly
if imax == 0: result[n-1] = "H" elif imax == 1: result[n-1] = "O" else: result[n-1] = "S"
Digital Medicine I: Introduction to Programming – HMMs Autumn 2019 Böckenhauer, Komm 33 / 42