intermediate 70 min read · October 25, 2026

Hidden Markov Models

Foundations of state-space inference. A finite Markov chain we never see drives every observation we do; one conditional-independence structure turns three exponential-time problems — likelihood, decoding, and learning — into linear-time passes over a trellis. Ten full proofs, featuring forward–backward smoothing; Viterbi decoding, Baum–Welch as EM with its ascent property proved, and the Kalman filter as the linear-Gaussian case. Market regimes and the dishonest casino as spine examples; speech, sequence labeling, and particle filters as the ML payoff. Track 9 opens here.

34.1 Motivation: regimes we cannot see

Look at a year or two of daily returns for almost any asset and the same pattern shows up: long, quiet stretches, then sudden bursts where every day moves a lot, then quiet again. A histogram of the returns throws that pattern away. It shows one distribution with fatter tails than a Normal, and it can’t tell us that the big moves cluster. The time order is the information. The question an ML system actually faces is a sequential one: given everything observed so far, which regime are we in today, and how sure are we?

The model this topic builds says there’s a hidden state, the market’s regime, that evolves on its own, and each day’s return is drawn from a distribution that depends only on the regime that day. We never observe the regime. We observe only its consequences. That is a hidden Markov model (HMM), and the same structure describes a speaker moving through phonemes, a genome moving between coding and non-coding stretches, a user moving between browsing and buying, or a server moving between healthy and degraded.

Example 1 Two-regime market

Take two regimes, calm and turbulent. On a calm day the return (in percent) is drawn from N(0.05,0.72)\mathcal{N}(0.05, 0.7^2), a Normal distribution with mean 0.05 and standard deviation 0.7; on a turbulent day from N(−0.10,2.02)\mathcal{N}(-0.10, 2.0^2). A calm day is followed by another calm day with probability 0.98, and a turbulent day by another turbulent day with probability 0.95. Simulating T=1000T = 1000 days:

  • The series is turbulent on a fraction 0.362 of days. The long-run value is 0.02/(0.02+0.05)=0.28570.02/(0.02 + 0.05) = 0.2857 (Example 3 derives it), but the regimes are so persistent that 1,000 days contain only 37 switches, and the sample fraction wanders.
  • The returns have sample excess kurtosis 2.77: fat tails, from a mixture of two thin-tailed Normals.
  • The lag-1 autocorrelation of the returns is −0.018, essentially zero. The lag-1 autocorrelation of the squared returns is 0.206.

That last pair is the fingerprint. Returns look unpredictable, and their magnitudes are strongly predictable. Example 5 derives this in closed form.

Three panels. Top: 1,000 simulated daily returns over time with the turbulent days shaded in rose; the shaded stretches are visibly more volatile. Bottom left: a histogram of the returns with the two weighted Normal emission densities, calm in sky blue and narrow, turbulent in rose and wide, and their sum dashed. Bottom right: autocorrelations at lags 1 to 40, near zero for the returns and clearly positive and slowly decaying for the squared returns.

Figure 1. Two hidden regimes produce one fat-tailed histogram. The time order is the evidence: squared returns are autocorrelated even though returns are not.

Example 2 The dishonest casino (DUR1998 §3.1)

A casino rolls one of two dice: a fair die and a loaded die that shows a six with probability 0.5 and each other face with probability 0.1. Between rolls it switches from the fair die to the loaded one with probability 0.05, and back with probability 0.10. We see only the 300 rolls. Which stretches were rolled with the loaded die?

We return to this example throughout §34.4–§34.6. Its emissions are dice, so every posterior probability in it has a concrete reading: “how likely is it that this roll came from the loaded die?”

Remark 1 Notation, and what is hidden

We write Zt∈{1,…,K}Z_t \in \{1, \dots, K\} for the hidden state at time tt and XtX_t for the observation, with lowercase xtx_t for an observed value. This matches the EM appendix of Topic 14, where ZZ was the latent label and XX the data. formalML’s sequential Monte Carlo page writes xtx_t for the hidden state and yty_t for the observation; when crossing between the sites, swap the letters. We write xs:t=(xs,…,xt)x_{s:t} = (x_s, \dots, x_t) for a block of consecutive observations.

Remark 2 Rabiner's three problems (RAB1989)

Every use of an HMM reduces to one of three computations:

  1. Evaluate: compute the likelihood p(x1:T)p(x_{1:T}) of an observed sequence (§34.4).
  2. Decode: recover the hidden states, either one time at a time (§34.5) or as a single best path (§34.6).
  3. Learn: estimate the parameters from data (§34.7).

Each has a brute-force solution that costs KTK^T operations, exponential in the sequence length. The point of this topic is that the HMM’s structure brings each one down to O(TK2)O(TK^2). The picture to hold on to is the trellis: a K×TK \times T grid with one node per (state, time) pair and edges between consecutive columns. Every algorithm here is one dynamic-programming sweep across that grid, and the only thing that changes between them is whether we sum over incoming edges or maximize over them.

34.2 Finite Markov chains

The hidden part of an HMM is a Markov chain, so we start there, but only with what HMMs need. Topic 26 developed Markov chains on general state spaces as the engine of MCMC (§26.2, §26.7); here the state space is finite and everything becomes a matrix.

Definition 1 Finite Markov chain; transition matrix

A sequence Z1,Z2,…Z_1, Z_2, \dots taking values in {1,…,K}\{1, \dots, K\} is a (time-homogeneous) Markov chain if the next state depends on the past only through the present:

P(Zt+1=k∣Zt=j,Z1:t−1)=P(Zt+1=k∣Zt=j)=ajk.P(Z_{t+1} = k \mid Z_t = j, Z_{1:t-1}) = P(Z_{t+1} = k \mid Z_t = j) = a_{jk}.

The transition matrix A=(ajk)A = (a_{jk}) has nonnegative entries and rows that sum to 1 (it is row-stochastic): row jj is the distribution of the next state given the current state jj. The initial distribution is the row vector ν\nu with νk=P(Z1=k)\nu_k = P(Z_1 = k). This is Topic 26’s transition kernel (§26.2 Def 1) on a finite state space.

The first fact is that multi-step behavior is matrix multiplication.

Theorem 1 Chapman–Kolmogorov; marginal law

For a finite Markov chain with transition matrix AA and initial distribution ν\nu:

(i) P(Zt+n=k∣Zt=j)=(An)jkP(Z_{t+n} = k \mid Z_t = j) = (A^n)_{jk} for all t,n≥1t, n \ge 1;

(ii) Am+n=AmAnA^{m+n} = A^m A^n, that is, (Am+n)jk=∑l(Am)jl(An)lk(A^{m+n})_{jk} = \sum_l (A^m)_{jl}(A^n)_{lk};

(iii) the marginal law of ZtZ_t is the row vector νAt−1\nu A^{t-1}.

Proof 1 Proof of Thm 1 (Chapman–Kolmogorov) [show]

(i) By induction on nn. For n=1n = 1 it is Definition 1. Suppose it holds for nn. Condition on Zt+nZ_{t+n} with the law of total probability (Topic 2):

P(Zt+n+1=k∣Zt=j)=∑lP(Zt+n+1=k∣Zt+n=l,Zt=j) P(Zt+n=l∣Zt=j).P(Z_{t+n+1} = k \mid Z_t = j) = \sum_{l} P(Z_{t+n+1} = k \mid Z_{t+n} = l, Z_t = j)\, P(Z_{t+n} = l \mid Z_t = j).

By the Markov property the first factor is P(Zt+n+1=k∣Zt+n=l)=alkP(Z_{t+n+1} = k \mid Z_{t+n} = l) = a_{lk}, and by the induction hypothesis the second is (An)jl(A^n)_{jl}. So the sum is ∑l(An)jlalk=(An+1)jk\sum_l (A^n)_{jl} a_{lk} = (A^{n+1})_{jk}.

(ii) is associativity of matrix multiplication, and (i) gives it a probabilistic reading: to go from jj to kk in m+nm + n steps, the chain passes through some state ll at step mm.

(iii) By total probability over Z1Z_1 and (i) with n=t−1n = t - 1:

P(Zt=k)=∑jνj P(Zt=k∣Z1=j)=∑jνj(At−1)jk=(νAt−1)k.P(Z_t = k) = \sum_j \nu_j\, P(Z_t = k \mid Z_1 = j) = \sum_j \nu_j (A^{t-1})_{jk} = (\nu A^{t-1})_k.

■\blacksquare — using the law of total probability and the Markov property (Definition 1).

◼

The second fact is that a well-behaved chain forgets where it started.

Definition 2 Stationary distribution; irreducible; aperiodic

A distribution π\pi on {1,…,K}\{1, \dots, K\} is stationary for AA if πA=π\pi A = \pi: starting the chain from π\pi, every ZtZ_t has law π\pi. Geometrically, π\pi is a left eigenvector of AA with eigenvalue 1 ( formalCalculus: Eigenvalues & Eigenvectors ). The chain is irreducible if every state can be reached from every other, and aperiodic if for each state kk the return times {n:(An)kk>0}\{n : (A^n)_{kk} > 0\} have greatest common divisor 1.

Theorem 2 Convergence to stationarity (stated; NOR1997 Thms 1.7.7, 1.8.3)

Let AA be the transition matrix of a finite, irreducible, aperiodic chain. Then (a) there is a unique stationary distribution π\pi, and πk>0\pi_k > 0 for every kk; (b) there are constants C<∞C < \infty and ρ∈(0,1)\rho \in (0, 1) such that max⁡k∣(νAn)k−πk∣≤Cρn\max_k |(\nu A^n)_k - \pi_k| \le C\rho^n for every initial distribution ν\nu; (c) πk=1/E[τk∣Z1=k]\pi_k = 1/E[\tau_k \mid Z_1 = k], where τk\tau_k is the time the chain takes to return to kk.

We state Theorem 2 rather than prove it: the proof is Perron–Frobenius theory for nonnegative matrices, and Topic 26 already proved the general-state ergodic theorem it specializes (§26.7 Thm 5). For two states we can do everything by hand, and the hand calculation is what we’ll actually use.

Example 3 The two-state chain, solved

Write the two-state transition matrix as

A=(1−ppq1−q),A = \begin{pmatrix} 1-p & p \\ q & 1-q \end{pmatrix},

so pp is the probability of leaving state 1 and qq the probability of leaving state 2. Multiplying out shows that π=(q,p)/(p+q)\pi = (q, p)/(p + q) satisfies πA=π\pi A = \pi. The eigenvalues of AA are 1 and λ=1−p−q\lambda = 1 - p - q.

To see how fast the chain forgets its start, let μn=νAn\mu_n = \nu A^n and track its first coordinate. By Theorem 1,

μn+1,1=μn,1(1−p)+(1−μn,1) q=q+λ μn,1.\mu_{n+1,1} = \mu_{n,1}(1 - p) + (1 - \mu_{n,1})\,q = q + \lambda\,\mu_{n,1}.

The stationary value satisfies the same equation, π1=q+λπ1\pi_1 = q + \lambda\pi_1. Subtracting,

μn+1,1−π1=λ (μn,1−π1),\mu_{n+1,1} - \pi_1 = \lambda\,(\mu_{n,1} - \pi_1),

and induction gives (νAn)1−π1=(ν1−π1)λn(\nu A^n)_1 - \pi_1 = (\nu_1 - \pi_1)\lambda^n. The distance to stationarity shrinks by the factor λ\lambda every step. Starting from a known state jj (so ν\nu puts mass 1 on jj), the same identity in each coordinate gives the hh-step transition probabilities we will need in Example 5:

P(Zt+h=k∣Zt=j)=πk+(1{j=k}−πk) λh,P(Z_{t+h} = k \mid Z_t = j) = \pi_k + (\mathbf{1}\{j = k\} - \pi_k)\,\lambda^h,

where 1{j=k}\mathbf{1}\{j = k\} is 1 if j=kj = k and 0 otherwise.

For the market chain, p=0.02p = 0.02 and q=0.05q = 0.05, so π=(0.7143,0.2857)\pi = (0.7143, 0.2857) and λ=0.93\lambda = 0.93. The influence of the starting regime halves every log⁡2/(−log⁡0.93)≈9.55\log 2/(-\log 0.93) \approx 9.55 days.

The third fact is the one that defines what an HMM can and can’t express.

Theorem 3 Sojourn times are geometric

