---
title: Hidden Markov models
heading: Markov chains with their transition matrices, stationary distributions and dwell times, hidden states seen through noisy observations, the forward algorithm for filtering and likelihoods, Viterbi decoding of the best state path, and training by EM
eyebrow: S14 · Lesson 42 · Hidden Markov models
xp: 50
---

::: hook
A machine is either healthy or failing, and you can't see which; you only see whether its vibration alarm fires, and the alarm is unreliable. Its state persists from hour to hour, so a run of alarms means more than any single one. A hidden Markov model captures exactly this: a state that evolves by a Markov chain, and observations that depend only on the current state. Its algorithms, built on dynamic programming, track the hidden state, score whole sequences and find the most likely path. They were the backbone of speech recognition for decades and are the Viterbi decoder of every convolutional code in S8.
:::

::: play
- A two-state Markov chain leaves state 1 with probability a per step and returns from state 2 with probability b. The probability of being in state 1 after n steps, starting from $p_0$.
- It settles to the stationary value b/(a + b), approaching it geometrically by the factor 1 − a − b each step.
- When a + b > 1 the factor is negative and the approach oscillates; when a and b are small the chain is "sticky" and forgets its start slowly.
:::

```sim plot
view: graph
x: n = 0..30
y: p = 0..1.05
slider: a = 0.01..0.9 step 0.01 = 0.1
slider: b = 0.01..0.9 step 0.01 = 0.2
slider: q = 0..1 step 0.05 = 1
plot: b/(a + b) + (q - b/(a + b))*(1 - a - b)^n | stems | label: P(state 1 at step n)
readout: stationary probability of state 1 = b/(a + b) | digits: 4
readout: mean stay in state 1, steps = 1/a | digits: 4
```

::: predict
## A machine stays healthy from one hour to the next with probability 0.9 and stays faulty with probability 0.8. In the long run, what fraction of hours is it healthy?

- [ ] 90%
- [ ] 50%
- [x] About 67%
- [ ] 80%

::: reveal
In balance, the flow out of healthy equals the flow back: $0.1\pi_H = 0.2\pi_F$, so $\pi_H = 0.2/(0.1 + 0.2)$ = 2/3. Healthy spells last 1/0.1 = 10 hours on average and faulty ones 1/0.2 = 5, which is the same 2:1 ratio.
:::
:::

::: nameit
## Markov chains

A chain with transition matrix $A_{ij} = P(z_{t+1} = j|z_t = i)$ forgets everything but its present state. Its **stationary distribution** π satisfies $\boldsymbol{\pi}^TA = \boldsymbol{\pi}^T$; for two states with leaving probabilities a and b, $\pi_1 = b/(a + b)$, and any start approaches it by the factor $1 - a - b$ per step. Time spent in a state per visit is geometric with mean $1/(1 - A_{ii})$.

## Hidden Markov models

The state $z_t$ follows the chain, and each observation $x_t$ is drawn from an **emission** distribution $p(x_t|z_t)$. The joint probability of a state path and the observations is

$$p(\mathbf{x}, \mathbf{z}) = \pi_{z_1}p(x_1|z_1)\prod_{t=2}^NA_{z_{t-1}z_t}p(x_t|z_t)$$

## The forward algorithm

Summing over all $K^N$ paths is hopeless, but the sum factors. With $\alpha_t(j) = p(x_1, \ldots, x_t, z_t = j)$:

$$\alpha_1(j) = \pi_jp(x_1|j), \qquad \alpha_t(j) = p(x_t|j)\sum_i\alpha_{t-1}(i)A_{ij}$$

Then $p(\mathbf{x}) = \sum_j\alpha_N(j)$, and $\alpha_t(j)/\sum_i\alpha_t(i)$ is the filtered probability of the current state. The cost is about $NK^2$ operations.

## Viterbi and training

Replacing the sum by a max (and remembering which predecessor won) finds the single most probable path: the **Viterbi algorithm**. Training by EM, the Baum–Welch algorithm, adds a backward pass to get each state's posterior at each time and then re-estimates A, π and the emissions from expected counts, exactly as lesson 36 did for mixtures.
:::

::: example
## The machine's alarm fires with probability 0.1 when healthy and 0.7 when faulty. Starting from the stationary distribution, it fires in hours 1 and 2. Run the forward algorithm.

::: solution
1. **Hour 1.**
   $$\begin{aligned} \alpha_1 &= (\tfrac23 \times 0.1,\ \tfrac13 \times 0.7) \\ &= (0.0667, 0.2333) \end{aligned}$$
   so P(faulty) = 0.778 already.
