Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 26: Temporal and Undirected Models

Open in Colab

The only certainty is that nothing is certain.

Pliny the Elder

26.1 Sequences and the Markov Assumption

Chapters 22–25 modelled one moment: a patient, a record. Many problems unfold in time: a machine wears out, a speaker says a word, a vehicle moves. The variables repeat at each step, and the network is a dynamic Bayesian network: one slice per time step, with edges inside a slice and from each slice to the next.

Two assumptions keep it manageable:

  • Markov: the state at time tt depends on the past only through the state at t−1t - 1: P(zt∣z1:t−1)=P(zt∣zt−1)P(z_t \mid z_{1:t-1}) = P(z_t \mid z_{t-1}).

  • Stationarity: the same tables hold at every step, so a model of any length has a fixed number of parameters.

The simplest such model with hidden states is the hidden Markov model.

26.2 Hidden Markov Models

An HMM has a hidden state ztz_t with KK values and an observation oto_t that depends only on ztz_t:

  • an initial distribution πi=P(z1=i)\pi_i = P(z_1 = i),

  • a transition matrix Aij=P(zt+1=j∣zt=i)A_{ij} = P(z_{t+1} = j \mid z_t = i),

  • an emission matrix Bik=P(ot=k∣zt=i)B_{ik} = P(o_t = k \mid z_t = i).

Our example is a machine on a factory floor. Its state is normal, worn or faulty; a sensor reports vibration as low, medium or high. A machine wears out, a worn machine may fail, and a faulty one is repaired (back to normal) with probability 0.10 per step.

time spent in each state: {'normal': 0.523, 'worn': 0.09, 'faulty': 0.387}
first 30 states:       NNNNNNNNNNNNNFFFFFFFFFFFNNNNNN
first 30 observations: llmlmllllllllhhmhmhmmmhhmlllll

26.3 Inference in an HMM

Three questions, three algorithms. All exploit the chain structure: variable elimination (Chapter 24) along the chain, in time linear in TT.

Filtering, P(zt∣o1:t)P(z_t \mid o_{1:t}): the state now, from what has been seen so far. The forward algorithm carries a message αt(j)∝P(zt=j,o1:t)\alpha_t(j) \propto P(z_t = j, o_{1:t}):

αt(j)=Bj,ot∑iαt−1(i) Aij.\alpha_t(j) = B_{j,o_t} \sum_i \alpha_{t-1}(i)\, A_{ij}.

Smoothing, P(zt∣o1:T)P(z_t \mid o_{1:T}): the state at tt in hindsight, using the later observations too. A backward message βt(i)=P(ot+1:T∣zt=i)\beta_t(i) = P(o_{t+1:T} \mid z_t = i) is computed from the end, and P(zt∣o1:T)∝αtβtP(z_t \mid o_{1:T}) \propto \alpha_t \beta_t: the forward–backward algorithm, belief propagation on a chain.

Decoding, the most likely state sequence arg⁡max⁡z1:TP(z1:T∣o1:T)\arg\max_{z_{1:T}} P(z_{1:T} \mid o_{1:T}): the Viterbi algorithm replaces the sum by a max and keeps back-pointers.

Products of hundreds of probabilities underflow, so the forward messages are normalised at each step and the normalisers ctc_t kept: log⁡P(o1:T)=∑tlog⁡ct\log P(o_{1:T}) = \sum_t \log c_t. Viterbi works with logarithms.

log P(observations) = -284.96
guess each state from                        accuracy
its own observation only (no model of time)  0.523
filtering, P(z_t | o_1..t)                   0.777
smoothing, P(z_t | o_1..T)                   0.833
Viterbi, the best whole sequence             0.830
Source
<Figure size 1100x460 with 2 Axes>

Guessing each state from its own vibration reading, with no model of time, is right 52.3% of the time, and only because the machine is normal 52.3% of the time: the initial distribution makes “normal” the best guess for every reading, even a high one. Knowing that states persist changes everything. Filtering, which uses the readings up to now, is right 77.7% of the time; smoothing, which also uses the later readings, 83.3%; Viterbi’s single best sequence, 83.0%.

The plot shows why hindsight helps. When a fault begins, the filter needs several high readings before it believes it (the grey curve rises late and drops at every low reading); the smoothed curve, knowing that more high readings follow, rises at the right step and stays up. A monitoring system acting in real time has only the filter; a maintenance report written afterwards can use the smoother.

T =  100: unnormalised P(observations) = 2.117e-48   normalised: log P = -109.8
T =  500: unnormalised P(observations) = 5.364e-201   normalised: log P = -461.1
T = 1000: unnormalised P(observations) = 0.000e+00   normalised: log P = -812.5