Suppose the chain enters state kk at time ss (that is, Zs=kZ_s = k, and either s=1s = 1 or Zs−1≠kZ_{s-1} \ne k), and let D=min⁡{d≥1:Zs+d≠k}D = \min\{d \ge 1 : Z_{s+d} \ne k\} be the number of consecutive steps it spends in kk. If akk<1a_{kk} < 1, then

P(D=d)=akk d−1(1−akk),d=1,2,…,P(D = d) = a_{kk}^{\,d-1}(1 - a_{kk}), \qquad d = 1, 2, \dots,

so D∼Geometric(1−akk)D \sim \mathrm{Geometric}(1 - a_{kk}) and E[D]=1/(1−akk)E[D] = 1/(1 - a_{kk}).

Proof 2 Proof of Thm 3 (geometric sojourns) [show]

The event {D=d}\{D = d\} is {Zs+1=k,…,Zs+d−1=k,Zs+d≠k}\{Z_{s+1} = k, \dots, Z_{s+d-1} = k, Z_{s+d} \ne k\}. Condition on Zs=kZ_s = k and on the history before ss. By the chain rule and the Markov property, each factor depends only on the previous state:

P(D=d∣Zs=k,Z1:s−1)=(∏i=1d−1P(Zs+i=k∣Zs+i−1=k)) P(Zs+d≠k∣Zs+d−1=k).P(D = d \mid Z_s = k, Z_{1:s-1}) = \Big(\prod_{i=1}^{d-1} P(Z_{s+i} = k \mid Z_{s+i-1} = k)\Big)\, P(Z_{s+d} \ne k \mid Z_{s+d-1} = k).

Each factor in the product is akka_{kk}. The last factor is ∑l≠kakl=1−akk\sum_{l \ne k} a_{kl} = 1 - a_{kk}, because row kk sums to 1. The right side doesn’t depend on the history, so it is also the unconditional probability given entry at time ss. That is the Geometric pmf with success probability 1−akk1 - a_{kk} from Topic 5 (§5.4), whose mean is 1/(1−akk)1/(1 - a_{kk}). ■\blacksquare — using the chain rule, the Markov property, and the geometric mean (Topic 5).

◼

For the market chain the mean calm spell lasts 1/0.02=501/0.02 = 50 days and the mean turbulent spell 1/0.05=201/0.05 = 20 days. A 200,000-step simulation gives empirical means of 50.91 and 20.38 over 2,803 and 2,804 completed spells.

Two panels. Left: the probability of being turbulent after n steps, starting from calm (rising from 0) and from turbulent (falling from 1), both converging to the dashed stationary value 0.2857; an inset on a log scale shows the gap to stationarity shrinking along a straight line, the geometric rate 0.93 to the n. Right: on a log scale, empirical sojourn-length frequencies from a 200,000-step simulation for the calm and turbulent states, each following a straight line given by its geometric probability mass function, with means 50 and 20 days.

Figure 2. A two-state chain forgets its starting point at rate λ = 1 − p − q, and the time it spends in each state is geometric.

Remark 3 The spectral gap sets the memory

With K>2K > 2 states, the second-largest eigenvalue modulus ∣λ2∣|\lambda_2| of AA plays the role of λ\lambda: the chain forgets its starting point at roughly the rate ∣λ2∣n|\lambda_2|^n, and 1−∣λ2∣1 - |\lambda_2| is called the spectral gap. That is the finite-state face of a mixing-time bound, developed in formalML: random-walks . We won’t need more than the two-state case.

Remark 4 The Markov property is a modeling choice

Requiring the next state to depend only on the current one costs less generality than it seems. A chain where the next state depends on the last mm states is a first-order chain on the KmK^m possible blocks of mm states, so “first order” restricts only how big the state space is. The genuine restriction is Theorem 3: every state’s dwell time is geometric, so the most likely duration is always 1, whatever the mean. Regimes that tend to last about a month, or phonemes with a typical length, violate that. §34.9 Remark 21 gives the fix.

34.3 The hidden Markov model

Now we hide the chain and let it emit.

Definition 3 Hidden Markov model

A hidden Markov model with KK states has parameters θ=(ν,A,{bk})\theta = (\nu, A, \{b_k\}) and satisfies:

(i) Z1:TZ_{1:T} is a Markov chain with initial distribution ν\nu and transition matrix AA;

(ii) given the whole state sequence Z1:TZ_{1:T}, the observations X1,…,XTX_1, \dots, X_T are independent, and XtX_t has distribution bZtb_{Z_t}, which depends only on the current state.

Here bkb_k is a pmf or density, the emission distribution of state kk. In words: the state walks; at every step it emits one observation from its own distribution and otherwise leaves no trace. Categorical emissions have bk(v)=Bkvb_k(v) = B_{kv} for symbols vv in a finite alphabet (the casino). Gaussian emissions have bk=N(μk,σk2)b_k = \mathcal{N}(\mu_k, \sigma_k^2) (the market).

Everything that follows rests on one theorem: the joint distribution factors along the chain, and the factorization makes the past and the future conditionally independent given the present state.

Theorem 4 Factorization and conditional independence

Under Definition 3, for every TT and every (z1:T,x1:T)(z_{1:T}, x_{1:T}):

(i) the joint probability factors along the chain,

p(z1:T,x1:T)=νz1bz1(x1)∏t=2Tazt−1zt bzt(xt);p(z_{1:T}, x_{1:T}) = \nu_{z_1} b_{z_1}(x_1) \prod_{t=2}^T a_{z_{t-1}z_t}\, b_{z_t}(x_t);

(ii) for each tt, the past block (Z1:t−1,X1:t)(Z_{1:t-1}, X_{1:t}) and the future block (Zt+1:T,Xt+1:T)(Z_{t+1:T}, X_{t+1:T}) are conditionally independent given ZtZ_t; in particular p(xt+1:T∣zt,z1:t−1,x1:t)=p(xt+1:T∣zt)p(x_{t+1:T} \mid z_t, z_{1:t-1}, x_{1:t}) = p(x_{t+1:T} \mid z_t);

(iii) p(xt∣zt,z1:t−1,x1:t−1)=bzt(xt)p(x_t \mid z_t, z_{1:t-1}, x_{1:t-1}) = b_{z_t}(x_t) and p(zt+1∣z1:t,x1:t)=aztzt+1p(z_{t+1} \mid z_{1:t}, x_{1:t}) = a_{z_t z_{t+1}}.

Proof 3 Proof of Thm 4 (factorization and conditional independence) [show]

(i) Write p(z1:T,x1:T)=p(z1:T) p(x1:T∣z1:T)p(z_{1:T}, x_{1:T}) = p(z_{1:T})\, p(x_{1:T} \mid z_{1:T}). The first factor is νz1∏t≥2azt−1zt\nu_{z_1}\prod_{t \ge 2} a_{z_{t-1}z_t} by the chain rule and the Markov property. The second is ∏tbzt(xt)\prod_t b_{z_t}(x_t) by Definition 3(ii).

(ii) Group the factors of (i) by whether their indices are at most tt or greater than tt. Define

f(z1:t,x1:t)=νz1bz1(x1)∏s=2tazs−1zs bzs(xs),f(z_{1:t}, x_{1:t}) = \nu_{z_1}b_{z_1}(x_1)\prod_{s=2}^{t} a_{z_{s-1}z_s}\,b_{z_s}(x_s),g(zt,zt+1:T,xt+1:T)=∏s=t+1Tazs−1zs bzs(xs),g(z_t, z_{t+1:T}, x_{t+1:T}) = \prod_{s=t+1}^{T} a_{z_{s-1}z_s}\,b_{z_s}(x_s),

so that p(z1:T,x1:T)=f⋅gp(z_{1:T}, x_{1:T}) = f \cdot g. The function gg touches the past only through ztz_t. Fix ztz_t and divide by p(zt)p(z_t), the sum of f gf\,g over every other variable. The conditional joint density of the two blocks given Zt=ztZ_t = z_t is then a function of the past block times a function of the future block. A joint density that factors this way is the product of its conditional marginals (Topic 2’s characterization of conditional independence, applied to densities), which is the claimed independence. The “in particular” statement applies it to the XX part of the future block.

(iii) Summing the future factors of (i) over zt+1:Tz_{t+1:T} and xt+1:Tx_{t+1:T} gives 1, so the joint of the prefix (z1:t,x1:t)(z_{1:t}, x_{1:t}) is the product (i) truncated at tt. Divide that truncated product by the same product with xtx_t summed or integrated out. Every factor cancels except bzt(xt)b_{z_t}(x_t), because ∑xtbzt(xt)=1\sum_{x_t} b_{z_t}(x_t) = 1. The same argument at horizon t+1t + 1, with xt+1x_{t+1} summed out, leaves aztzt+1a_{z_t z_{t+1}}. ■\blacksquare — using the chain rule, the Markov property, and the factorization criterion for conditional independence.

◼

Part (ii) is the remark Topic 2 made in passing (“in hidden Markov models, observations are conditionally independent given the hidden state”), now proved. It’s the only property of the model the algorithms will use: the current state screens off the past from the future.

Example 4 A joint probability by hand

In the casino, start the chain at its stationary distribution ν=π=(2/3,1/3)\nu = \pi = (2/3, 1/3) (fair, loaded). Take the rolls x1:3=(6,6,1)x_{1:3} = (6, 6, 1) and the path z1:3=(L,L,F)z_{1:3} = (\mathrm{L}, \mathrm{L}, \mathrm{F}). Theorem 4(i) multiplies one factor per edge and node of the path:

p(z1:3,x1:3)=13⏟νL⋅0.5⏟bL(6)⋅0.90⏟aLL⋅0.5⏟bL(6)⋅0.10⏟aLF⋅16⏟bF(1)=0.00125.p(z_{1:3}, x_{1:3}) = \underbrace{\tfrac13}_{\nu_{\mathrm{L}}} \cdot \underbrace{0.5}_{b_{\mathrm{L}}(6)} \cdot \underbrace{0.90}_{a_{\mathrm{LL}}} \cdot \underbrace{0.5}_{b_{\mathrm{L}}(6)} \cdot \underbrace{0.10}_{a_{\mathrm{LF}}} \cdot \underbrace{\tfrac16}_{b_{\mathrm{F}}(1)} = 0.00125.

Summing this product over all 23=82^3 = 8 paths gives the likelihood of the rolls, p(x1:3)=0.0116235p(x_{1:3}) = 0.0116235. That 8-term sum is the brute-force computation §34.4 replaces.

The factorization also tells us what an HMM’s observations look like marginally: what statistics they have once we sum the hidden states out.

Example 5 Where volatility clustering comes from

Take a two-state HMM started at stationarity with Gaussian emissions, and write μk\mu_k and σk2\sigma_k^2 for the mean and variance of state kk. Fix a lag h≥1h \ge 1. Given the whole state path, XtX_t and Xt+hX_{t+h} are independent (Theorem 4), so their covariance comes entirely from the states. Conditioning on the path and using the tower property,

Cov(Xt,Xt+h)=Cov(E[Xt∣Z],E[Xt+h∣Z])=Cov(μZt,μZt+h).\mathrm{Cov}(X_t, X_{t+h}) = \mathrm{Cov}\big(E[X_t \mid Z], E[X_{t+h} \mid Z]\big) = \mathrm{Cov}(\mu_{Z_t}, \mu_{Z_{t+h}}).

Now use the hh-step formula from Example 3:

E[μZtμZt+h]=∑j,kπj μjμk[πk+(1{j=k}−πk)λh]=(π⋅μ)2+λh(∑jπjμj2−(π⋅μ)2).E[\mu_{Z_t}\mu_{Z_{t+h}}] = \sum_{j,k}\pi_j\,\mu_j\mu_k\big[\pi_k + (\mathbf{1}\{j = k\} - \pi_k)\lambda^h\big] = (\pi\cdot\mu)^2 + \lambda^h\Big(\sum_j \pi_j\mu_j^2 - (\pi\cdot\mu)^2\Big).

Subtracting E[μZt]E[μZt+h]=(π⋅μ)2E[\mu_{Z_t}]E[\mu_{Z_{t+h}}] = (\pi\cdot\mu)^2 leaves λh\lambda^h times the variance of μZ\mu_Z. For two states that variance is π1π2(μ1−μ2)2\pi_1\pi_2(\mu_1 - \mu_2)^2, so

Cov(Xt,Xt+h)=π1π2(μ1−μ2)2 λh.\mathrm{Cov}(X_t, X_{t+h}) = \pi_1\pi_2(\mu_1 - \mu_2)^2\,\lambda^h.