2. **Hour 2, healthy.**
   $$\begin{aligned} \alpha_2(H) &= (0.0667 \times 0.9 \\ &\quad + 0.2333 \times 0.2) \times 0.1 \\ &= 0.0107 \end{aligned}$$
3. **Hour 2, faulty.**
   $$\begin{aligned} \alpha_2(F) &= (0.0667 \times 0.1 \\ &\quad + 0.2333 \times 0.8) \times 0.7 \\ &= 0.1353 \end{aligned}$$
4. **Filter.** The sequence has probability 0.0107 + 0.1353 = 0.146, so
   $$\begin{aligned} P(\text{faulty now}) &= 0.1353/0.146 \\ &= 0.927 \end{aligned}$$

**Answer:** the two alarms have probability 0.146, and the machine is faulty with probability 0.778 after hour 1 and 0.927 after hour 2.
:::
:::

::: example
## What's the most likely state path for those two alarms, and how much work does the forward algorithm save over listing paths for 20 hours?

::: solution
1. **Score the paths.** The four paths score HH 0.0060, HF 0.0047, FH 0.0047 and FF 0.1307, so Viterbi picks faulty–faulty.
2. **Listing paths.** For 20 hours there are
   $$2^{20} = 1{,}048{,}576$$
   paths.
3. **Forward recursion.** It takes about
   $$20 \times 2^2 = 80$$
   multiply-adds.

**Answer:** the most likely path is faulty–faulty, and for 20 hours the forward algorithm's 80 multiply-adds replace a list of 1,048,576 paths.
:::
:::

::: example
## A labeled maintenance log shows a machine healthy for 900 hours, during which it failed 9 times, and faulty for 100 hours, during which it was repaired 30 times. Estimate the hourly transition probabilities, the long-run fraction of time it's faulty, and the mean length of a fault.

::: solution
1. **Count transitions.** With the states known, maximum likelihood just counts:
   $$\begin{aligned} \text{failure} &= 9/900 \\ &= 0.01\ \text{per hour} \\ \text{repair} &= 30/100 \\ &= 0.3\ \text{per hour} \end{aligned}$$
2. **Long-run faulty fraction.**
   $$\begin{aligned} \pi_F &= \frac{0.01}{0.01 + 0.3} \\ &= 3.2\% \end{aligned}$$
3. **Mean fault length.**
   $$1/0.3 = 3.3\ \text{hours}$$
4. **Hidden states.** When the states are hidden, Baum–Welch does the same counting with expected counts from the forward–backward algorithm, the EM of lesson 36 applied to a chain.

**Answer:** failure 0.01 and repair 0.3 per hour; the machine is faulty 3.2% of the time, and a fault lasts 3.3 hours on average.
:::
:::

::: check
given: a = 0.05 | 0.2 | 0.5; b = 0.1 | 0.3 | 0.6
answer: b/(a + b)
tolerance: 0.5%

## A two-state chain leaves state 1 with probability {a} and leaves state 2 with probability {b}. What's the stationary probability of state 1?

::: right
Right. $b/(a + b)$ = {answer}.
:::

::: misses
- [a/(a + b)] That's state 2's share; the rarely-left state gets the larger share.
- [any] Not yet. Balance the flows between the states.
:::
:::

::: check
given: p = 0.5 | 0.9 | 0.99
answer: 1/(1 - p)
tolerance: 0.5%

## A state persists from one step to the next with probability {p}. How many steps does a visit last on average?

::: right
Right. $1/(1 - p)$ = {answer}.
:::

::: misses
- [p/(1 - p)] That counts only the extra steps after the first.
- [any] Not yet. A geometric distribution.
:::
:::

::: check
given: a = 0.1 | 0.3; b = 0.2 | 0.4; q = 0 | 1; n = 2 | 3
answer: b/(a + b) + (q - b/(a + b))*(1 - a - b)^n
tolerance: 0.5%

## The same kind of chain (leaving probabilities {a} and {b}) starts in state 1 with probability {q}. What's the probability of state 1 after {n} steps?

::: right
Right. $\pi_1 + (p_0 - \pi_1)(1 - a - b)^n$ = {answer}.
:::

::: misses
- [b/(a + b)] That's the long-run value; after {n} steps it hasn't fully settled.
- [any] Not yet. The gap to the stationary value shrinks by $1 - a - b$ per step.
:::
:::