Without normalisation, the probability of 1 000 observations is smaller than the smallest positive floating-point number (about 10-308) and becomes exactly 0, after which every ratio is undefined. The normalised forward pass computes the same quantity as a sum of logarithms: -812.5.

26.4 Learning an HMM

With labelled sequences (states known), learning is counting (Chapter 25): transitions i→ji \to j and emissions kk in state ii. Usually the states are hidden, and the Baum–Welch algorithm, EM for HMMs, learns from observations alone. The E-step runs forward–backward on each sequence to get the expected number of times in each state (γ\gamma) and of each transition (ξt(i,j)∝αt(i)AijBj,ot+1βt+1(j)\xi_t(i, j) \propto \alpha_t(i) A_{ij} B_{j, o_{t+1}} \beta_{t+1}(j)); the M-step divides expected counts.

We learn from 20 sequences of 200 steps, from two kinds of start: random tables, and sticky tables, where each state is assumed to persist (0.90 on the diagonal of AA) and only the emissions are random.

log-likelihood of the 20 sequences under the true model: -3624.2

random start 0: final log-likelihood -3638.0
random start 1: final log-likelihood -3638.4
random start 2: final log-likelihood -3614.7
sticky start 0: final log-likelihood -3614.6
sticky start 1: final log-likelihood -3614.6
sticky start 2: final log-likelihood -3614.6
random start 0, learned A:
[[0.95 0.   0.05]
 [0.14 0.25 0.61]
 [0.05 0.27 0.69]]
learned B:
[[0.78 0.16 0.06]
 [0.46 0.07 0.46]
 [0.07 0.53 0.4 ]]

sticky start 0, learned A:
[[0.96 0.03 0.01]
 [0.02 0.9  0.08]
 [0.1  0.02 0.89]]
learned B:
[[0.79 0.15 0.06]
 [0.29 0.48 0.23]
 [0.11 0.32 0.57]]

Two of the three random starts stop at −3 638.0-3\,638.0 and −3 638.4-3\,638.4; the third reaches −3 614.7-3\,614.7. All three sticky starts reach −3 614.6-3\,614.6, above the true model’s −3 624.2-3\,624.2, as a maximum-likelihood fit to these particular sequences should.

The tables show what a poor local maximum looks like. From random start 0, the middle state moves to the third state 61% of the time and emits low or high but almost never medium: a state that corresponds to nothing in the machine. From the sticky start, the learned matrices are within 0.03 of the true ones (diagonal of AA: 0.96, 0.90, 0.89 against 0.95, 0.90, 0.90). The states come out unnamed and in any order (EM learns them up to relabelling); here they are named by their probability of a low reading.

Baum–Welch is EM: it only climbs, and where it ends depends on where it starts. Encoding what is known (states persist; a faulty machine vibrates more) in the starting point is cheap and effective, and several starts should be compared by their likelihood.

26.5 The Kalman Filter

When the state is continuous (a position, a temperature) and the dynamics are linear with Gaussian noise, the same filtering idea has an exact closed form. The linear-Gaussian state-space model is

xt=Fxt−1+wt, wt∼N(0,Q),yt=Hxt+vt, vt∼N(0,R).x_t = F x_{t-1} + w_t,\ w_t \sim \mathcal N(0, Q), \qquad y_t = H x_t + v_t,\ v_t \sim \mathcal N(0, R).

The filtered distribution stays Gaussian, N(μt,Pt)\mathcal N(\mu_t, P_t), and the Kalman filter updates it in two steps:

  • predict: μ−=Fμt−1\mu^- = F \mu_{t-1}, P−=FPt−1F⊤+QP^- = F P_{t-1} F^\top + Q;

  • update: the gain K=P−H⊤(HP−H⊤+R)−1K = P^- H^\top (H P^- H^\top + R)^{-1}; μt=μ−+K(yt−Hμ−)\mu_t = \mu^- + K (y_t - H \mu^-), Pt=(I−KH)P−P_t = (I - K H) P^-.

The gain weighs the prediction against the measurement by their uncertainties. With no measurement, only the prediction step runs and the uncertainty grows. The Rauch–Tung–Striebel smoother is the backward pass, as forward–backward is for HMMs.

We track a vehicle on a road: the state is position and speed, the sensor measures position with a noise of standard deviation 3 m, and the sensor is blind from step 60 to step 75.

position error (RMSE, steps with a measurement): measurement 2.51 m, filtered 1.43 m, smoothed 0.78 m
during the blind steps 60-75: filtered 5.69 m, smoothed 0.67 m
filter standard deviation of the position: step 59 1.70 m, step 75 12.21 m, step 76 2.92 m
Source
<Figure size 1100x380 with 1 Axes>

The measurements are off by 2.51 m on average (RMSE); the filter, combining each measurement with the prediction from the past, by 1.43 m; the smoother, using the future as well, by 0.78 m.