The same argument applied to Xt2X_t^2, with sk=E[Xt2∣Zt=k]=μk2+σk2s_k = E[X_t^2 \mid Z_t = k] = \mu_k^2 + \sigma_k^2 in place of μk\mu_k, gives

Cov(Xt2,Xt+h2)=π1π2(s1−s2)2 λh.\mathrm{Cov}(X_t^2, X_{t+h}^2) = \pi_1\pi_2(s_1 - s_2)^2\,\lambda^h.

In the market model the means barely differ (0.05 vs −0.10), so returns are nearly uncorrelated: the theoretical lag-1 autocorrelation is 0.0029. The second moments differ a lot (s1=0.49s_1 = 0.49, s2=4.01s_2 = 4.01), so squared returns are strongly autocorrelated, decaying like 0.93h0.93^h. At lags h=1,5,20h = 1, 5, 20 the theory gives 0.1947, 0.1457, 0.0490; a 200,000-day simulation gives 0.1893, 0.1450, 0.0471, and the 1,000-day series of Example 1 gives 0.206, 0.124, 0.043. That is volatility clustering, produced by nothing more than a persistent hidden state. The model has no feedback from past returns to future variance; GARCH builds that feedback in directly, and Topic 35 fits it to this same data.

Two panels. Left: the HMM as a directed graph, a row of five hidden-state circles Z1 to Z5 joined left to right by arrows labeled with transition probabilities, each with an arrow down to a shaded observation circle X1 to X5 labeled with emission probabilities. Right: autocorrelation of squared returns from a 200,000-step simulation as gray bars at lags 1 to 40, with the closed-form theory curve in rose passing through them and decaying geometrically, and the near-zero theory curve for the returns themselves dashed along the bottom.

Figure 3. The HMM’s graph, and the volatility clustering it implies: the autocorrelation of squared observations decays like λ^h.

Remark 5 A Gaussian mixture is an HMM with no memory

If every row of AA equals π\pi, the next state ignores the current one, the labels ZtZ_t are i.i.d. draws from π\pi, and the HMM is exactly the Gaussian mixture of Topic 14’s EM appendix. Then λ=0\lambda = 0 and every autocovariance in Example 5 vanishes. The HMM’s extra content over a mixture is persistence: the cluster label at time tt predicts the label at time t+1t + 1. The “No memory” preset in the simulator below makes this concrete. Mixtures and their EM are developed in formalML: clustering .

Remark 6 The graph is the model

Figure 3’s directed graph encodes Theorem 4 by itself. Conditional independence (ii) is d-separation: every path from the past to the future passes through ZtZ_t, and observing ZtZ_t blocks it. Naive Bayes reads the same picture one time step at a time: one hidden class, many conditionally independent features. The HMM strings naive-Bayes models together along a Markov chain.

Try the generative model yourself. Raise the stay probabilities and the regimes lengthen, the sojourn histograms flatten into longer geometric tails, and the autocorrelation of the squared observations decays more slowly, along Example 5’s curve. The “No memory” preset keeps the marginal distribution and destroys the time structure.

Preset:
π = (0.714, 0.286)λ = a₁₁ + a₂₂ − 1 = 0.930mean sojourn 1: 50.0 theory · 48.4 simulatedmean sojourn 2: 20.0 theory · 23.3 simulated

34.4 Likelihood: the forward algorithm

The first of Rabiner’s problems is to compute p(x1:T)p(x_{1:T}): how probable is the observed sequence under the model? We need it to compare models, to fit them by maximum likelihood, and to flag anomalous sequences. By total probability over the hidden path,

p(x1:T)=∑z1:Tp(z1:T,x1:T),p(x_{1:T}) = \sum_{z_{1:T}} p(z_{1:T}, x_{1:T}),

a sum of KTK^T terms, each a product from Theorem 4(i). For the 300 casino rolls that is 2300≈2×10902^{300} \approx 2 \times 10^{90} paths. The sum is correct and useless. The way out is to organize it along time.

Definition 4 Forward variables; filtering distribution

The forward variable is the joint probability of the observations so far and the current state,

αt(k)=p(x1:t,Zt=k).\alpha_t(k) = p(x_{1:t}, Z_t = k).

The filtering distribution is P(Zt=k∣x1:t)P(Z_t = k \mid x_{1:t}): what we believe about the state now, having seen everything up to now and nothing after.

Theorem 5 Forward recursion

The forward variables satisfy α1(k)=νkbk(x1)\alpha_1(k) = \nu_k b_k(x_1) and, for t≥2t \ge 2,

αt(k)=bk(xt)∑j=1Kαt−1(j) ajk.\alpha_t(k) = b_k(x_t)\sum_{j=1}^K \alpha_{t-1}(j)\,a_{jk}.

Consequently p(x1:T)=∑kαT(k)p(x_{1:T}) = \sum_k \alpha_T(k), and computing it takes O(TK2)O(TK^2) operations.

Proof 4 Proof of Thm 5 (forward recursion) [show]

The base case is Theorem 4(i) with T=1T = 1. For t≥2t \ge 2, marginalize Zt−1Z_{t-1} and apply the chain rule:

αt(k)=∑jp(x1:t−1,Zt−1=j)  p(Zt=k∣Zt−1=j,x1:t−1)  p(xt∣Zt=k,Zt−1=j,x1:t−1).\alpha_t(k) = \sum_j p(x_{1:t-1}, Z_{t-1} = j)\; p(Z_t = k \mid Z_{t-1} = j, x_{1:t-1})\; p(x_t \mid Z_t = k, Z_{t-1} = j, x_{1:t-1}).

The first factor is αt−1(j)\alpha_{t-1}(j). By Theorem 4(iii) the second is ajka_{jk} and the third is bk(xt)b_k(x_t). Pull bk(xt)b_k(x_t) out of the sum. The likelihood is total probability over ZTZ_T. For the cost, each of the T−1T - 1 steps computes KK sums of KK products. ■\blacksquare — using the chain rule and Theorem 4(iii).

◼

The trellis makes the recursion visible. Each node (k,t)(k, t) holds αt(k)\alpha_t(k), computed from the KK nodes of the previous column along the KK incoming edges. Every path through the trellis is still counted, but the paths that share a prefix share its arithmetic.

Example 6 Counting operations

The forward algorithm costs about 2K2(T−1)+2K2K^2(T - 1) + 2K multiply-adds: 2,396 for the 300 casino rolls. Brute force costs about TKT≈TK^T \approx 6.1 × 10⁹². Both compute the same number. For the first 10 casino rolls (faces 1, 2, 5, 6, 4, 4, 2, 2, 1, 4), forward and brute-force enumeration of all 2102^{10} paths both give log⁡p(x1:10)=\log p(x_{1:10}) = −18.488737947800, identical to double precision.

Two panels. Left: a two-state trellis over six time steps, nodes in two rows joined by every possible edge between consecutive columns, with the two edges entering state 1 at time 4 highlighted in indigo and the annotation alpha 4 of 1 equals b1 of x4 times the sum over j of alpha 3 of j times a j1. Right: log base 10 of the operation count against sequence length T up to 60, with brute force rising in straight lines for K equals 2 and 3 and the forward algorithm staying nearly flat.

Figure 4. The forward algorithm reuses each column of the trellis instead of enumerating every path — linear in T instead of exponential.

There’s a numerical catch. Every αt(k)\alpha_t(k) is a probability of tt specific observations, so it shrinks geometrically in tt and soon falls below the smallest positive double. The fix normalizes each column, and the normalized column turns out to be exactly the quantity we wanted anyway.

Theorem 6 Scaling equals filtering

Define α^1(k)=νkbk(x1)/c1\hat\alpha_1(k) = \nu_k b_k(x_1)/c_1 with c1=∑kνkbk(x1)c_1 = \sum_k \nu_k b_k(x_1), and for t≥2t \ge 2

α~t(k)=bk(xt)∑jα^t−1(j) ajk,ct=∑kα~t(k),α^t(k)=α~t(k)/ct.\tilde\alpha_t(k) = b_k(x_t)\sum_j \hat\alpha_{t-1}(j)\,a_{jk}, \qquad c_t = \sum_k \tilde\alpha_t(k), \qquad \hat\alpha_t(k) = \tilde\alpha_t(k)/c_t.

Then:

(i) ct=p(xt∣x1:t−1)c_t = p(x_t \mid x_{1:t-1}), with c1=p(x1)c_1 = p(x_1);

(ii) α^t(k)=αt(k)/p(x1:t)=P(Zt=k∣x1:t)\hat\alpha_t(k) = \alpha_t(k)/p(x_{1:t}) = P(Z_t = k \mid x_{1:t});

(iii) log⁡p(x1:T)=∑t=1Tlog⁡ct\log p(x_{1:T}) = \sum_{t=1}^T \log c_t.

Every normalized quantity lies in [0,1][0, 1], so nothing underflows.

Proof 5 Proof of Thm 6 (scaling equals filtering) [show]

We prove (i) and (ii) together by induction on tt. At t=1t = 1, c1=∑kα1(k)=p(x1)c_1 = \sum_k \alpha_1(k) = p(x_1) and α^1=α1/p(x1)\hat\alpha_1 = \alpha_1/p(x_1). Suppose α^t−1=αt−1/p(x1:t−1)\hat\alpha_{t-1} = \alpha_{t-1}/p(x_{1:t-1}). Substitute it into α~t\tilde\alpha_t and use Theorem 5:

α~t(k)=bk(xt)∑jαt−1(j)ajkp(x1:t−1)=αt(k)p(x1:t−1).\tilde\alpha_t(k) = \frac{b_k(x_t)\sum_j \alpha_{t-1}(j)a_{jk}}{p(x_{1:t-1})} = \frac{\alpha_t(k)}{p(x_{1:t-1})}.

Summing over kk, ct=p(x1:t)/p(x1:t−1)=p(xt∣x1:t−1)c_t = p(x_{1:t})/p(x_{1:t-1}) = p(x_t \mid x_{1:t-1}), which is (i). Dividing, α^t(k)=αt(k)/p(x1:t)\hat\alpha_t(k) = \alpha_t(k)/p(x_{1:t}), which is (ii); its second equality is the definition of conditional probability. For (iii), the chain rule gives p(x1:T)=p(x1)∏t≥2p(xt∣x1:t−1)=∏tctp(x_{1:T}) = p(x_1)\prod_{t \ge 2} p(x_t \mid x_{1:t-1}) = \prod_t c_t. ■\blacksquare — using Theorem 5 and the definition of conditional probability.

◼

Read the two lines of the recursion as two steps. The sum ∑jα^t−1(j)ajk=P(Zt=k∣x1:t−1)\sum_j \hat\alpha_{t-1}(j)a_{jk} = P(Z_t = k \mid x_{1:t-1}) is the prediction: where the state will be next, before seeing xtx_t. Multiplying by bk(xt)b_k(x_t) and normalizing is the update: Bayes’ theorem with the new observation as data. The normalizer ctc_t is how surprising xtx_t was, and the log-likelihood is the total surprise.

Example 7 Underflow is not hypothetical

Run the unscaled recursion of Theorem 5 on the 1,000-day market series in double precision. The raw αt\alpha_t becomes exactly 0 at t = 542; after that the “likelihood” is log⁡0\log 0. The scaled recursion runs to the end without trouble and gives log⁡p(x1:1000)=\log p(x_{1:1000}) = −1522.1208729, which matches an independent log-sum-exp implementation to 1.4 × 10⁻¹² (about 15 significant digits). Figure 5’s right panel is the filter itself: α^t(turbulent)\hat\alpha_t(\text{turbulent}), jumping toward 1 at the first large return of each turbulent stretch.

Two panels. Left: log base 10 of the largest unscaled forward variable falling in a straight line until it hits the double-precision floor and underflows at t equals 542, with the scaled running sum of log c dashed on top of it and continuing to t equals 1000. Right: the filtered probability of the turbulent regime over the 1,000 days, mostly near 0 with abrupt rises to near 1 inside the shaded true turbulent stretches.

Figure 5. Unscaled forward variables underflow within a few hundred steps; the scaled recursion is the filter itself, and its scale factors multiply to the likelihood.

Remark 7 Two ways to stay finite

