800. Score a sequence with the HMM forward algorithm
Why it matters HMMs still power speech alignment, part-of-speech tagging and the CTC-style dynamic programs used in ASR.
A hidden Markov model has hidden states that move by a transition matrix and emit observations. The forward algorithm adds up the probability of every hidden path in O(T S^2) instead of S^T.
Write hmm_forward(pi, A, B, obs). pi has shape (S,) (start probabilities), A has shape (S, S) with A[i, j] = P(next state j | state i), B has shape (S, V) with B[s, o] = P(observation o | state s), and obs is a list of observation ids. Return log P(obs) as a float.
alpha_0 = pi * B[:, obs[0]], then alpha_t = (alpha_{t-1} @ A) * B[:, obs[t]]. Rescale alpha to sum 1 at every step and add the log of each scale factor, so long sequences do not underflow.
def hmm_forward(pi, A, B, obs)Example 1
Input: hmm_forward([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])
Output: -2.0826
Example 2
Input: pi = [0.6, 0.4], A = [[0.7, 0.3], [0.4, 0.6]], B = [[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]], obs = [0]
Output: -1.07881
Constraints
pihas shape(S,)Ahas shape(S, S)Bhas shape(S, V)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Keep a vector alpha with one entry per hidden state.
Hint 2
Each step: alpha @ A, then multiply by the emission column for the current observation.
Hint 3
Divide alpha by its sum every step and accumulate the log of that sum.
Common mistakes
- Multiplying probabilities for 2000 steps without rescaling, which underflows to 0 and log gives -inf.
- Using A.T instead of A, which flips the transition direction.
Understand the idea
alpha_t[s] is the probability of the first t+1 observations AND being in state s at time t. Each step pushes alpha through the transition matrix, then multiplies by how likely state s is to emit the next observation. Summing alpha at the end gives P(obs).
pi = [0.6, 0.4], obs = [0] with B[:, 0] = [0.5, 0.1]. alpha_0 = [0.3, 0.04], so P = 0.34 and log P = log 0.34.
alpha_t = (alpha_{t-1} @ A) * B[:, o_t]; rescale each step and add log scalesShapes and data flow
alpha (S,) @ A (S, S) -> (S,), times B[:, o] (S,)