During the blind stretch the filter can only predict, at the last estimated speed. Its uncertainty grows from a standard deviation of 1.70 m to 12.21 m, and its error averages 5.69 m: the vehicle accelerated slightly and the prediction drifts below it. The first measurement after the gap pulls the estimate back and the uncertainty falls to 2.92 m at once. The smoother, which knows where the vehicle reappeared, interpolates across the gap with an error of 0.67 m.

26.6 Markov Random Fields

Some dependences have no direction: neighbouring pixels of an image, neighbouring words, atoms in a crystal. A Markov random field (undirected graphical model) has an undirected graph and a non-negative potential ψC\psi_C for each clique CC:

P(x)=1Z∏CψC(xC),Z=∑x∏CψC(xC).P(x) = \frac{1}{Z} \prod_C \psi_C(x_C), \qquad Z = \sum_x \prod_C \psi_C(x_C).

Potentials are not probabilities: they say which joint values are compatible. Independence is read by plain separation: X⊥Y∣ZX \perp Y \mid Z when every path from XX to YY passes through ZZ, with no v-structures to worry about. (The Hammersley–Clifford theorem says that every positive distribution with these independences has this product form.)

The price is ZZ, the partition function, a sum over every joint state. Learning and exact likelihoods need it; for a grid of n×nn \times n binary pixels it has 2n22^{n^2} terms.

2 x 2 grid:     16 states, Z = 27.05, 0 ms
3 x 3 grid:    512 states, Z = 2675, 1 ms
4 x 4 grid:  65536 states, Z = 1.978e+06, 131 ms
64 x 64 grid: 2^4096 states, about 10^1233: no enumeration will ever finish

Denoising an image. A black-and-white image x∈{−1,+1}n×nx \in \{-1, +1\}^{n \times n} is observed through noise that flips 15% of the pixels, giving yy. The Ising prior says that neighbouring pixels tend to agree, and each observed pixel pulls its hidden pixel towards its value:

P(x∣y)∝exp⁡(β∑i∼jxixj+η∑ixiyi).P(x \mid y) \propto \exp\Big(\beta \sum_{i \sim j} x_i x_j + \eta \sum_i x_i y_i\Big).

Here η=12log⁡0.850.15=0.87\eta = \frac{1}{2}\log\frac{0.85}{0.15} = 0.87 comes from the noise level. Exact inference is out of reach, so we use two approximations: ICM (iterated conditional modes) sets each pixel in turn to its most likely value given its neighbours, until nothing changes; Gibbs sampling (Chapter 24) samples each pixel from its conditional and averages, giving each pixel’s posterior probability.

noisy image: 15.1% of pixels wrong
beta = 0.3: ICM 7.2% wrong (2 sweeps);  Gibbs 6.7% wrong
beta = 0.7: ICM 0.8% wrong (4 sweeps);  Gibbs 0.7% wrong
beta = 1.0: ICM 0.7% wrong (4 sweeps);  Gibbs 0.4% wrong
beta = 2.0: ICM 0.7% wrong (4 sweeps);  Gibbs 0.4% wrong
Source
<Figure size 1200x330 with 4 Axes>

Enumerating the 216 states of a 4 × 4 grid already takes about a tenth of a second; each extra pixel doubles the work.

With β=0.3\beta = 0.3 the prior is too weak to overrule the noise everywhere, and 7.2% of pixels stay wrong. From β=0.7\beta = 0.7 on, both methods remove almost all of the noise: under 1% wrong, from 15.1%. Gibbs sampling, which averages over many plausible images, does a little better than ICM, which settles on one image in 4 sweeps and can stop in a local optimum. The remaining errors sit on the edges of the shapes, where neighbours disagree in the clean image too; a stronger prior would also erase thin lines and fine details, which this image does not have.

26.7 Conditional Random Fields

An HMM is generative: it models P(z,o)P(z, o), observations included. To do so it must assume each observation depends only on its own state. Real inputs break this: a word’s spelling, its neighbours, a sensor reading that repeats. A conditional random field (Lafferty, McCallum and Pereira, 2001) models only P(z∣o)P(z \mid o), the labels given the whole input, and never the input itself, so its features may look at any part of the input:

P(z∣o)=1Z(o)exp⁡(∑t[w⊤f(zt,o,t)+Tzt−1,zt]).P(z \mid o) = \frac{1}{Z(o)} \exp\Big(\sum_t \big[ w^\top f(z_t, o, t) + T_{z_{t-1}, z_t} \big]\Big).

This is a linear-chain CRF: an MRF over the labels, conditioned on the input. Its Z(o)Z(o) is a sum over label sequences, computed by the forward algorithm, and training maximises the conditional log-likelihood by gradient: the gradient of each weight is the feature’s count in the data minus its expected count under the model, which forward–backward provides.