Scaling (Theorem 6) is one fix; the other is to run the recursion on log probabilities, replacing each sum with log-sum-exp, log⁡∑jeuj=m+log⁡∑jeuj−m\log\sum_j e^{u_j} = m + \log\sum_j e^{u_j - m} with m=max⁡jujm = \max_j u_j. Both are exact. The site’s implementation uses scaling, because it produces the filtering distribution for free and keeps the backward pass of §34.5 in the same units.

Remark 8 The forward pass is a filter, and the particle filter approximates it

Predict, then update: this is the same two-step recursion formalML’s sequential Monte Carlo page writes for general state spaces, with integrals over a continuous state in place of our sums over KK states. When the state is continuous and the model non-linear, those integrals have no closed form, and the bootstrap particle filter replaces the exact sum with a weighted sample of states ( formalML: sequential-monte-carlo ). The finite-state forward pass is the exact case it approximates. The same recursion appears in probabilistic programming: Stan and PyMC can’t sample discrete hidden states with gradient-based samplers, so they marginalize them out with exactly this forward pass ( formalML: probabilistic-programming ).

The filter answers “what is the state now, given the past?” Often the whole sequence is already in hand — a recorded utterance, a finished trading year, a sequenced genome — and the better question is “what was the state at time tt, given everything?” The answer conditions on the future too, and the future can only sharpen it.

Definition 5 Backward variables; smoothing marginals

The backward variable is the probability of the future observations given the current state,

βt(k)=p(xt+1:T∣Zt=k),βT(k)=1.\beta_t(k) = p(x_{t+1:T} \mid Z_t = k), \qquad \beta_T(k) = 1.

The smoothing marginals are γt(k)=P(Zt=k∣x1:T)\gamma_t(k) = P(Z_t = k \mid x_{1:T}), the posterior probability of state kk at time tt given all the data, and ξt(j,k)=P(Zt=j,Zt+1=k∣x1:T)\xi_t(j,k) = P(Z_t = j, Z_{t+1} = k \mid x_{1:T}), the posterior probability that the transition from tt to t+1t + 1 was j→kj \to k.

Theorem 7 Forward–backward smoothing (featured)

The backward variables satisfy βT(j)=1\beta_T(j) = 1 and, for t<Tt < T,

βt(j)=∑k=1Kajk bk(xt+1) βt+1(k).\beta_t(j) = \sum_{k=1}^K a_{jk}\, b_k(x_{t+1})\, \beta_{t+1}(k).

For every tt:

(i) αt(k)βt(k)=p(x1:T,Zt=k)\alpha_t(k)\beta_t(k) = p(x_{1:T}, Z_t = k), hence ∑kαt(k)βt(k)=p(x1:T)\sum_k \alpha_t(k)\beta_t(k) = p(x_{1:T}) for every tt;

(ii) γt(k)=αt(k)βt(k)/p(x1:T)\gamma_t(k) = \alpha_t(k)\beta_t(k)/p(x_{1:T});

(iii) ξt(j,k)=αt(j) ajk bk(xt+1) βt+1(k)/p(x1:T)\xi_t(j,k) = \alpha_t(j)\,a_{jk}\,b_k(x_{t+1})\,\beta_{t+1}(k)/p(x_{1:T}) for t<Tt < T.

With the scaled forward variables of Theorem 6 and β^t=βt/∏s>tcs\hat\beta_t = \beta_t/\prod_{s > t} c_s, the same formulas hold with α^,β^\hat\alpha, \hat\beta in place of α,β\alpha, \beta: the denominator p(x1:T)p(x_{1:T}) disappears from (ii), so γt=α^t⊙β^t\gamma_t = \hat\alpha_t \odot \hat\beta_t (elementwise product), and 1/ct+11/c_{t+1} replaces 1/p(x1:T)1/p(x_{1:T}) in (iii).

Proof 6 Proof of Thm 7 (forward–backward) [show]

Backward recursion. βT=1\beta_T = 1 by convention: an empty block of future observations has probability 1. For t<Tt < T, marginalize Zt+1Z_{t+1}:

βt(j)=∑kp(Zt+1=k∣Zt=j)  p(xt+1∣Zt+1=k,Zt=j)  p(xt+2:T∣xt+1,Zt+1=k,Zt=j).\beta_t(j) = \sum_k p(Z_{t+1} = k \mid Z_t = j)\; p(x_{t+1} \mid Z_{t+1} = k, Z_t = j)\; p(x_{t+2:T} \mid x_{t+1}, Z_{t+1} = k, Z_t = j).

The first factor is ajka_{jk}, and the second is bk(xt+1)b_k(x_{t+1}) by Theorem 4(iii). For the third, Theorem 4(ii) at time t+1t + 1 says Xt+2:TX_{t+2:T} is conditionally independent of (Zt,Xt+1)(Z_t, X_{t+1}) given Zt+1Z_{t+1}, so the factor is βt+1(k)\beta_{t+1}(k).

(i). By the chain rule,

p(x1:T,Zt=k)=p(x1:t,Zt=k)  p(xt+1:T∣Zt=k,x1:t).p(x_{1:T}, Z_t = k) = p(x_{1:t}, Z_t = k)\;p(x_{t+1:T} \mid Z_t = k, x_{1:t}).

The first factor is αt(k)\alpha_t(k). By Theorem 4(ii) the conditioning on x1:tx_{1:t} can be dropped from the second, leaving βt(k)\beta_t(k). Summing over kk gives the second claim, which is a free consistency check: the product summed over states is the same number at every tt.

(ii) is (i) divided by p(x1:T)p(x_{1:T}), by the definition of conditional probability.

(iii). Expand the joint with the chain rule in time order:

p(x1:T,Zt=j,Zt+1=k)=p(x1:t,Zt=j)  ajk  bk(xt+1)  p(xt+2:T∣Zt+1=k).p(x_{1:T}, Z_t = j, Z_{t+1} = k) = p(x_{1:t}, Z_t = j)\; a_{jk}\; b_k(x_{t+1})\; p(x_{t+2:T} \mid Z_{t+1} = k).

Each conditional factor is simplified by Theorem 4(ii)–(iii) exactly as in the backward step: the next state depends only on ZtZ_t, the emission only on Zt+1Z_{t+1}, and the future block only on Zt+1Z_{t+1}. The factors are αt(j)\alpha_t(j), ajka_{jk}, bk(xt+1)b_k(x_{t+1}) and βt+1(k)\beta_{t+1}(k); divide by p(x1:T)p(x_{1:T}).

Scaled version. By Theorem 6(ii), α^t=αt/∏s≤tcs\hat\alpha_t = \alpha_t/\prod_{s \le t}c_s, and by definition β^t=βt/∏s>tcs\hat\beta_t = \beta_t/\prod_{s > t}c_s. So

α^t(k)β^t(k)=αt(k)βt(k)∏s=1Tcs=γt(k),\hat\alpha_t(k)\hat\beta_t(k) = \frac{\alpha_t(k)\beta_t(k)}{\prod_{s=1}^T c_s} = \gamma_t(k),

by Theorem 6(iii) and (ii) above. In (iii), the scale factors in the denominators of α^t\hat\alpha_t and β^t+1\hat\beta_{t+1} multiply to ∏s≠t+1cs=p(x1:T)/ct+1\prod_{s \ne t+1}c_s = p(x_{1:T})/c_{t+1}, which gives the stated 1/ct+11/c_{t+1}. The scaled backward recursion is β^t(j)=∑kajkbk(xt+1)β^t+1(k)/ct+1\hat\beta_t(j) = \sum_k a_{jk}b_k(x_{t+1})\hat\beta_{t+1}(k)/c_{t+1}. ■\blacksquare — using the chain rule, Theorem 4(ii)–(iii), and Theorem 6.

◼

Geometrically, the forward pass carries evidence across the trellis from left to right and the backward pass carries it from right to left. At each column they meet, and the posterior is their elementwise product. Two passes of O(TK2)O(TK^2) each give all TKTK marginals and all the pairwise transition marginals, which is exactly what learning will need (§34.7).

Three stacked panels over 300 casino rolls. Top: the rolls as tick marks, sixes tall and red, with the true loaded-die stretches shaded. Middle: the filtered probability that the die is loaded, jagged and quick to spike on single sixes, with an annotation that it crosses 0.5 at roll 91 in the loaded run starting at roll 85. Bottom: the smoothed probability, smoother and more decisive, rising earlier in each loaded stretch and crossing 0.5 at roll 88 in the same run, with the filtered curve faint behind it.

Figure 6. Forward–backward on the dishonest casino. The smoother sees the end of each loaded run and reacts before the filter can.

The explorer below runs both passes on a simulated sequence. The three heatmap rows are α^t\hat\alpha_t (the filter), β^t\hat\beta_t (rescaled per column for display), and their product γt\gamma_t. Move the cursor to the start of a loaded run and watch the backward message arrive before the forward message has caught on. The readout confirms Theorem 7(i) at every step: ∑kα^t(k)β^t(k)=1\sum_k \hat\alpha_t(k)\hat\beta_t(k) = 1. The switching-rate slider changes only the transition matrix used for inference: tell the model to expect fewer switches and smoothing borrows evidence from farther away.

Scenario:
Example 8 Catching the loaded die

On the 300 casino rolls (loaded 40.7% of the time), threshold each posterior at 0.5 and compare with the truth. The filter labels 75.7% of rolls correctly and the smoother 85.0%. The mean log-loss of the probabilities against the true states falls from 0.478 to 0.354. At the loaded run that starts at roll 85, the smoother crosses 0.5 at roll 88 and the filter only at roll 91: the smoother has already seen the run of sixes that follows. The filter also raises more false alarms. A cluster of sixes near roll 38 pushes the filtered probability to 0.75, and the smoother, seeing the fair rolls that come after, holds it to 0.58.

Example 9 Dating the regime changes

On the 1,000-day market series, the true regime path switches 37 times. Thresholding the filtered probability of turbulence at 0.5 switches 53 times: the filter flickers whenever a single large calm-day return looks turbulent. The smoother switches 29 times. Its accuracy is 94.8% against the filter’s 89.6%.

The ML reading is a warning. A backtest that conditions trading decisions on smoothed regimes uses information from the future: at day tt the smoother has seen days t+1,…,Tt + 1, \dots, T. A live system gets only the filter. Using γt\gamma_t where α^t\hat\alpha_t belongs is a textbook leakage bug, and the 5-point accuracy gap above is roughly how much it can flatter a backtest.

Remark 9 Filter, smoother, and the fixed-lag compromise

The filter is online and the smoother is offline. In between is the fixed-lag smoother P(Zt∣x1:t+L)P(Z_t \mid x_{1:t+L}): wait LL steps, then commit to a belief about time tt. It costs a delay of LL and recovers most of the smoother’s accuracy when LL is a few multiples of the typical regime length. Which one to use is a latency decision, not a statistical one.

Remark 10 Sum-product on a chain

Forward–backward is belief propagation on the HMM’s chain-shaped graph. The forward variables are messages passed left to right and the backward variables are messages passed right to left. On any tree-shaped graph the same messages give exact marginals. On graphs with loops, running them anyway gives “loopy” belief propagation, an approximation that works surprisingly well in practice. The chain is the cleanest case: every message is exact and the whole computation is two sweeps.

34.6 Decoding: the Viterbi algorithm

Smoothing gives a probability for each state at each time. Often we need a single answer: one label per time step, a transcription, a segmentation, a gene annotation. There are two natural ways to get one, and they answer different questions.

Definition 6 MAP path; posterior decoding

The MAP path is the single most probable hidden path,

z∗=arg⁡max⁡z1:T p(z1:T∣x1:T).z^* = \arg\max_{z_{1:T}}\, p(z_{1:T} \mid x_{1:T}).

Posterior (pointwise) decoding picks the most probable state at each time separately: z^t=arg⁡max⁡kγt(k)\hat z_t = \arg\max_k \gamma_t(k). The first is “the single most probable story”; the second is “the most probable state at each moment, considered one moment at a time.”

Posterior decoding is a byproduct of forward–backward. The MAP path needs one more recursion: the forward recursion with the sum replaced by a maximum.

Theorem 8 Viterbi decoding (VIT1967; FOR1973)

Let δt(k)=max⁡z1:t−1p(z1:t−1,Zt=k,x1:t)\delta_t(k) = \max_{z_{1:t-1}} p(z_{1:t-1}, Z_t = k, x_{1:t}), the probability of the best path that ends in state kk at time tt, with δ1(k)=νkbk(x1)\delta_1(k) = \nu_k b_k(x_1). Then for t≥2t \ge 2