::: check
given: p = 0.5 | 0.8; e = 0.05 | 0.2; f = 0.6 | 0.9
answer: (1 - p)*f/((1 - p)*f + p*e)
tolerance: 0.5%

## A machine is healthy with prior probability {p}. An alarm fires with probability {e} when healthy and {f} when faulty. It fires. What's the probability the machine is faulty?

::: right
Right. The first step of the forward algorithm, normalized: {answer}.
:::

::: misses
- [f] That's P(alarm | faulty); weight by the prior.
- [any] Not yet. Bayes' theorem.
:::
:::

::: check
given: p = 0.5 | 0.7; s = 0.8 | 0.95; e = 0.1 | 0.3; f = 0.6 | 0.9
answer: p*e*s*e
tolerance: 0.5%

## A chain starts healthy with probability {p} and stays healthy with probability {s}. Alarms fire with probability {e} when healthy and {f} when faulty. What's the joint probability of "healthy, healthy" with alarms in both hours?

::: right
Right. $\pi_HP(a|H)A_{HH}P(a|H)$ = {answer}.
:::

::: misses
- [p*e*e] Include the transition probability between the hours.
- [any] Not yet. Multiply along the path.
:::
:::

::: check
given: K = 2 | 4 | 10; N = 10 | 50 | 100
answer: N*K^2
tolerance: 0.5%

## Roughly how many multiply-adds does the forward algorithm need for a {K}-state model and {N} observations?

::: right
Right. About $NK^2$ = {answer}.
:::

::: misses
- [K^N] That's the number of paths, which the recursion avoids listing.
- [any] Not yet. K sums of K terms at every step.
:::
:::

::: check
kind: parts
given: a = 0.1 | 0.2; b = 0.2 | 0.4; n = 2 | 3 | 4

## A two-state chain leaves state 1 with probability {a} and state 2 with probability {b} per step. It starts in state 1.

::: part
answer: b/(a + b) + a/(a + b)*(1 - a - b)^n
tolerance: 0.5%

### What is the probability it's in state 1 after {n} steps?

::: misses
- [b/(a + b)] That's the limit; after {n} steps some memory of the start remains.
- [(1 - a)^n] That's the probability of never having left.
- [any] $\pi_1 + \pi_2(1 - a - b)^n$.
:::
:::

::: part
answer: -1/ln(abs(1 - a - b))
unit: steps
tolerance: 0.5%

### What is the time constant of its approach to equilibrium?

::: misses
- [any] The deviation shrinks as $|1 - a - b|^n$.
:::
:::
:::

::: check
kind: derivation
vars: a = 0.01..0.5, b = 0.01..0.5, n = 0..50

## A two-state chain leaves state 1 with probability a and state 2 with probability b, and starts in state 1.

::: step
answer: b/(a + b)

### What is its stationary probability of state 1?
:::

::: step
answer: b/(a + b) + a/(a + b)*(1 - a - b)^n

### What is the probability of state 1 after n steps?
:::

::: right
Right. The second eigenvalue, 1 − a − b, sets how quickly the chain forgets where it started.
:::
:::

::: explain
## Why can the forward algorithm sum over every hidden path without listing them?

::: model
Because of the Markov property, the future depends on the past only through the current state. So all paths that end in the same state at time t can be merged: their total probability, α, is all that later steps need to know. At each step the algorithm updates K numbers, one per state, by summing the K ways to arrive there and multiplying by the new observation's probability. The exponential number of paths is never formed; the work grows linearly with the length of the sequence. Viterbi uses the same merging with a maximum in place of the sum.
:::
:::

::: practice

::: check
given: a = 0.01 | 0.8; b = 0.01 | 0.8
answer: b/(a + b)
tolerance: 0.5%

## Stationary state 1: leave {a}, return {b}?

::: misses
- [any] $b/(a + b)$.
:::
:::

::: check
given: p = 0.3 | 0.5 | 0.8 | 0.9 | 0.99 | 0.999
answer: 1/(1 - p)
tolerance: 0.5%

## Mean visit length, stay probability {p}?

::: misses
- [any] $1/(1 - p)$.
:::
:::

::: check
given: p = 0.1 | 0.95; e = 0.01 | 0.4; f = 0.3 | 0.99
answer: (1 - p)*f/((1 - p)*f + p*e)
tolerance: 0.5%

## P(faulty | alarm): prior healthy {p}, alarm rates {e} and {f}?

::: misses
- [any] Bayes' theorem.
:::
:::
:::