An experiment. Two labels follow a Markov chain (stay with probability 0.9). Each observation (one of 4 symbols) is drawn from its label’s emission table, or, with probability 0.6, is a copy of the previous observation. The copies break the HMM’s assumption: the HMM counts a repeated symbol as fresh evidence. The CRF gets one extra feature: whether the symbol repeats the previous one.

CRF trained in 117.2 s
HMM                test accuracy 0.774
linear-chain CRF   test accuracy 0.800

CRF weight of each symbol for label 1 over label 0:
  symbol new:      [-2.27 -0.75  0.6   2.32]
  symbol repeated: [-0.29 -0.02  0.1   0.23]

The CRF labels 80.0% of the test steps correctly, the HMM 77.4%. The weights show why. For a new symbol, the CRF’s evidence ranges from -2.27 (symbol 0, label 0) to +2.32 (symbol 3, label 1); for a repeated symbol, from -0.29 to +0.23, about a tenth. The CRF has learned that a copy says almost nothing about the current label. The HMM cannot express this: in its model every observation is fresh evidence, so a run of copied symbols becomes overwhelming, misleading evidence.

The CRF pays for this in training: no counting, but an optimisation with forward–backward in every step (here about 2 minutes, against an instant for the HMM), and it needs labelled data, while an HMM can be learned from observations alone with Baum–Welch.

26.8 Choosing a Model

ModelGraphStateModelsInferenceTypical use
Markov chaindirected, chainobservedP(z)P(z)countingtext, weather, web navigation
HMMdirected, chaindiscrete, hiddenP(z,o)P(z, o)forward–backward, Viterbispeech, sensors, biological sequences
Kalman filterdirected, chaincontinuous, linear-GaussianP(x,y)P(x, y)exact, closed formtracking, navigation, finance
Dynamic Bayesian networkdirected, slicesanyP(z,o)P(z, o)Chapter 24’s methods, particle filtersseveral interacting processes
Markov random fieldundirectedanyP(x)P(x)Gibbs, ICM, belief propagationimages, spatial data
Conditional random fieldundirected, conditioneddiscrete labelsP(z∣o)P(z \mid o)forward–backward (chain)tagging, segmentation

For non-linear dynamics, the extended and unscented Kalman filters linearise; particle filters represent the distribution by weighted samples (likelihood weighting through time). Recurrent networks and transformers learn sequence models without a hand-written state; CRF layers are still placed on top of them for tagging, so that the labels are consistent with each other.

26.9 Summary

  • Temporal models repeat a slice through time under the Markov and stationarity assumptions.

  • An HMM answers filtering (forward), smoothing (forward–backward) and decoding (Viterbi) in time linear in the length; messages are normalised against underflow.

  • Baum–Welch learns an HMM by EM from observations alone; its local maxima make the starting point matter, and prior knowledge (states persist) is a good start.

  • The Kalman filter is exact filtering for linear-Gaussian models: predict, then correct by a gain that weighs the uncertainties.

  • MRFs use potentials on cliques and a partition function; approximate inference (ICM, Gibbs) denoises images.

  • CRFs model labels given the input, so their features can use any part of it; they are trained by gradient with forward–backward.

Exercises

  1. In the machine HMM, compute P(z2)P(z_2) given that z1z_1 is normal, and the filtered distribution after observing o1=o_1 = high.

  2. Why is smoothing more accurate than filtering? When can only filtering be used?

  3. Run Viterbi by hand for 3 steps of a 2-state HMM of your choice. Can the Viterbi path contain a transition of probability 0?

  4. In the Kalman filter, what happens to the gain KK when RR grows? When QQ grows? Explain in words.

  5. Write the potentials of a 3-pixel chain MRF that prefers equal neighbours, and compute ZZ by hand.

  6. Give a feature that a CRF for recognising names in text could use but an HMM could not.

Further Reading

  • L. Rabiner, “A tutorial on hidden Markov models and selected applications in speech recognition”, Proceedings of the IEEE, 1989.

  • R. Kalman, “A new approach to linear filtering and prediction problems”, Journal of Basic Engineering, 1960.

  • J. Lafferty, A. McCallum, F. Pereira, “Conditional random fields: probabilistic models for segmenting and labeling sequence data”, ICML, 2001.

  • J. Besag, “On the statistical analysis of dirty pictures”, Journal of the Royal Statistical Society B, 1986.

  • D. Koller, N. Friedman, Probabilistic Graphical Models, MIT Press, 2009, Chapters 4, 6 and 15.

  • S. Russell, P. Norvig, Artificial Intelligence: A Modern Approach, 4th ed., 2020, Chapter 14.