δt(k)=bk(xt) max⁡j δt−1(j) ajk,ψt(k)∈arg⁡max⁡j δt−1(j) ajk.\delta_t(k) = b_k(x_t)\,\max_j\, \delta_{t-1}(j)\,a_{jk}, \qquad \psi_t(k) \in \arg\max_j\, \delta_{t-1}(j)\,a_{jk}.

Set zT∗∈arg⁡max⁡kδT(k)z^*_T \in \arg\max_k \delta_T(k) and backtrack with zt∗=ψt+1(zt+1∗)z^*_t = \psi_{t+1}(z^*_{t+1}) for t=T−1,…,1t = T-1, \dots, 1. Then z1:T∗z^*_{1:T} maximizes p(z1:T∣x1:T)p(z_{1:T} \mid x_{1:T}) over all KTK^T paths, and max⁡zp(z1:T,x1:T)=max⁡kδT(k)\max_z p(z_{1:T}, x_{1:T}) = \max_k \delta_T(k). The cost is O(TK2)O(TK^2) time and O(TK)O(TK) memory for the back-pointers ψ\psi.

Proof 7 Proof of Thm 8 (Viterbi) [show]

Recursion. By Theorem 4(i), the joint probability of a prefix factors as

p(z1:t−1,Zt=k,x1:t)=p(z1:t−2,zt−1,x1:t−1)  azt−1k  bk(xt).p(z_{1:t-1}, Z_t = k, x_{1:t}) = p(z_{1:t-2}, z_{t-1}, x_{1:t-1})\; a_{z_{t-1}k}\; b_k(x_t).

Maximize over z1:t−1z_{1:t-1} in two stages: first over z1:t−2z_{1:t-2} with zt−1=jz_{t-1} = j held fixed, then over jj. In the first stage the factor ajkbk(xt)≥0a_{jk}b_k(x_t) \ge 0 doesn’t depend on z1:t−2z_{1:t-2}, and for a nonnegative constant cc, max⁡uc f(u)=cmax⁡uf(u)\max_u c\,f(u) = c\max_u f(u). So the inner maximum is δt−1(j) ajk bk(xt)\delta_{t-1}(j)\,a_{jk}\,b_k(x_t), and maximizing over jj gives the recursion. The maximizing jj is the back-pointer ψt(k)\psi_t(k).

Backtracking. Define, for every state kk and time tt, the backtracked path ending in kk: wt(t,k)=kw^{(t,k)}_t = k and ws(t,k)=ψs+1(ws+1(t,k))w^{(t,k)}_{s} = \psi_{s+1}(w^{(t,k)}_{s+1}) for s<ts < t. We show by induction on tt that this path attains δt(k)\delta_t(k), meaning p(w1:t−1(t,k),Zt=k,x1:t)=δt(k)p(w^{(t,k)}_{1:t-1}, Z_t = k, x_{1:t}) = \delta_t(k), for every kk. At t=1t = 1 it is the definition. Suppose it holds at t−1t - 1 for every state. With j=ψt(k)j = \psi_t(k), the path w(t,k)w^{(t,k)} is w(t−1,j)w^{(t-1,j)} followed by kk, so by the factorization above and the induction hypothesis for jj,

p(w1:t(t,k),x1:t)=δt−1(j) ajk bk(xt)=δt(k),p(w^{(t,k)}_{1:t}, x_{1:t}) = \delta_{t-1}(j)\,a_{jk}\,b_k(x_t) = \delta_t(k),

the last step being the definition of ψt(k)\psi_t(k). At t=Tt = T, the backtracked path from zT∗z^*_T is exactly z∗z^*, and zT∗z^*_T maximizes δT\delta_T, so p(z1:T∗,x1:T)=max⁡kδT(k)=max⁡zp(z1:T,x1:T)p(z^*_{1:T}, x_{1:T}) = \max_k \delta_T(k) = \max_z p(z_{1:T}, x_{1:T}). Finally, p(z∣x)=p(z,x)/p(x)p(z \mid x) = p(z, x)/p(x) and p(x)p(x) doesn’t depend on zz, so z∗z^* also maximizes the posterior. ■\blacksquare — using Theorem 4(i) and the fact that maximization commutes with multiplication by a nonnegative constant (Bellman’s principle of optimality).

◼

The two decoders usually agree. They can disagree sharply, and the disagreement can be disqualifying.

Example 10 Posterior decoding can be impossible

Take three states with two structural zeros, a13=a31=0a_{13} = a_{31} = 0: the chain can’t jump between states 1 and 3 without passing through 2. Let

A=(0.90.100.50.20.300.20.8),A = \begin{pmatrix} 0.9 & 0.1 & 0 \\ 0.5 & 0.2 & 0.3 \\ 0 & 0.2 & 0.8 \end{pmatrix},

with a uniform starting distribution and binary emissions, P(x=1∣Z=k)=0.1,0.2,0.1P(x = 1 \mid Z = k) = 0.1, 0.2, 0.1 for k=1,2,3k = 1, 2, 3. Observe x1:5=(0,1,1,1,0)x_{1:5} = (0, 1, 1, 1, 0). Forward–backward gives these smoothed marginals (rows are times; the largest entry in each row is in bold):

ttγt(1)\gamma_t(1)γt(2)\gamma_t(2)γt(3)\gamma_t(3)
10.3070.3160.377
20.3670.2940.339
30.4130.2860.301
40.4580.2700.272
50.5550.1400.305

Posterior decoding reads off z^=(3,1,1,1,1)\hat z = (3, 1, 1, 1, 1), and its first step is the forbidden transition 3→13 \to 1. So p(z^∣x)=0p(\hat z \mid x) = 0: the “most probable state at each time” assembles into a path the model says cannot happen. Viterbi returns z∗=(1,1,1,1,1)z^* = (1, 1, 1, 1, 1), with posterior probability 0.148. Enumerating all 35=2433^5 = 243 paths confirms both answers.

The lesson: when the transition structure carries hard constraints — a gene grammar where exons and introns alternate, a phoneme graph that fixes the order of sounds in a word, a protocol state machine — decode with Viterbi. Pointwise decoding optimizes each label without checking that the labels fit together.

Example 11 Casino: two decoders, two error profiles

The two decoders optimize different losses. Posterior decoding maximizes the expected number of correctly labeled rolls under the model; Viterbi maximizes the probability of getting the whole path right. On the 300 casino rolls, the model’s own expected accuracy (the average of γt\gamma_t at the decoded state) is 0.800 for posterior decoding and 0.777 for Viterbi, as the theory says it must be.

On this particular realization the realized accuracies flip: Viterbi labels 88.7% of rolls correctly and posterior decoding 85.0%. That isn’t a contradiction. An expectation guarantee is a statement about the average over sequences the model could have produced, not a promise about every sequence.

Where the decoders differ reliably is segment structure. The true path switches dice 11 times. Viterbi’s path switches 6 times; it merges short excursions into the surrounding segment because a switch costs a factor of 0.050.05 or 0.100.10 in path probability. Posterior decoding switches 24 times, flickering wherever γt\gamma_t hovers near 0.5. As a whole path, Viterbi’s has log⁡p(z∗∣x)=\log p(z^* \mid x) = −21.07, against −55.03 for the posterior-decoded path.

Two panels. Top: three horizontal ribbons over 300 rolls, the truth, the Viterbi path, and the posterior-decoded path, colored blue for fair and red for loaded, with small triangles marking decoding errors; the posterior ribbon breaks into many short segments. Bottom: the three-state, five-step trellis of Example 10, each node labeled with its smoothed probability, with the Viterbi path running along state 1 and the posterior-decoded path drawn dashed, its first edge from state 3 to state 1 in red because that transition has probability zero.

Figure 7. Viterbi’s single best path versus the sequence of most probable states. The second can be a path the model forbids.

In the decoder below, click any roll to cycle its face. Engineer a run of sixes and watch both decoders respond: posterior decoding flips the affected rolls one at a time, while Viterbi waits until the run is long enough to pay for two switches. The second scenario is Example 10.

Scenario:
Remark 11 Same trellis, different semiring

The forward algorithm combines edges with (+,×)(+, \times): multiply along a path, add across paths. Viterbi uses (max⁡,×)(\max, \times). In log space Viterbi becomes (max⁡,+)(\max, +): each edge has a length −log⁡ajk−log⁡bk(xt)-\log a_{jk} - \log b_k(x_t), and z∗z^* is the shortest path through the trellis (FOR1973). That is Bellman’s dynamic programming, and it’s why Viterbi in log space never needs scaling: sums of logs don’t underflow.

Remark 12 Decoding in speech and sequence models

For three decades, speech recognizers were HMMs: one small chain per phoneme, phoneme chains joined into word chains by a pronunciation dictionary, and Viterbi over the resulting graph to transcribe audio. Beam search in modern sequence models is Viterbi made approximate: the state space (every possible prefix) is too large to sweep exactly, so the search keeps only the best few partial paths. And the CTC loss used to train speech and handwriting recognizers (GRA2006) is a forward–backward sum over all alignments of a label sequence to an input sequence.

34.7 Learning: Baum–Welch as EM

So far the parameters were known. In practice we have only observations, and must learn θ=(ν,A,{bk})\theta = (\nu, A, \{b_k\}) from them. Maximum likelihood is the natural target, and §34.4 computes the likelihood, but maximizing it directly is awkward: log⁡p(x1:T;θ)\log p(x_{1:T}; \theta) is a log of a sum over KTK^T paths. Topic 14’s EM appendix previewed the general strategy for likelihoods with latent variables: alternate between guessing the latent variables and maximizing as if the guesses were data. It stated without proof that each iteration increases the likelihood. Here we prove it, then work out what EM does for an HMM.

Definition 7 Complete-data log-likelihood; the Q function

The complete-data log-likelihood is the log-likelihood we would have if the hidden path were observed,

ℓc(θ′;z,x)=log⁡p(z1:T,x1:T;θ′).\ell_c(\theta'; z, x) = \log p(z_{1:T}, x_{1:T}; \theta').

The EM objective averages it over the posterior of the path under the current parameter θ\theta:

Q(θ′∣θ)=EZ∼p(⋅∣x; θ)[ℓc(θ′;Z,x)].Q(\theta' \mid \theta) = E_{Z \sim p(\cdot \mid x;\, \theta)}\big[\ell_c(\theta'; Z, x)\big].

The E-step computes Q(⋅∣θ(s))Q(\cdot \mid \theta^{(s)}) (in practice, the posterior expectations it needs), and the M-step sets θ(s+1)=arg⁡max⁡θ′Q(θ′∣θ(s))\theta^{(s+1)} = \arg\max_{\theta'} Q(\theta' \mid \theta^{(s)}).

Theorem 9 EM never decreases the likelihood (DEM1977)

