Compute HMM state posteriors with forward-backward

Why it matters Forward-backward is the E step for HMM training and the core of CTC loss used in speech models.

Forward-backward gives, for every time step, the probability of each hidden state given the whole observation sequence.

Write hmm_posteriors(init, trans, emit, obs) with probabilities (not logs): init (S,), trans (S, S) with [i, j] = P(j | i), emit (S, V), obs a list of ids. Use scaled recursions: alpha_t normalised to sum 1 at each step with scale c_t, beta computed backward with the same scales. Return (gamma, loglik) where gamma is (T, S) with each row summing to 1 and loglik = sum of log c_t.

Signaturedef hmm_posteriors(init, trans, emit, obs)

Example

if each state emits its own symbol with probability 1, gamma for obs [0, 1] is [[1, 0], [0, 1]].

Understand the idea

Forward-backward tells you, for every time step, how likely each hidden state is given the whole observation sequence, past and future. The forward pass alpha carries evidence from the left, the backward pass beta carries evidence from the right, and gamma is their normalised product. Scaling alpha to sum to 1 at each step avoids underflow, and the log of the scales adds up to the log likelihood. Worked example: init [0.5, 0.5], trans [[0.9, 0.1], [0.1, 0.9]], state 0 emits a with 0.8 and b with 0.2, state 1 the reverse, obs [a, b]. alpha_0 = [0.4, 0.1], c_0 = 0.5, scaled [0.8, 0.2]. alpha_1 = ([0.8, 0.2] @ trans) * [0.2, 0.8] = [0.74, 0.26] * [0.2, 0.8] = [0.148, 0.208], c_1 = 0.356. loglik = ln 0.5 + ln 0.356 = ln 0.178. At the last step gamma = scaled alpha = [0.416, 0.584]. Rule: alpha_t = (alpha_{t-1} @ trans) * emit[:, obs_t], scaled by c_t; beta_T = 1, beta_t = trans @ (emit[:, obs_{t+1}] * beta_{t+1}) / c_{t+1}; gamma_t is alpha_t * beta_t normalised. Used in: Baum-Welch training and speech models.

Shapes and data flow

alpha (T, S) forward, scales c (T,)
beta (T, S) backward
gamma = alpha * beta, rows normalised -> (T, S)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplehmm_posteriors([0.5, 0.5], [[0.5, 0.5], [0.5, 0.5]], [[1, 0], [0, 1]], [0, 1])
  • Sample 2: weatherhmm_posteriors([0.6, 0.4], [[0.7, 0.3], [0.4, 0.6]], [[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]], [0, 1, 2, 2, 0])