Decode the best HMM path with Viterbi

Why it matters Constrained decoding, CRF taggers and speech alignment all run Viterbi.

Viterbi finds the most likely hidden state sequence of an HMM by dynamic programming.

Write viterbi(log_init, log_trans, log_emit, obs). log_init is (S,), log_trans is (S, S) with [i, j] = log P(j | i), log_emit is (S, V), obs is a list of observation ids. Return (best_path, best_log_prob). Break ties by the smaller state index.

Signaturedef viterbi(log_init, log_trans, log_emit, obs)

Example

with two states that each emit their own symbol with probability 1 (log 0 elsewhere as -1e9), obs [0, 1, 1] returns path [0, 1, 1].

Understand the idea

An HMM has hidden states that emit observations. Viterbi finds the single most likely hidden path with dynamic programming: for each state, keep only the best score of any path ending there, plus a pointer to where it came from. Worked example in plain probabilities (the code uses logs): init [0.6, 0.4], trans [[0.7, 0.3], [0.4, 0.6]], state 0 emits a with 0.9 and b with 0.1, state 1 emits a with 0.2 and b with 0.8, obs [a, b]. Step 0: delta = [0.6 * 0.9, 0.4 * 0.2] = [0.54, 0.08]. Step 1, state 0: max(0.54 * 0.7, 0.08 * 0.4) = 0.378, times 0.1 gives 0.0378, from state 0. State 1: max(0.54 * 0.3, 0.08 * 0.6) = 0.162, times 0.8 gives 0.1296, from state 0. Best end is state 1, trace back to path [0, 1], probability 0.1296. Rule (logs): delta_0 = log_init + log_emit[:, obs0]; delta_t[j] = max over i of (delta_{t-1}[i] + log_trans[i, j]) + log_emit[j, obs_t]; store the argmax i; trace back from the best final state. argmax picks the smaller index on ties. Used in: speech recognition, part-of-speech tagging and CRF decoding.

Shapes and data flow

delta (S,) -> delta[:, None] + log_trans (S, S) -> max over axis 0 -> (S,)
back (T, S) traced from the last argmax
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleviterbi(np.log([0.5, 0.5]), np.log([[0.5, 0.5], [0.5, 0.5]]), [[0, -1e9], [-1e9, 0]], [0, 1, 1])
  • Sample 2: weatherviterbi(np.log([0.6, 0.4]), np.log([[0.7, 0.3], [0.4, 0.6]]), np.log([[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]]), [...