Chapter 26: Temporal and Undirected Models
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 depends on the past only through the state at : .
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.
import itertools, time
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.special import logsumexp26.2 Hidden Markov Models¶
An HMM has a hidden state with values and an observation that depends only on :
an initial distribution ,
a transition matrix ,
an emission matrix .
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.
STATES, OBS = ['normal', 'worn', 'faulty'], ['low', 'medium', 'high']
PI = np.array([0.90, 0.08, 0.02])
A = np.array([[0.95, 0.04, 0.01],
[0.05, 0.90, 0.05],
[0.10, 0.00, 0.90]])
B = np.array([[0.80, 0.15, 0.05],
[0.30, 0.50, 0.20],
[0.10, 0.30, 0.60]])
def hmm_sample(T, rng, pi=PI, A=A, B=B):
z, o = np.zeros(T, int), np.zeros(T, int)
z[0] = rng.choice(len(pi), p=pi)
for t in range(T):
if t: z[t] = rng.choice(len(pi), p=A[z[t - 1]])
o[t] = rng.choice(B.shape[1], p=B[z[t]])
return z, o
z, o = hmm_sample(300, np.random.default_rng(0))
print('time spent in each state:', {s: round(float(np.mean(z == i)), 3) for i, s in enumerate(STATES)})
print('first 30 states: ', ''.join('NWF'[s] for s in z[:30]))
print('first 30 observations:', ''.join('lmh'[k] for k in o[:30]))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 .
Filtering, : the state now, from what has been seen so far. The forward algorithm carries a message :
Smoothing, : the state at in hindsight, using the later observations too. A backward message is computed from the end, and : the forward–backward algorithm, belief propagation on a chain.
Decoding, the most likely state sequence : 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 kept: . Viterbi works with logarithms.
def forward(o, pi=PI, A=A, B=B):
"""Filtered distributions P(z_t | o_1..t) and the normalisers c_t, with log P(o) = sum(log c)."""
alpha, c = np.zeros((len(o), len(pi))), np.zeros(len(o))
a = pi * B[:, o[0]]
for t in range(len(o)):
if t: a = (alpha[t - 1] @ A) * B[:, o[t]]
c[t] = a.sum(); alpha[t] = a / c[t]
return alpha, c
def backward(o, c, A=A, B=B):
beta = np.ones((len(o), A.shape[0]))
for t in range(len(o) - 2, -1, -1):
beta[t] = A @ (B[:, o[t + 1]] * beta[t + 1]) / c[t + 1]
return beta
def viterbi(o, pi=PI, A=A, B=B):
with np.errstate(divide='ignore'):
lA, lB, lpi = np.log(A), np.log(B), np.log(pi)
d, back = lpi + lB[:, o[0]], np.zeros((len(o), len(pi)), int)
for t in range(1, len(o)):
s = d[:, None] + lA; back[t] = s.argmax(0); d = s.max(0) + lB[:, o[t]]
path = [int(d.argmax())]
for t in range(len(o) - 1, 0, -1): path.append(int(back[t, path[-1]]))
return np.array(path[::-1])
alpha, c = forward(o); beta = backward(o, c); gamma = alpha * beta
print(f'log P(observations) = {np.log(c).sum():.2f}')
print(f"{'guess each state from':<44} accuracy")
print(f"{'its own observation only (no model of time)':<44} {np.mean((PI[:, None] * B[:, o]).argmax(0) == z):.3f}")
print(f"{'filtering, P(z_t | o_1..t)':<44} {np.mean(alpha.argmax(1) == z):.3f}")
print(f"{'smoothing, P(z_t | o_1..T)':<44} {np.mean(gamma.argmax(1) == z):.3f}")
print(f"{'Viterbi, the best whole sequence':<44} {np.mean(viterbi(o) == z):.3f}")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
fig, (a1, a2) = plt.subplots(2, 1, figsize=(11, 4.6), sharex=True)
colours = ['#2a6b80', '#e69f00', '#c0504d']
for i, s in enumerate(STATES):
a1.fill_between(range(300), 0, 1, where=z == i, step='mid', color=colours[i], alpha=0.35, label=f'true: {s}')
a1.scatter(range(300), (o + 0.5) / 3, s=8, c='k', label='vibration (low, medium, high)')
a1.set_yticks([]); a1.legend(loc='upper left', ncol=4, fontsize=8); a1.set_ylim(0, 1.25)
a2.plot(alpha[:, 2], color='#999999', label='filtered P(faulty)'); a2.plot(gamma[:, 2], color='#c0504d', label='smoothed P(faulty)')
a2.set_xlabel('time step'); a2.set_ylim(0, 1); a2.legend(loc='upper left', fontsize=8)
plt.tight_layout(); plt.show()
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.
for T in [100, 500, 1000]:
_, oo = hmm_sample(T, np.random.default_rng(T))
a = PI * B[:, oo[0]]
for t in range(1, T): a = (a @ A) * B[:, oo[t]]
print(f'T = {T:>4}: unnormalised P(observations) = {a.sum():.3e} normalised: log P = {np.log(forward(oo)[1]).sum():.1f}')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 and emissions in state . 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 () and of each transition (); 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 ) and only the emissions are random.
def baum_welch(seqs, pi, A_, B_, iters=150):
history = []
for _ in range(iters):
pi_c, A_c, B_c, ll = np.zeros_like(pi), np.zeros_like(A_), np.zeros_like(B_), 0.0
for o in seqs:
al, c = forward(o, pi, A_, B_); be = backward(o, c, A_, B_); g = al * be
ll += np.log(c).sum(); pi_c += g[0]
A_c += np.einsum('ti,ij,tj->ij', al[:-1], A_, B_[:, o[1:]].T * be[1:] / c[1:, None]) # expected transitions
for k in range(B_.shape[1]): B_c[:, k] += g[o == k].sum(0) # expected emissions
history.append(ll)
pi, A_, B_ = pi_c / pi_c.sum(), A_c / A_c.sum(1, keepdims=True), B_c / B_c.sum(1, keepdims=True)
return pi, A_, B_, history
seqs = [hmm_sample(200, np.random.default_rng(100 + i))[1] for i in range(20)]
true_ll = sum(np.log(forward(s)[1]).sum() for s in seqs)
print(f'log-likelihood of the 20 sequences under the true model: {true_ll:.1f}\n')
learned = {}
for kind in ['random', 'sticky']:
for seed in range(3):
r = np.random.default_rng(seed)
A0 = r.dirichlet(np.ones(3), 3) if kind == 'random' else np.full((3, 3), 0.05) + 0.85 * np.eye(3)
pi_, A_, B_, h = baum_welch(seqs, np.ones(3) / 3, A0, r.dirichlet(np.ones(3), 3))
order = np.argsort(-B_[:, 0]) # name states by P(low vibration), most first
learned[kind, seed] = (A_[order][:, order], B_[order], h)
print(f'{kind:>6} start {seed}: final log-likelihood {h[-1]:.1f}')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
for kind in ['random', 'sticky']:
A_, B_, _ = learned[kind, 0]
print(f'{kind} start 0, learned A:\n{np.round(A_, 2)}\nlearned B:\n{np.round(B_, 2)}\n')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 and ; the third reaches . All three sticky starts reach , above the true model’s , 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 : 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
The filtered distribution stays Gaussian, , and the Kalman filter updates it in two steps:
predict: , ;
update: the gain ; , .
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.
F = np.array([[1.0, 1.0], [0.0, 1.0]]); H = np.array([[1.0, 0.0]])
Q = 0.05 * np.array([[0.25, 0.5], [0.5, 1.0]]); R = np.array([[9.0]])
rng = np.random.default_rng(1); T = 100
x = np.zeros((T, 2)); x[0] = [0, 1]
for t in range(1, T): x[t] = F @ x[t - 1] + rng.multivariate_normal([0, 0], Q)
y = x[:, 0] + rng.normal(0, 3, T)
seen = np.ones(T, bool); seen[60:76] = False
def kalman(y, seen, mu0=np.zeros(2), P0=np.eye(2) * 100):
mus, Ps, mu_pred, P_pred = [], [], [], []
mu, P = mu0, P0
for t in range(len(y)):
if t: mu, P = F @ mu, F @ P @ F.T + Q # predict
mu_pred.append(mu); P_pred.append(P)
if seen[t]: # update
K = P @ H.T @ np.linalg.inv(H @ P @ H.T + R)
mu = mu + (K @ (y[t] - H @ mu)).ravel(); P = (np.eye(2) - K @ H) @ P
mus.append(mu); Ps.append(P)
return np.array(mus), np.array(Ps), np.array(mu_pred), np.array(P_pred)
def rts(mus, Ps, mu_pred, P_pred):
ms, Pss = mus.copy(), Ps.copy()
for t in range(len(mus) - 2, -1, -1):
G = Ps[t] @ F.T @ np.linalg.inv(P_pred[t + 1])
ms[t] = mus[t] + G @ (ms[t + 1] - mu_pred[t + 1]); Pss[t] = Ps[t] + G @ (Pss[t + 1] - P_pred[t + 1]) @ G.T
return ms, Pss
mus, Ps, mp, Pp = kalman(y, seen); ms, Pss = rts(mus, Ps, mp, Pp)
rmse = lambda e: np.sqrt(np.mean(e ** 2))
print(f'position error (RMSE, steps with a measurement): measurement {rmse(y[seen] - x[seen, 0]):.2f} m, '
f'filtered {rmse(mus[seen, 0] - x[seen, 0]):.2f} m, smoothed {rmse(ms[seen, 0] - x[seen, 0]):.2f} m')
print(f'during the blind steps 60-75: filtered {rmse(mus[~seen, 0] - x[~seen, 0]):.2f} m, smoothed {rmse(ms[~seen, 0] - x[~seen, 0]):.2f} m')
print(f'filter standard deviation of the position: step 59 {np.sqrt(Ps[59, 0, 0]):.2f} m, step 75 {np.sqrt(Ps[75, 0, 0]):.2f} m, step 76 {np.sqrt(Ps[76, 0, 0]):.2f} m')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
fig, ax = plt.subplots(figsize=(11, 3.8)); t = np.arange(T)
ax.axvspan(60, 75.5, color='#eeeeee', label='sensor blind')
ax.plot(t[seen], y[seen], '.', color='#999999', label='measurements')
ax.plot(t, x[:, 0], 'k', lw=1, label='true position')
ax.plot(t, mus[:, 0], color='#2a6b80', label='filtered'); sd = np.sqrt(Ps[:, 0, 0])
ax.fill_between(t, mus[:, 0] - 2 * sd, mus[:, 0] + 2 * sd, color='#2a6b80', alpha=0.15, label='filtered ± 2 sd')
ax.plot(t, ms[:, 0], color='#c0504d', ls='--', label='smoothed')
ax.set_xlabel('time step'); ax.set_ylabel('position (m)'); ax.legend(fontsize=8, ncol=3); plt.tight_layout(); plt.show()
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 for each clique :
Potentials are not probabilities: they say which joint values are compatible. Independence is read by plain separation: when every path from to passes through , 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 , the partition function, a sum over every joint state. Learning and exact likelihoods need it; for a grid of binary pixels it has terms.
def ising_Z(n, beta=0.5):
"""Partition function of an n x n grid of +-1 pixels with potential exp(beta * x_i x_j) per neighbouring pair, by enumeration."""
states = np.array(list(itertools.product([-1, 1], repeat=n * n))).reshape(-1, n, n)
energy = (states[:, 1:, :] * states[:, :-1, :]).sum((1, 2)) + (states[:, :, 1:] * states[:, :, :-1]).sum((1, 2))
return np.exp(beta * energy).sum()
for n in [2, 3, 4]:
t0 = time.time(); Zn = ising_Z(n)
print(f'{n} x {n} grid: {2 ** (n * n):>6} states, Z = {Zn:.4g}, {1000 * (time.time() - t0):.0f} ms')
print('64 x 64 grid: 2^4096 states, about 10^1233: no enumeration will ever finish')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 is observed through noise that flips 15% of the pixels, giving . The Ising prior says that neighbouring pixels tend to agree, and each observed pixel pulls its hidden pixel towards its value:
Here 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.
n = 64; I, J = np.mgrid[:n, :n]
clean = np.where(((I - 24) ** 2 + (J - 22) ** 2 < 15 ** 2) | ((I > 34) & (I < 56) & (J > 34) & (J < 58)), 1, -1)
noisy = np.where(np.random.default_rng(2).random((n, n)) < 0.15, -clean, clean)
eta = 0.5 * np.log(0.85 / 0.15)
def neighbour_sum(x):
s = np.zeros_like(x, float)
s[1:] += x[:-1]; s[:-1] += x[1:]; s[:, 1:] += x[:, :-1]; s[:, :-1] += x[:, 1:]
return s
def icm(y, beta, max_sweeps=20):
x = y.copy()
for sweep in range(max_sweeps):
changed = 0
for i, j in itertools.product(range(n), range(n)):
s = (x[i - 1, j] if i else 0) + (x[i + 1, j] if i < n - 1 else 0) + (x[i, j - 1] if j else 0) + (x[i, j + 1] if j < n - 1 else 0)
new = 1 if beta * s + eta * y[i, j] > 0 else -1
changed += new != x[i, j]; x[i, j] = new
if not changed: break
return x, sweep + 1
def gibbs_denoise(y, beta, sweeps=60, burn=10, seed=0):
rng = np.random.default_rng(seed); x = y.copy(); total = np.zeros((n, n))
for sweep in range(sweeps):
for parity in (0, 1): # checkerboard: half the pixels at once
mask = (I + J) % 2 == parity
p = 1 / (1 + np.exp(-2 * (beta * neighbour_sum(x) + eta * y)))
x = np.where(mask, np.where(rng.random((n, n)) < p, 1, -1), x)
if sweep >= burn: total += x == 1
return total / (sweeps - burn) # P(pixel = +1 | y), estimated
print(f'noisy image: {np.mean(noisy != clean):.1%} of pixels wrong')
for beta in [0.3, 0.7, 1.0, 2.0]:
x_icm, sweeps = icm(noisy, beta); p_g = gibbs_denoise(noisy, beta)
print(f'beta = {beta}: ICM {np.mean(x_icm != clean):.1%} wrong ({sweeps} sweeps); Gibbs {np.mean(np.where(p_g > 0.5, 1, -1) != clean):.1%} wrong')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
beta = 1.0; x_icm, _ = icm(noisy, beta); p_g = gibbs_denoise(noisy, beta)
fig, axes = plt.subplots(1, 4, figsize=(12, 3.3))
for ax, img, title in zip(axes, [clean, noisy, x_icm, p_g * 2 - 1], ['clean', 'noisy (15% flipped)', 'ICM, beta = 1', 'Gibbs: P(pixel = 1), beta = 1']):
ax.imshow(img, cmap='gray', vmin=-1, vmax=1); ax.set_title(title, fontsize=10); ax.axis('off')
plt.tight_layout(); plt.show()
Enumerating the 216 states of a 4 × 4 grid already takes about a tenth of a second; each extra pixel doubles the work.
With the prior is too weak to overrule the noise everywhere, and 7.2% of pixels stay wrong. From 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 , 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 , the labels given the whole input, and never the input itself, so its features may look at any part of the input:
This is a linear-chain CRF: an MRF over the labels, conditioned on the input. Its 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.
EMIT = np.array([[0.50, 0.30, 0.15, 0.05], [0.05, 0.15, 0.30, 0.50]])
def sticky_sequences(count, T, rng, copy=0.6, stay=0.9):
X, Y = [], []
for _ in range(count):
y, o = np.zeros(T, int), np.zeros(T, int); y[0] = rng.integers(2); o[0] = rng.choice(4, p=EMIT[y[0]])
for t in range(1, T):
y[t] = y[t - 1] if rng.random() < stay else 1 - y[t - 1]
o[t] = o[t - 1] if rng.random() < copy else rng.choice(4, p=EMIT[y[t]])
X.append(o); Y.append(y)
return X, Y
rng = np.random.default_rng(0)
X_train, Y_train = sticky_sequences(200, 40, rng); X_test, Y_test = sticky_sequences(300, 40, rng)
def chain_marginals(U, Tm):
"""Label marginals of a chain with unary log-scores U (T x K) and transition log-scores Tm (K x K); also log Z."""
la, lb = np.zeros_like(U), np.zeros_like(U); la[0] = U[0]
for t in range(1, len(U)): la[t] = U[t] + logsumexp(la[t - 1][:, None] + Tm, axis=0)
for t in range(len(U) - 2, -1, -1): lb[t] = logsumexp(Tm + (U[t + 1] + lb[t + 1])[None], axis=1)
logZ = logsumexp(la[-1])
return np.exp(la + lb - logZ), la, lb, logZ
# the HMM: tables by counting on the labelled training sequences (pseudo-count 1)
pi_h = np.ones(2); A_h = np.ones((2, 2)); B_h = np.ones((2, 4))
for o, y in zip(X_train, Y_train):
pi_h[y[0]] += 1; np.add.at(A_h, (y[:-1], y[1:]), 1); np.add.at(B_h, (y, o), 1)
pi_h, A_h, B_h = pi_h / pi_h.sum(), A_h / A_h.sum(1, keepdims=True), B_h / B_h.sum(1, keepdims=True)
def hmm_labels(o):
U = np.log(B_h[:, o]).T.copy(); U[0] += np.log(pi_h)
return chain_marginals(U, np.log(A_h))[0].argmax(1)
# the CRF: weights for (label, symbol, repeats-previous), label transitions, first label
def repeats(o): return np.r_[0, (o[1:] == o[:-1]).astype(int)]
def unpack(w): return w[:16].reshape(2, 4, 2), w[16:20].reshape(2, 2), w[20:22]
def crf_scores(w, o):
We, Wt, Ws = unpack(w); U = We[:, o, repeats(o)].T.copy(); U[0] += Ws
return U, Wt
def crf_nll(w, X, Y, lam=0.1):
"""Negative conditional log-likelihood (with an L2 penalty) and its gradient: expected minus observed feature counts."""
gE, gT, gS, f = np.zeros((2, 4, 2)), np.zeros((2, 2)), np.zeros(2), 0.0
for o, y in zip(X, Y):
U, Tm = crf_scores(w, o); marg, la, lb, logZ = chain_marginals(U, Tm); r = repeats(o)
f += logZ - (U[np.arange(len(y)), y].sum() + Tm[y[:-1], y[1:]].sum())
for k in range(2): np.add.at(gE[k], (o, r), marg[:, k])
np.add.at(gE, (y, o, r), -1)
gS += marg[0]; gS[y[0]] -= 1
gT += np.exp(la[:-1, :, None] + Tm[None] + (U[1:] + lb[1:])[:, None, :] - logZ).sum(0); np.add.at(gT, (y[:-1], y[1:]), -1)
return f + lam * w @ w, np.r_[gE.ravel(), gT.ravel(), gS] + 2 * lam * w
t0 = time.time()
w = minimize(crf_nll, np.zeros(22), args=(X_train, Y_train), jac=True, method='L-BFGS-B').x
crf_labels = lambda o: chain_marginals(*crf_scores(w, o))[0].argmax(1)
print(f'CRF trained in {time.time() - t0:.1f} s')
for name, f in [('HMM', hmm_labels), ('linear-chain CRF', crf_labels)]:
print(f'{name:<18} test accuracy {np.mean(np.concatenate([f(o) == y for o, y in zip(X_test, Y_test)])):.3f}')
We = unpack(w)[0]
print('\nCRF weight of each symbol for label 1 over label 0:')
print(' symbol new: ', np.round(We[1, :, 0] - We[0, :, 0], 2))
print(' symbol repeated:', np.round(We[1, :, 1] - We[0, :, 1], 2))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¶
| Model | Graph | State | Models | Inference | Typical use |
|---|---|---|---|---|---|
| Markov chain | directed, chain | observed | counting | text, weather, web navigation | |
| HMM | directed, chain | discrete, hidden | forward–backward, Viterbi | speech, sensors, biological sequences | |
| Kalman filter | directed, chain | continuous, linear-Gaussian | exact, closed form | tracking, navigation, finance | |
| Dynamic Bayesian network | directed, slices | any | Chapter 24’s methods, particle filters | several interacting processes | |
| Markov random field | undirected | any | Gibbs, ICM, belief propagation | images, spatial data | |
| Conditional random field | undirected, conditioned | discrete labels | 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¶
In the machine HMM, compute given that is normal, and the filtered distribution after observing high.
Why is smoothing more accurate than filtering? When can only filtering be used?
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?
In the Kalman filter, what happens to the gain when grows? When grows? Explain in words.
Write the potentials of a 3-pixel chain MRF that prefers equal neighbours, and compute by hand.
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.