Let ℓ(θ)=log⁡p(x;θ)\ell(\theta) = \log p(x; \theta) for observed xx and latent zz (finitely many values, or densities), with p(z∣x;θ)>0p(z \mid x; \theta) > 0 wherever p(z,x;θ′)>0p(z, x; \theta') > 0. For any θ,θ′\theta, \theta':

ℓ(θ′)−ℓ(θ)  ≥  Q(θ′∣θ)−Q(θ∣θ).\ell(\theta') - \ell(\theta) \;\ge\; Q(\theta' \mid \theta) - Q(\theta \mid \theta).

Hence if θ(s+1)\theta^{(s+1)} maximizes Q(⋅∣θ(s))Q(\cdot \mid \theta^{(s)}), or merely increases it, then ℓ(θ(s+1))≥ℓ(θ(s))\ell(\theta^{(s+1)}) \ge \ell(\theta^{(s)}).

Proof 8 Proof of Thm 9 (EM ascent) [show]

For any zz with p(z∣x;θ)>0p(z \mid x; \theta) > 0, Bayes’ theorem gives log⁡p(x;θ′)=log⁡p(z,x;θ′)−log⁡p(z∣x;θ′)\log p(x; \theta') = \log p(z, x; \theta') - \log p(z \mid x; \theta'). The left side doesn’t depend on zz, so average both sides over z∼p(⋅∣x;θ)z \sim p(\cdot \mid x; \theta):

ℓ(θ′)=Q(θ′∣θ)−H(θ′∣θ),H(θ′∣θ)=Ez∼p(⋅∣x;θ)[log⁡p(z∣x;θ′)].\ell(\theta') = Q(\theta' \mid \theta) - H(\theta' \mid \theta), \qquad H(\theta' \mid \theta) = E_{z \sim p(\cdot \mid x;\theta)}\big[\log p(z \mid x; \theta')\big].

The same identity holds at θ′=θ\theta' = \theta. Subtracting the two,

ℓ(θ′)−ℓ(θ)=[Q(θ′∣θ)−Q(θ∣θ)]+[H(θ∣θ)−H(θ′∣θ)].\ell(\theta') - \ell(\theta) = \big[Q(\theta' \mid \theta) - Q(\theta \mid \theta)\big] + \big[H(\theta \mid \theta) - H(\theta' \mid \theta)\big].

The second bracket is Ez∼p(⋅∣x;θ)[log⁡p(z∣x;θ)p(z∣x;θ′)]=DKL(p(⋅∣x;θ) ∥ p(⋅∣x;θ′))E_{z \sim p(\cdot\mid x;\theta)}\big[\log \tfrac{p(z \mid x; \theta)}{p(z \mid x; \theta')}\big] = D_{\mathrm{KL}}\big(p(\cdot \mid x;\theta)\,\|\,p(\cdot \mid x;\theta')\big), the Kullback–Leibler divergence between the two posteriors over paths (Topic 24 §24.3). It is nonnegative by Jensen’s inequality applied to the concave log⁡\log, with all expectations over z∼p(⋅∣x;θ)z \sim p(\cdot \mid x; \theta):

−DKL=E[log⁡p(z∣x;θ′)p(z∣x;θ)]≤log⁡E[p(z∣x;θ′)p(z∣x;θ)]=log⁡∑z: p(z∣x;θ)>0p(z∣x;θ′)≤log⁡1=0.-D_{\mathrm{KL}} = E\Big[\log \frac{p(z \mid x;\theta')}{p(z \mid x;\theta)}\Big] \le \log E\Big[\frac{p(z \mid x;\theta')}{p(z \mid x;\theta)}\Big] = \log \sum_{z:\,p(z\mid x;\theta)>0} p(z \mid x;\theta') \le \log 1 = 0.

Dropping the nonnegative second bracket gives the inequality. If the M-step makes the first bracket nonnegative, the likelihood doesn’t decrease. ■\blacksquare — using Bayes’ theorem, Jensen’s inequality, and the nonnegativity of KL divergence.

◼

The proof also shows when EM stops. Equality forces both brackets to zero, so at a fixed point θ\theta maximizes Q(⋅∣θ)Q(\cdot \mid \theta), and if QQ is differentiable then ∇θ′Q(θ′∣θ)=0\nabla_{\theta'}Q(\theta' \mid \theta) = 0 at θ′=θ\theta' = \theta. Since ℓ(θ′)−Q(θ′∣θ)\ell(\theta') - Q(\theta' \mid \theta) is minimized at θ′=θ\theta' = \theta, the gradients match there, so ∇ℓ(θ)=0\nabla\ell(\theta) = 0 too. WU1983 gives the conditions under which the iterates actually converge to such stationary points. That is the “equality only at a stationary point” clause in Topic 14’s appendix. A stationary point need not be the global maximum, and for HMMs it often isn’t (Example 13).

For an HMM, the M-step has a closed form, and the E-step is forward–backward.

Theorem 10 Baum–Welch M-step (BAU1970)

Let γt\gamma_t and ξt\xi_t be the smoothing marginals computed by Theorem 7 under θ\theta. Then Q(⋅∣θ)Q(\cdot \mid \theta) is maximized over θ′=(ν′,A′,{bk′})\theta' = (\nu', A', \{b'_k\}) by

νk′=γ1(k),ajk′=∑t=1T−1ξt(j,k)∑t=1T−1γt(j),\nu'_k = \gamma_1(k), \qquad a'_{jk} = \frac{\sum_{t=1}^{T-1}\xi_t(j,k)}{\sum_{t=1}^{T-1}\gamma_t(j)},

and, for categorical emissions, bk′(v)=∑tγt(k)1{xt=v}/∑tγt(k)b'_k(v) = \sum_t \gamma_t(k)\mathbf{1}\{x_t = v\} \big/ \sum_t \gamma_t(k); for Gaussian emissions,

μk′=∑tγt(k) xt∑tγt(k),σk′2=∑tγt(k) (xt−μk′)2∑tγt(k).\mu'_k = \frac{\sum_t \gamma_t(k)\,x_t}{\sum_t \gamma_t(k)}, \qquad \sigma'^2_k = \frac{\sum_t \gamma_t(k)\,(x_t - \mu'_k)^2}{\sum_t \gamma_t(k)}.
Proof 9 Proof of Thm 10 (Baum–Welch M-step) [show]

Decomposing Q. Take the log of Theorem 4(i) at θ′\theta' and write each term with indicators:

ℓc(θ′;z,x)=∑k1{z1=k}log⁡νk′+∑t=1T−1∑j,k1{zt=j,zt+1=k}log⁡ajk′+∑t=1T∑k1{zt=k}log⁡bk′(xt).\ell_c(\theta'; z, x) = \sum_k \mathbf{1}\{z_1 = k\}\log\nu'_k + \sum_{t=1}^{T-1}\sum_{j,k}\mathbf{1}\{z_t = j, z_{t+1} = k\}\log a'_{jk} + \sum_{t=1}^T\sum_k \mathbf{1}\{z_t = k\}\log b'_k(x_t).

Take the expectation over z∼p(⋅∣x;θ)z \sim p(\cdot \mid x; \theta). The expected indicators are exactly γ1(k)\gamma_1(k), ξt(j,k)\xi_t(j,k) and γt(k)\gamma_t(k):

Q(θ′∣θ)=∑kγ1(k)log⁡νk′+∑j,k(∑t<Tξt(j,k))log⁡ajk′+∑k∑tγt(k)log⁡bk′(xt).Q(\theta' \mid \theta) = \sum_k \gamma_1(k)\log\nu'_k + \sum_{j,k}\Big(\sum_{t<T}\xi_t(j,k)\Big)\log a'_{jk} + \sum_k\sum_t \gamma_t(k)\log b'_k(x_t).

The three groups involve disjoint parameters, so we maximize each one separately.

A weighted-log lemma. For weights wk≥0w_k \ge 0 with W=∑kwk>0W = \sum_k w_k > 0, the maximum of ∑kwklog⁡pk\sum_k w_k\log p_k over probability vectors pp is attained at pk=wk/Wp_k = w_k/W. To see it, form the Lagrangian ∑kwklog⁡pk−λ(∑kpk−1)\sum_k w_k\log p_k - \lambda(\sum_k p_k - 1) ( formalCalculus: The Gradient ). Setting ∂/∂pk=wk/pk−λ=0\partial/\partial p_k = w_k/p_k - \lambda = 0 gives pk=wk/λp_k = w_k/\lambda, and the constraint gives λ=W\lambda = W. The objective is concave (a nonnegative combination of the concave functions log⁡pk\log p_k) on the convex set of probability vectors, so this stationary point is the global maximum.

Initial distribution: the lemma with wk=γ1(k)w_k = \gamma_1(k) and W=1W = 1.

Transitions: the entries ajk′a'_{jk} for different jj sit in separate terms and are constrained separately (each row sums to 1), so apply the lemma row by row with wk=∑tξt(j,k)w_k = \sum_t \xi_t(j,k). Its total is ∑t∑kξt(j,k)=∑t<Tγt(j)\sum_t\sum_k\xi_t(j,k) = \sum_{t<T}\gamma_t(j), because summing the pairwise marginal over the second state gives the single marginal.

Categorical emissions: the lemma for row kk with wv=∑tγt(k)1{xt=v}w_v = \sum_t \gamma_t(k)\mathbf{1}\{x_t = v\}.

Gaussian emissions: for each kk, ∑tγt(k)log⁡φ(xt;μk,σk2)\sum_t \gamma_t(k)\log\varphi(x_t; \mu_k, \sigma_k^2) is a Normal log-likelihood with weights γt(k)\gamma_t(k), where φ(⋅ ;μ,σ2)\varphi(\cdot\,; \mu, \sigma^2) is the Normal density. Setting the μk\mu_k-derivative ∑tγt(k)(xt−μk)/σk2\sum_t \gamma_t(k)(x_t - \mu_k)/\sigma_k^2 to zero gives the weighted mean. Setting the σk2\sigma_k^2-derivative ∑tγt(k)[−12σk2+(xt−μk)22σk4]\sum_t\gamma_t(k)\big[-\tfrac{1}{2\sigma_k^2} + \tfrac{(x_t-\mu_k)^2}{2\sigma_k^4}\big] to zero at μk=μk′\mu_k = \mu'_k gives the weighted variance. This is Topic 14’s Normal MLE with weights, and the same concavity argument, in the parameters (μ,1/σ2)(\mu, 1/\sigma^2), makes it the maximum. ■\blacksquare — using Theorem 4(i), Theorem 7, Lagrange multipliers, and the Normal MLE (Topic 14).

◼

The updates have an intuitive reading. The new transition probability ajk′a'_{jk} is the expected number of j→kj \to k transitions divided by the expected number of visits to jj, with expectations under the current posterior. The new emission parameters are the usual estimates, each observation weighted by how likely it is to have come from that state. If we could see the path, these would be counts. EM uses expected counts instead.

Example 12 Fitting the market model

Fit a two-state Gaussian HMM to the 1,000-day market series (rounded to 6 decimals, the fixture the site’s tests use). Initialize deterministically with one-dimensional k-means: centers −1.049 and 0.843, SDs 0.996 and 0.911, so neither starting state looks like either true regime. Baum–Welch converges (∣Δℓ∣<10−8|\Delta\ell| < 10^{-8}) in 25 iterations, and every iteration increases the log-likelihood; the smallest increase is 2.7×10−9>02.7 \times 10^{-9} > 0. Fitted against true values (calm, turbulent):

  • standard deviations 0.711, 2.073 (true 0.7, 2.0);
  • stay probabilities 0.9717, 0.9415 (true 0.98, 0.95);
  • means 0.036, −0.040 (true 0.05, −0.10).

The fitted log-likelihood −1519.40 exceeds the true parameters’ −1522.12, as a maximum-likelihood fit should in-sample. The means are the weakest estimates: 1,000 days barely pin down a 0.15-point gap in means under this much noise, while the volatilities and persistences are well identified. One more detail: ν^\hat\nu collapses onto the state of day 1. A single sequence contains a single draw of Z1Z_1, so the initial distribution is essentially unestimable without several sequences.

Example 13 Local optima are real

Now take a three-state market (calm, normal, crisis: means 0.06, 0, −0.3 and SDs 0.5, 1.0, 3.0), simulate 1,500 days, and run Baum–Welch from 50 random starting points. Each start draws its transition rows from a Dirichlet(1) distribution (uniform over probability vectors), its means from the data, and its SDs between 0.5 and 1.5 times the sample SD. The runs end at 6 distinct optima, separated by more than 0.1 in log-likelihood. The best, −1951.52, is reached by 88% of the starts; the worst is −1992.86. The true parameters score −1956.31, below the best fit (in-sample again). Every run climbs monotonically, as Theorem 9 guarantees, but they climb different hills.

Three panels. Left: log-likelihood against Baum–Welch iteration for the two-state market fit, rising steeply and then flattening just above the dashed log-likelihood of the true parameters. Center: the fitted standard deviations and stay probabilities of both states converging over about ten iterations to near their dotted true values. Right: a histogram of final log-likelihoods from 50 random restarts of a three-state fit, most piled at the best value near minus 1952 and a few stuck near minus 1990, with the true-parameter log-likelihood dashed between them.

Figure 8. Baum–Welch never decreases the likelihood, but where it stops depends on where it starts.

The fitter below runs EM step by step. Watch the trace climb and the fitted densities settle onto the histogram. Then fit with more states than the truth, or press “New random init” a few times and run each to convergence: the restart tally collects the final log-likelihoods and reproduces Example 13’s spread. A red badge would appear if the log-likelihood ever decreased. It shouldn’t, and that is Theorem 9 checked live.

Data:Fit K:
Remark 13 Label switching

Permuting the state labels of θ\theta — swapping which state we call “1” and which “2”, and permuting ν\nu, the rows and columns of AA, and the emissions to match — gives exactly the same likelihood. So the likelihood has at least K!K! equivalent maxima, and the labels in a fit mean nothing until we fix a convention after fitting, such as sorting the states by emission mean or by variance. For a single maximum-likelihood fit that’s a cosmetic step. For Bayesian HMMs, whose posterior is multimodal by this symmetry, it’s a real problem for MCMC summaries.

Remark 14 Degenerate Gaussian emissions

As with Gaussian mixtures, the HMM likelihood is unbounded: put one state’s mean exactly on one observation and let its variance shrink to zero, and that observation’s density, and with it the likelihood, goes to infinity. EM can drift toward such a degenerate solution on small data. The standard defenses are a variance floor (the site’s implementation floors each variance at 10−610^{-6} times the sample variance) or a prior on the variances, which turns the fit into MAP estimation.

Remark 15 Baum–Welch is EM before EM

Baum and colleagues proved the monotonicity of this algorithm for HMMs in 1970 (BAU1970), seven years before Dempster, Laird and Rubin named the general EM algorithm and proved Theorem 9 in general (DEM1977). The NPMLE grid algorithm of Topic 33 §33.6 is another instance, with the prior’s weights in the role of ν\nu.

Remark 16 Gradients without the M-step

Fisher’s identity says the gradient of the log-likelihood is the posterior expectation of the complete-data gradient: ∇θℓ(θ)=EZ∼p(⋅∣x;θ)[∇θℓc(θ;Z,x)]\nabla_\theta \ell(\theta) = E_{Z \sim p(\cdot \mid x;\theta)}[\nabla_\theta \ell_c(\theta; Z, x)]. Equivalently, automatic differentiation through the scaled forward pass of Theorem 6 gives the exact gradient of log⁡p(x1:T)\log p(x_{1:T}). That’s how HMM layers sit inside neural networks and get trained by stochastic gradient descent along with everything else, with no M-step at all.

Remark 17 Bayesian HMMs

Put priors on ν\nu, the rows of AA (Dirichlet), and the emission parameters (Normal–inverse-gamma, say), and sample the posterior by Gibbs sampling (Topic 26 §26.3), alternating two blocks. Given θ\theta, draw the whole path Z1:TZ_{1:T} at once by forward-filtering backward-sampling: run the filter, sample ZTZ_T from α^T\hat\alpha_T, then sample each earlier state given the one after it (SCO2002). Given the path, draw θ\theta from its conjugate full conditionals (Topic 25), which use the same counts as the M-step, now as data in a conjugate update.

34.8 Identifiability and choosing the number of states

Two questions remain before an HMM fit can be trusted: are the parameters determined by the data at all, and how many states should the model have?

Theorem 11 Identifiability up to relabeling (stated; GAS2016, ALL2009)

Suppose the hidden chain is stationary, irreducible and aperiodic, the transition matrix AA has full rank, and the emission distributions b1,…,bKb_1, \dots, b_K are linearly independent. If two parameter values θ\theta and θ~\tilde\theta induce the same distribution of (X1,X2,X3)(X_1, X_2, X_3), then θ~\tilde\theta is obtained from θ\theta by a permutation of the state labels.

So label switching (Remark 13) is the only ambiguity, and three consecutive observations already carry all the information about θ\theta. The proof (GAS2016, building on Kruskal’s uniqueness theorem for three-way arrays, as ALL2009 does for finite emission alphabets; PET1969 is the classical finite-alphabet result) is outside our spine. Notice what the conditions exclude: two states with the same emission distribution, or a transition matrix with linearly dependent rows (the “no memory” case of Remark 5 has rank 1), break identifiability.

Example 14 BIC over K

Simulate 2,000 days from the three-state market of Example 13 and fit K=1,…,5K = 1, \dots, 5 states, keeping the best of 10 starts (one k-means and nine random) for each KK. A Gaussian HMM with KK states has dK=(K−1)+K(K−1)+2Kd_K = (K - 1) + K(K - 1) + 2K free parameters: the initial distribution, the transition rows, and a mean and variance per state. The criteria from Topic 24 are BIC=−2ℓ^+dKlog⁡T\mathrm{BIC} = -2\hat\ell + d_K\log T and AIC=−2ℓ^+2dK\mathrm{AIC} = -2\hat\ell + 2d_K:

KKℓ^\hat\elldKd_KBICAIC
1−3312.5726640.346629.13
2−2437.9274929.054889.84
3−2388.79144884.004805.59
4−2384.22234943.264814.44
5−2380.09345018.614828.18

Both criteria pick K = 3, the truth. AIC’s curve is much flatter beyond the truth (+9 at K=4K = 4, against +59 for BIC), the familiar pattern of AIC’s lighter penalty overfitting more readily.

A line chart of BIC and AIC against the number of hidden states K from 1 to 5. Both fall steeply from K equals 1, off the top of the scale, to K equals 2, reach their minimum at K equals 3, circled, and rise afterwards, BIC more steeply than AIC.

Figure 9. Information criteria over the number of hidden states.

Remark 18 Why BIC's justification fails here, and what to do about it

BIC’s derivation (Topic 24 §24.4) is a Laplace approximation that needs a regular model: an interior maximum and an invertible Fisher information. An HMM with more states than the truth is not regular. The extra states can duplicate a true state or go unused, the parameters are non-identifiable (Theorem 11’s conditions fail), and the Fisher information is singular. In practice BIC still tends to choose well, as in Example 14, but the guarantee is gone. The robust alternative is held-out predictive log-likelihood on contiguous blocks of the sequence. Randomly scattered held-out points leak information through the Markov dependence, because their neighbors are in the training set.

Remark 19 Asymptotics of the HMM maximum-likelihood estimator

Under regularity conditions, the HMM MLE is consistent and asymptotically Normal, with a Fisher information defined through the stationary chain (BIC1998). It’s the time-series analogue of the i.i.d. result in Topic 14 §14.5. The proof needs the forgetting property of Theorem 2, applied to the filter rather than the chain.

34.9 Beyond finite states: the Kalman filter and continuous time

Nothing in Theorem 4 needed the state space to be finite. Replace sums over states by integrals and every recursion in this topic still holds; the problem is that the integrals rarely have closed forms. There is one great exception.

Definition 8 Linear-Gaussian state-space model

A linear-Gaussian state-space model has a vector-valued hidden state and vector observations,

Zt=FZt−1+Wt,Xt=HZt+Vt,Z_t = F Z_{t-1} + W_t, \qquad X_t = H Z_t + V_t,

with state noise Wt∼N(0,Q)W_t \sim \mathcal{N}(0, Q), observation noise Vt∼N(0,R)V_t \sim \mathcal{N}(0, R), and initial state Z1∼N(m1,P1)Z_1 \sim \mathcal{N}(m_1, P_1), all mutually independent. The matrix FF moves the state forward, HH maps the state to what we observe, and Q,RQ, R are the noise covariance matrices. It’s an HMM with a continuous state: Definition 3 with a Gaussian transition kernel and Gaussian emissions, and Theorem 4’s factorization holds verbatim with densities.

The miracle of this model is that every filtering distribution stays Gaussian, so the filter only has to track a mean and a covariance.

Theorem 12 Kalman filter (KAL1960)

Under Definition 8, suppose Zt−1∣x1:t−1∼N(mt−1,Pt−1)Z_{t-1} \mid x_{1:t-1} \sim \mathcal{N}(m_{t-1}, P_{t-1}). Then:

Predict. Zt∣x1:t−1∼N(mt−,Pt−)Z_t \mid x_{1:t-1} \sim \mathcal{N}(m^-_t, P^-_t), with mt−=Fmt−1m^-_t = F m_{t-1} and Pt−=FPt−1F⊤+QP^-_t = F P_{t-1} F^\top + Q.

Update. With innovation et=xt−Hmt−e_t = x_t - H m^-_t, innovation covariance St=HPt−H⊤+RS_t = H P^-_t H^\top + R, and gain Kt=Pt−H⊤St−1K_t = P^-_t H^\top S_t^{-1},

Zt∣x1:t∼N(mt,Pt),mt=mt−+Ktet,Pt=Pt−−KtStKt⊤.Z_t \mid x_{1:t} \sim \mathcal{N}(m_t, P_t), \qquad m_t = m^-_t + K_t e_t, \qquad P_t = P^-_t - K_t S_t K_t^\top.

Likelihood. Xt∣x1:t−1∼N(Hmt−,St)X_t \mid x_{1:t-1} \sim \mathcal{N}(Hm^-_t, S_t), so log⁡p(x1:T)=∑tlog⁡φ(xt;Hmt−,St)\log p(x_{1:T}) = \sum_t \log\varphi(x_t; Hm^-_t, S_t), where φ\varphi is the multivariate Normal density: the continuous-state analogue of Theorem 6(iii).

Starting from Z1∼N(m1,P1)Z_1 \sim \mathcal{N}(m_1, P_1) (take m1−=m1m^-_1 = m_1, P1−=P1P^-_1 = P_1), induction makes every filtering distribution Gaussian with these moments.

Proof 10 Proof of Thm 12 (Kalman filter) [show]

Predict. Zt=FZt−1+WtZ_t = FZ_{t-1} + W_t, and WtW_t is independent of (Zt−1,X1:t−1)(Z_{t-1}, X_{1:t-1}) by Definition 8’s independence assumptions and Theorem 4(ii), whose proof applies verbatim to densities. So, conditionally on x1:t−1x_{1:t-1}, ZtZ_t is an affine map of a Gaussian vector plus an independent Gaussian vector, hence Gaussian (Topic 8, §8.3: affine maps and sums of independent Normals stay Normal). Its mean is Fmt−1Fm_{t-1} and its covariance FPt−1F⊤+QFP_{t-1}F^\top + Q, by the covariance rules for affine maps and independent sums.

Joint of state and observation. Xt=HZt+VtX_t = HZ_t + V_t with VtV_t independent of (Zt,X1:t−1)(Z_t, X_{1:t-1}). So, conditionally on x1:t−1x_{1:t-1}, the pair (Zt,Xt)(Z_t, X_t) is jointly Gaussian with means (mt−,Hmt−)(m^-_t, Hm^-_t) and covariance blocks

Cov(Zt)=Pt−,Cov(Zt,Xt)=Pt−H⊤,Cov(Xt)=HPt−H⊤+R=St.\mathrm{Cov}(Z_t) = P^-_t, \qquad \mathrm{Cov}(Z_t, X_t) = P^-_tH^\top, \qquad \mathrm{Cov}(X_t) = HP^-_tH^\top + R = S_t.

The cross-covariance uses Cov(Zt,HZt+Vt)=Cov(Zt)H⊤+0\mathrm{Cov}(Z_t, HZ_t + V_t) = \mathrm{Cov}(Z_t)H^\top + 0. The marginal of XtX_t given the past is the likelihood claim.

Update. Apply the conditional MVN formula (Topic 8 §8.4 Thm 3): for a jointly Gaussian pair, μ1∣2=μ1+Σ12Σ22−1(x2−μ2)\mu_{1|2} = \mu_1 + \Sigma_{12}\Sigma_{22}^{-1}(x_2 - \mu_2) and Σ1∣2=Σ11−Σ12Σ22−1Σ21\Sigma_{1|2} = \Sigma_{11} - \Sigma_{12}\Sigma_{22}^{-1}\Sigma_{21}. Take block 1 to be ZtZ_t and block 2 to be XtX_t:

mt=mt−+Pt−H⊤St−1(xt−Hmt−)=mt−+Ktet,m_t = m^-_t + P^-_tH^\top S_t^{-1}(x_t - Hm^-_t) = m^-_t + K_te_t,Pt=Pt−−Pt−H⊤St−1HPt−=Pt−−KtStKt⊤,P_t = P^-_t - P^-_tH^\top S_t^{-1}HP^-_t = P^-_t - K_tS_tK_t^\top,

where the last step uses KtStKt⊤=Pt−H⊤St−1StSt−1HPt−K_tS_tK_t^\top = P^-_tH^\top S_t^{-1}S_tS_t^{-1}HP^-_t. ■\blacksquare — using Topic 8 §8.3 (affine maps of Normals), §8.4 Thm 3 (conditional MVN), and Theorem 4(ii) for densities.

◼

The structure is Theorem 6’s, line for line. The predict step pushes the belief through the dynamics, and the update step conditions on the new observation. The gain KtK_t decides how far the new observation moves the estimate: close to 1 when the prediction is uncertain relative to the observation noise, close to 0 when the observation is the noisy one. (The subscript always distinguishes the gain KtK_t from the number of states KK.)

Example 15 Local level: the Kalman filter is exponential smoothing

The simplest state-space model is a random walk observed with noise: F=H=1F = H = 1, state-noise variance qq, observation-noise variance rr. The scalar Kalman recursions are

Pt−=Pt−1+q,Kt=Pt−Pt−+r,Pt=(1−Kt)Pt−.P^-_t = P_{t-1} + q, \qquad K_t = \frac{P^-_t}{P^-_t + r}, \qquad P_t = (1 - K_t)P^-_t.

Combining them gives a recursion for the predicted variance alone (the Riccati recursion):

Pt+1−=Pt− rPt−+r+q.P^-_{t+1} = \frac{P^-_t\,r}{P^-_t + r} + q.

It converges to a fixed point P∞−P^-_\infty, which solves P(P+r)=Pr+q(P+r)P(P + r) = Pr + q(P + r), that is, (P−)2−qP−−qr=0(P^-)^2 - qP^- - qr = 0:

P∞−=q+q2+4qr2,K∞=P∞−P∞−+r.P^-_\infty = \frac{q + \sqrt{q^2 + 4qr}}{2}, \qquad K_\infty = \frac{P^-_\infty}{P^-_\infty + r}.

Once the gain has settled, the filter is mt=mt−1+K∞(xt−mt−1)m_t = m_{t-1} + K_\infty(x_t - m_{t-1}): an exponentially weighted moving average with smoothing weight K∞K_\infty. The weight that practitioners usually tune by hand is derived here from the signal-to-noise ratio q/rq/r.

With q=0.1q = 0.1 and r=1r = 1: P∞−=P^-_\infty = 0.370156 and K∞=K_\infty = 0.270156. Starting from a vague prior P1=10P_1 = 10 (so K1=0.909K_1 = 0.909), the gain is within 10−610^{-6} of K∞K_\infty from step 22 on, and after step 20 the exponential smoother and the Kalman mean never differ by more than 3.1 × 10⁻⁴. The filter tracks the hidden level with error 0.515 (root mean square), against 0.997 for the raw observations.

Two panels. Left: 200 noisy observations of a random-walk level as gray dots, the true latent level as a dark line, the Kalman filtered mean as an indigo line with a shaded band of plus and minus two standard deviations, and an exponentially weighted moving average using the steady-state gain drawn dashed in amber on top of the Kalman mean, indistinguishable after the first few steps. Right: the Kalman gain over the first 40 steps falling from 0.91 and settling onto the dashed steady-state value 0.2702.

Figure 10. The Kalman filter for a local-level model. Its gain settles to a constant, and the filter becomes an exponentially weighted moving average.

Time itself can be made continuous too.

Definition 9 Continuous-time Markov chain; Markov-modulated Poisson process

A continuous-time Markov chain on {1,…,K}\{1, \dots, K\} is governed by a generator matrix Q\mathcal{Q} whose off-diagonal entries qjk≥0q_{jk} \ge 0 are jump rates and whose rows sum to 0. Its transition matrices are P(t)=etQP(t) = e^{t\mathcal{Q}}, the matrix exponential, and the time it stays in state kk is Exponential(−qkk)\mathrm{Exponential}(-q_{kk}): the continuous twin of Theorem 3. A Markov-modulated Poisson process (MMPP; FIS1993) is an HMM in continuous time: events arrive as a Poisson process whose rate λZ(t)\lambda_{Z(t)} is set by the hidden chain.

Remark 20 Kolmogorov's forward equation

The transition matrices of a continuous-time chain solve P′(t)=P(t)QP'(t) = P(t)\mathcal{Q} with P(0)=IP(0) = I, a linear system of first-order ODEs ( formalCalculus: First-Order ODEs & Existence Theorems ), whose solution is etQe^{t\mathcal{Q}}. Sampling a continuous-time chain every Δ\Delta time units gives a discrete-time chain with A=eΔQA = e^{\Delta\mathcal{Q}}, which is how irregularly timed data enter the discrete framework: each gap gets its own transition matrix. In ML systems an MMPP is a natural model for bursty event streams, such as requests to a service, clicks in a session, or trades in a book, where the arrival rate itself switches between regimes.

Remark 21 When geometric durations are wrong: semi-Markov models

Theorem 3 and Remark 4 flagged the HMM’s built-in assumption that every state’s duration is geometric. Hidden semi-Markov models (YU2010) give each state an explicit duration distribution (Poisson, negative binomial, or anything else) and let the chain jump only when the duration expires. The forward recursion gains a sum over durations, costing O(TK2D)O(TK^2D) for maximum duration DD, and segment lengths stop being forced to have their mode at 1.

Remark 22 Nonlinear and non-Gaussian states

The Kalman update is exact only because Gaussian conditioning has a closed form. With nonlinear dynamics or observations, the extended Kalman filter linearizes the model around the current estimate and the unscented filter propagates a few carefully chosen points. Particle filters give up on closed forms entirely and approximate the filtering distribution by weighted samples (formalML’s formalML: sequential-monte-carlo , §6). That page cites the Kalman filter of Theorem 12 as the exact baseline its particle filter generalizes.

34.10 Connections to ML and the road ahead

One structure did all the work in this topic: a hidden Markov chain with observations that depend only on the current state (Theorem 4). It turned three exponential problems into linear-time sweeps over one trellis. Summing over the trellis gives the likelihood and the filter (§34.4); summing forward and backward gives the smoother (§34.5); maximizing gives Viterbi (§34.6); and iterating smoothing with expected-count updates gives Baum–Welch (§34.7). The same recursion with a Gaussian state is the Kalman filter (§34.9), and with weighted samples in place of sums it’s the particle filter. Four places where this machinery runs in practice:

Remark 23 Speech and sequence labeling

GMM-HMM acoustic models, with a Gaussian mixture as each state’s emission distribution, were the core of speech recognition for decades. Hybrid systems replaced the emission model with a neural network that outputs state posteriors and kept the HMM for the time structure. In language, HMM part-of-speech taggers gave way to the linear-chain conditional random field (LAF2001). The CRF models p(z1:T∣x1:T)p(z_{1:T} \mid x_{1:T}) directly instead of modeling how the words were generated, but keeps the chain structure, so its marginals and its best path come from exactly the forward–backward and Viterbi recursions of §34.5–§34.6. A CRF layer on top of a neural encoder is still a standard choice for named-entity recognition.

Remark 24 Biological sequences

The casino is a cartoon of a real problem. CpG islands are stretches of DNA where the dinucleotide CG is unusually frequent, and a two-state HMM over the four-letter alphabet finds them exactly as Example 8 finds the loaded die (DUR1998 §3.3). Gene finders use HMMs whose states encode exons, introns and the boundaries between them, a transition structure with hard constraints of the kind Example 10 warns about. Profile HMMs model protein families with one match, insert and delete state per alignment column; database searches for distant relatives of a protein run the forward algorithm against thousands of them.

Remark 25 State-space layers in deep sequence models, and regime models in finance

Modern linear state-space layers such as S4 (GU2022) and Mamba (GU2023) run the recurrence ht=Aˉht−1+Bˉxth_t = \bar A h_{t-1} + \bar B x_t: Definition 8’s state equation with learned matrices and no noise model. They aren’t probabilistic filters, since nothing is conditioned on, but they share the linear-in-TT scan structure that made Theorem 5 practical, and their designers lean on the same linear-systems theory as the Kalman filter. In econometrics, Hamilton’s Markov-switching model (HAM1989) uses the HMM directly as a time-series model: a regression whose coefficients switch with a hidden business-cycle regime, fit by exactly the filter of Theorem 6.

Remark 26 Where Track 9 goes next

This topic opens the time-series track with the latent-state view. Future Track 9 topics build out from here: Kalman smoothing and EM for linear-Gaussian models (the continuous-state counterparts of §34.5 and §34.7), autoregressive and ARIMA models and the Wold decomposition, conditional heteroskedasticity (GARCH) as the observation-driven alternative to Example 5’s state-driven volatility, and spectral methods for stationary series.


References

  1. Rabiner, Lawrence R. (1989). A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proceedings of the IEEE, 77(2), 257–286.
  2. Baum, Leonard E., and Ted Petrie. (1966). Statistical Inference for Probabilistic Functions of Finite State Markov Chains. Annals of Mathematical Statistics, 37(6), 1554–1563.
  3. Baum, Leonard E., Ted Petrie, George Soules, and Norman Weiss. (1970). A Maximization Technique Occurring in the Statistical Analysis of Probabilistic Functions of Markov Chains. Annals of Mathematical Statistics, 41(1), 164–171.
  4. Viterbi, Andrew J. (1967). Error Bounds for Convolutional Codes and an Asymptotically Optimum Decoding Algorithm. IEEE Transactions on Information Theory, 13(2), 260–269.
  5. Forney, G. David, Jr. (1973). The Viterbi Algorithm. Proceedings of the IEEE, 61(3), 268–278.
  6. Dempster, A. P., N. M. Laird, and D. B. Rubin. (1977). Maximum Likelihood from Incomplete Data via the EM Algorithm. Journal of the Royal Statistical Society, Series B, 39(1), 1–22.
  7. Wu, C. F. Jeff. (1983). On the Convergence Properties of the EM Algorithm. Annals of Statistics, 11(1), 95–103.
  8. Petrie, Ted. (1969). Probabilistic Functions of Finite State Markov Chains. Annals of Mathematical Statistics, 40(1), 97–115.
  9. Allman, Elizabeth S., Catherine Matias, and John A. Rhodes. (2009). Identifiability of Parameters in Latent Structure Models with Many Observed Variables. Annals of Statistics, 37(6A), 3099–3132.
  10. Gassiat, Elisabeth, Alice Cleynen, and Stéphane Robin. (2016). Inference in Finite State Space Non Parametric Hidden Markov Models and Applications. Statistics and Computing, 26(1–2), 61–71.
  11. Bickel, Peter J., Ya’acov Ritov, and Tobias Rydén. (1998). Asymptotic Normality of the Maximum-Likelihood Estimator for General Hidden Markov Models. Annals of Statistics, 26(4), 1614–1635.
  12. Kalman, Rudolph E. (1960). A New Approach to Linear Filtering and Prediction Problems. Journal of Basic Engineering, 82(1), 35–45.
  13. Hamilton, James D. (1989). A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle. Econometrica, 57(2), 357–384.
  14. Cappé, Olivier, Eric Moulines, and Tobias Rydén. (2005). Inference in Hidden Markov Models. Springer.
  15. Zucchini, Walter, Iain L. MacDonald, and Roland Langrock. (2016). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman & Hall/CRC.
  16. Durbin, Richard, Sean R. Eddy, Anders Krogh, and Graeme Mitchison. (1998). Biological Sequence Analysis: Probabilistic Models of Proteins and Nucleic Acids. Cambridge University Press.
  17. Norris, J. R. (1997). Markov Chains. Cambridge University Press.
  18. Särkkä, Simo. (2013). Bayesian Filtering and Smoothing. Cambridge University Press.
  19. Bishop, Christopher M. (2006). Pattern Recognition and Machine Learning. Springer.
  20. Scott, Steven L. (2002). Bayesian Methods for Hidden Markov Models: Recursive Computing in the 21st Century. Journal of the American Statistical Association, 97(457), 337–351.
  21. Fischer, Wolfgang, and Kathleen Meier-Hellstern. (1993). The Markov-Modulated Poisson Process (MMPP) Cookbook. Performance Evaluation, 18(2), 149–171.
  22. Yu, Shun-Zheng. (2010). Hidden Semi-Markov Models. Artificial Intelligence, 174(2), 215–243.
  23. Lafferty, John, Andrew McCallum, and Fernando C. N. Pereira. (2001). Conditional Random Fields: Probabilistic Models for Segmenting and Labeling Sequence Data. In Proceedings of the 18th International Conference on Machine Learning (ICML 2001), 282–289.
  24. Graves, Alex, Santiago Fernández, Faustino Gomez, and Jürgen Schmidhuber. (2006). Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks. In Proceedings of the 23rd International Conference on Machine Learning (ICML 2006), 369–376.
  25. Gu, Albert, Karan Goel, and Christopher Ré. (2022). Efficiently Modeling Long Sequences with Structured State Spaces. International Conference on Learning Representations (ICLR 2022).
  26. Gu, Albert, and Tri Dao. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv preprint arXiv:2312.00752.