Chapter 26 — Implementation: Temporal and Undirected Models in Practice
Four applications:
Activity recognition from a wearable sensor: an HMM with Gaussian emissions against a classifier that looks at one moment at a time.
Tracking in two dimensions with a Kalman filter, and protecting it from faulty measurements.
Cleaning a scanned text with a Markov random field, against a median filter.
Localising a robot with a particle filter, when the state’s distribution has several peaks and no Kalman filter applies.
import itertools, time
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import median_filter
from scipy.stats import norm1. Activity Recognition with a Gaussian HMM¶
A wrist sensor reports, every second, the average magnitude of acceleration. The wearer is sitting, walking or running, and keeps an activity for a while. The readings of the activities overlap: a vigorous gesture while sitting looks like walking. The emissions are now continuous: , and the forward–backward and Viterbi algorithms are unchanged, with densities in place of the emission table.
ACTS = ['sitting', 'walking', 'running']
A = np.array([[0.97, 0.03, 0.00], [0.03, 0.94, 0.03], [0.00, 0.08, 0.92]])
MEAN, SD = np.array([1.0, 2.2, 3.6]), np.array([0.45, 0.6, 0.7])
def simulate(T, rng):
z = np.zeros(T, int); z[0] = rng.integers(3)
for t in range(1, T): z[t] = rng.choice(3, p=A[z[t - 1]])
return z, rng.normal(MEAN[z], SD[z])
rng = np.random.default_rng(0)
train = [simulate(600, rng) for _ in range(5)]
test = [simulate(600, rng) for _ in range(10)]
# learning with labels is counting: transitions, and each activity's mean and standard deviation
A_hat = np.ones((3, 3))
for z, _ in train: np.add.at(A_hat, (z[:-1], z[1:]), 1)
A_hat /= A_hat.sum(1, keepdims=True)
zs, os_ = np.concatenate([z for z, _ in train]), np.concatenate([o for _, o in train])
m_hat = np.array([os_[zs == k].mean() for k in range(3)]); s_hat = np.array([os_[zs == k].std() for k in range(3)])
prior = np.bincount(zs, minlength=3) / len(zs)
print('learned means', np.round(m_hat, 2), 'standard deviations', np.round(s_hat, 2))
print('learned transitions\n', np.round(A_hat, 3))
def smooth(o, A, means, sds, pi):
E = norm.pdf(o[:, None], means, sds) # emission densities, T x K
alpha, c = np.zeros_like(E), np.zeros(len(o)); a = pi * E[0]
for t in range(len(o)):
if t: a = (alpha[t - 1] @ A) * E[t]
c[t] = a.sum(); alpha[t] = a / c[t]
beta = np.ones_like(E)
for t in range(len(o) - 2, -1, -1): beta[t] = A @ (E[t + 1] * beta[t + 1]) / c[t + 1]
return alpha, alpha * beta
def accuracy(pred_fn):
return np.mean(np.concatenate([pred_fn(o) == z for z, o in test]))
per_moment = lambda o: (prior * norm.pdf(o[:, None], m_hat, s_hat)).argmax(1)
filtered = lambda o: smooth(o, A_hat, m_hat, s_hat, prior)[0].argmax(1)
smoothed = lambda o: smooth(o, A_hat, m_hat, s_hat, prior)[1].argmax(1)
print(f"\n{'method':<40} accuracy")
for name, f in [('one moment at a time (Gaussian Bayes)', per_moment), ('HMM, filtering (real time)', filtered), ('HMM, smoothing (afterwards)', smoothed)]:
print(f'{name:<40} {accuracy(f):.3f}')learned means [1.01 2.17 3.63] standard deviations [0.44 0.61 0.68]
learned transitions
[[0.97 0.03 0.001]
[0.034 0.935 0.031]
[0.002 0.069 0.93 ]]
method accuracy
one moment at a time (Gaussian Bayes) 0.825
HMM, filtering (real time) 0.934
HMM, smoothing (afterwards) 0.971
Source
z, o = test[0]; seg = slice(0, 250)
fig, (a1, a2) = plt.subplots(2, 1, figsize=(11, 4.2), sharex=True)
a1.plot(np.arange(600)[seg], o[seg], color='#999999', lw=0.8); a1.set_ylabel('acceleration')
for k, col in enumerate(['#2a6b80', '#e69f00', '#c0504d']):
a1.fill_between(np.arange(600)[seg], 0, 5.5, where=z[seg] == k, step='mid', color=col, alpha=0.25, label=ACTS[k])
a1.legend(ncol=3, fontsize=8, loc='upper left')
a2.step(np.arange(600)[seg], per_moment(o)[seg] + 0.06, where='mid', color='#999999', label='one moment at a time')
a2.step(np.arange(600)[seg], smoothed(o)[seg] - 0.06, where='mid', color='#c0504d', label='HMM, smoothed')
a2.step(np.arange(600)[seg], z[seg], where='mid', color='k', lw=0.8, ls='--', label='true')
a2.set_yticks([0, 1, 2]); a2.set_yticklabels(ACTS); a2.set_xlabel('second'); a2.legend(fontsize=8, ncol=3, loc='upper left')
plt.tight_layout(); plt.show()
Counting on 3 000 labelled seconds recovers the model closely (means 1.01, 2.17, 3.63 against 1.0, 2.2, 3.6). Looking at one second at a time, a Gaussian classifier is right 82.5% of the time: the plot shows its label flickering wherever a reading strays into a neighbouring activity’s range. The HMM knows that activities last, so a single odd reading does not switch the label: filtering, usable in real time on the watch, is right 93.4% of the time, and smoothing, for the daily summary computed in the evening, 97.1%. The remaining errors sit at the changes of activity, where even hindsight cannot place the boundary to the second.
2. Tracking in Two Dimensions, with Faulty Measurements¶
A drone flies in a plane; a camera reports its position every step with a noise of 2 m, but 5% of the reports are faulty (another object detected), off by about 30 m. The state is position and velocity in both directions (4 numbers). A plain Kalman filter trusts every report. A gated filter first computes the innovation and its covariance ; under the model, the Mahalanobis distance follows a distribution with 2 degrees of freedom, and a report beyond its 99.9% point (13.8) is rejected as an outlier: the filter only predicts at that step.
dt = 1.0
F = np.block([[np.eye(2), dt * np.eye(2)], [np.zeros((2, 2)), np.eye(2)]])
H = np.hstack([np.eye(2), np.zeros((2, 2))])
Q = 0.02 * np.block([[dt ** 3 / 3 * np.eye(2), dt ** 2 / 2 * np.eye(2)], [dt ** 2 / 2 * np.eye(2), dt * np.eye(2)]])
R = 4.0 * np.eye(2)
rng = np.random.default_rng(3); T = 150
x = np.zeros((T, 4)); x[0] = [0, 0, 1.0, 0.5]
for t in range(1, T):
x[t] = F @ x[t - 1] + rng.multivariate_normal(np.zeros(4), Q)
if 60 <= t < 70: x[t, 2:] = x[t - 1, 2:] @ np.array([[0.95, 0.31], [-0.31, 0.95]]) # a turn
faulty = rng.random(T) < 0.05
y = x[:, :2] + rng.normal(0, 2, (T, 2)) + faulty[:, None] * rng.normal(0, 30, (T, 2))
print(f'{faulty.sum()} faulty reports among {T}')
def track(y, Qf, gate=None):
"""Kalman filter with process noise Qf; with a gate, reports whose Mahalanobis distance exceeds it are ignored."""
mu, P, out, rejected = np.r_[y[0], 0, 0], np.diag([4, 4, 10, 10.0]), [], []
for t in range(len(y)):
if t: mu, P = F @ mu, F @ P @ F.T + Qf
nu = y[t] - H @ mu; S = H @ P @ H.T + R
if gate is not None and nu @ np.linalg.solve(S, nu) > gate:
rejected.append(t) # an outlier: keep the prediction
else:
K = P @ H.T @ np.linalg.inv(S); mu = mu + K @ nu; P = (np.eye(4) - K @ H) @ P
out.append(mu.copy())
return np.array(out), rejected
err = lambda est: np.sqrt(np.mean(np.sum((est[:, :2] - x[:, :2]) ** 2, 1)))
speed_err = lambda est: np.sqrt(np.mean(np.sum((est[:, 2:] - x[:, 2:]) ** 2, 1)))
good = ~faulty
print(f'raw reports: position error (RMSE) {err(y):.2f} m; the good reports alone {np.sqrt(np.mean(np.sum((y[good] - x[good, :2]) ** 2, 1))):.2f} m\n')
runs = {}
for name, Qf, gate in [('plain, process noise Q', Q, None), ('gated, process noise Q', Q, 13.8),
('plain, process noise 5 Q', 5 * Q, None), ('gated, process noise 5 Q', 5 * Q, 13.8)]:
est, rejected = track(y, Qf, gate); runs[name] = est
print(f'{name:<26} position {err(est):6.2f} m velocity {speed_err(est):5.2f} m/step rejected {len(rejected):>2} reports ({sum(faulty[rejected])} faulty)')
plain, gated = runs['plain, process noise 5 Q'], runs['gated, process noise 5 Q']7 faulty reports among 150
raw reports: position error (RMSE) 11.98 m; the good reports alone 2.87 m
plain, process noise Q position 7.28 m velocity 3.31 m/step rejected 0 reports (0 faulty)
gated, process noise Q position 35.15 m velocity 1.52 m/step rejected 49 reports (7 faulty)
plain, process noise 5 Q position 7.95 m velocity 3.56 m/step rejected 0 reports (0 faulty)
gated, process noise 5 Q position 1.88 m velocity 0.75 m/step rejected 7 reports (7 faulty)
Source
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(y[~faulty, 0], y[~faulty, 1], '.', color='#bbbbbb', label='reports')
ax.plot(y[faulty, 0], y[faulty, 1], 'x', color='#c0504d', label='faulty reports')
ax.plot(x[:, 0], x[:, 1], 'k', lw=1, label='true path')
ax.plot(runs['gated, process noise Q'][:, 0], runs['gated, process noise Q'][:, 1], color='#999999', ls=':', label='gated, process noise Q (lost)')
ax.plot(plain[:, 0], plain[:, 1], color='#e69f00', label='plain, 5 Q')
ax.plot(gated[:, 0], gated[:, 1], color='#2a6b80', label='gated, 5 Q')
ax.set_aspect('equal'); ax.legend(fontsize=8); ax.set_xlabel('x (m)'); ax.set_ylabel('y (m)'); ax.set_xlim(x[:, 0].min() - 15, x[:, 0].max() + 15); ax.set_ylim(x[:, 1].min() - 15, x[:, 1].max() + 15)
plt.tight_layout(); plt.show()
The 7 faulty reports, 30 m off, make the raw reports’ error 11.98 m. A plain Kalman filter trusts every report and is pulled towards each faulty one (the orange spikes); its position error is 7–8 m whatever its process noise.
The gate needs a model that is honest about its own uncertainty. With the process noise that describes straight flight, the filter is too confident during the turn: its prediction drifts off the true path, the good reports now look like outliers, and it rejects them, 42 good reports in all. It never recovers (the dotted line): an error of 35 m, worse than no filter. With , which allows for manoeuvres, the gate rejects exactly the 7 faulty reports and nothing else: position error 1.88 m, below the good reports’ own 2.9 m, and a velocity, never measured, estimated within 0.75 m per step. An outlier gate is only as good as the uncertainty it is computed from.
3. Cleaning a Scanned Text with a Markov Random Field¶
A line of text is rendered as a black-and-white image and degraded by flipping 12% of its pixels, as a bad scan or a fax would. We clean it with the Ising model of the chapter (Gibbs sampling, posterior marginals) and compare with a median filter, the usual quick fix.
fig = plt.figure(figsize=(6, 1), dpi=100); fig.text(0.02, 0.2, 'Graphical models', fontsize=40, family='DejaVu Sans')
fig.canvas.draw(); img = np.asarray(fig.canvas.buffer_rgba())[..., 0]; plt.close(fig)
clean = np.where(img < 128, 1, -1)
h, w = clean.shape; Ig, Jg = np.mgrid[:h, :w]
noisy = np.where(np.random.default_rng(4).random(clean.shape) < 0.12, -clean, clean)
eta = 0.5 * np.log(0.88 / 0.12)
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 gibbs_denoise(y, beta, sweeps=60, burn=10, seed=0):
rng = np.random.default_rng(seed); x = y.copy(); ones = np.zeros(y.shape)
for sweep in range(sweeps):
for parity in (0, 1):
p = 1 / (1 + np.exp(-2 * (beta * neighbour_sum(x) + eta * y)))
x = np.where((Ig + Jg) % 2 == parity, np.where(rng.random(y.shape) < p, 1, -1), x)
if sweep >= burn: ones += x == 1
return np.where(ones / (sweeps - burn) > 0.5, 1, -1)
ink = clean == 1
def report(name, out):
print(f'{name:<24} {np.mean(out != clean):6.2%} of pixels wrong; ink pixels lost {np.mean(out[ink] != 1):6.1%}')
print(f'image {h} x {w}, ink {ink.mean():.1%} of pixels')
report('noisy', noisy)
report('median filter 3 x 3', median_filter(noisy, size=3))
results = {}
for beta in [0.5, 0.8, 1.5]:
results[beta] = gibbs_denoise(noisy, beta); report(f'MRF, beta = {beta}', results[beta])image 100 x 600, ink 9.4% of pixels
noisy 11.95% of pixels wrong; ink pixels lost 11.4%
median filter 3 x 3 1.27% of pixels wrong; ink pixels lost 5.8%
MRF, beta = 0.5 1.10% of pixels wrong; ink pixels lost 4.6%
MRF, beta = 0.8 0.56% of pixels wrong; ink pixels lost 3.0%
MRF, beta = 1.5 0.65% of pixels wrong; ink pixels lost 3.5%
Source
fig, axes = plt.subplots(5, 1, figsize=(9, 6.5))
for ax, (title, im) in zip(axes, [('clean', clean), ('noisy: 12% of pixels flipped', noisy), ('median filter 3 x 3', median_filter(noisy, size=3)),
('MRF, beta = 0.8', results[0.8]), ('MRF, beta = 1.5', results[1.5])]):
ax.imshow(-im, cmap='gray', vmin=-1, vmax=1); ax.set_title(title, fontsize=9, loc='left'); ax.axis('off')
plt.tight_layout(); plt.show()
The noise flips 12% of the pixels. A median filter removes most of it (1.27% wrong) but erodes the letters: it loses 5.8% of the ink, and the thin strokes come out ragged. The MRF with makes fewer errors (0.56%) and loses less ink (3.0%): the prior asks neighbours to agree, but the observed pixel still has its say, so a stroke supported by its own pixels survives. A weaker prior () leaves more noise, a stronger one () starts to round the corners of the letters: 0.65% wrong. As in Section 26.6, trades noise for detail.
4. Localising a Robot with a Particle Filter¶
A robot moves along a corridor 100 m long with doors at a few known places. Each second it moves about 1 m (with noise), and a sensor says “door” or “wall”, right 95% of the time. At the start it has no idea where it is. The belief about its position is multimodal: after seeing one door, it could be in front of any of them. A Kalman filter, whose belief is one Gaussian, cannot represent this.
A particle filter represents the belief by samples (particles). Each step: move every particle with the motion model (sampling the noise), weight it by the probability of the sensor reading at its position (likelihood weighting, Chapter 24), and resample particles in proportion to their weights, so that the cloud concentrates where the evidence points.
DOORS = [(9, 13), (20, 24), (50, 54), (76, 80)]
is_door = lambda pos: np.any([(a <= pos) & (pos < b) for a, b in DOORS], axis=0)
rng = np.random.default_rng(5); T, N = 60, 2000
true = np.zeros(T); true[0] = 3.0
for t in range(1, T): true[t] = true[t - 1] + 1 + rng.normal(0, 0.1)
reading = np.where(rng.random(T) < 0.95, is_door(true), ~is_door(true)) # 5% wrong
particles = rng.uniform(0, 100, N); history = []
for t in range(T):
if t: particles = particles + 1 + rng.normal(0, 0.3, N) # motion, with more noise than reality
weights = np.where(is_door(particles) == reading[t], 0.95, 0.05) # sensor model
weights /= weights.sum()
particles = particles[rng.choice(N, size=N, p=weights)] # resample
history.append(particles.copy())
if t in (0, 5, 10, 15, 20, 30, 59):
spread = np.percentile(particles, 95) - np.percentile(particles, 5)
print(f'step {t:>2}: true {true[t]:5.1f} m, mean of particles {particles.mean():5.1f} m, 90% of particles within {spread:5.1f} m')step 0: true 3.0 m, mean of particles 49.9 m, 90% of particles within 91.3 m
step 5: true 7.9 m, mean of particles 60.0 m, 90% of particles within 93.9 m
step 10: true 13.0 m, mean of particles 47.6 m, 90% of particles within 67.6 m
step 15: true 18.0 m, mean of particles 52.5 m, 90% of particles within 68.5 m
step 20: true 22.6 m, mean of particles 23.3 m, 90% of particles within 1.6 m
step 30: true 32.3 m, mean of particles 32.9 m, 90% of particles within 3.1 m
step 59: true 60.6 m, mean of particles 60.6 m, 90% of particles within 2.8 m
Source
fig, ax = plt.subplots(figsize=(11, 4))
for a, b in DOORS: ax.axhspan(a, b, color='#e69f00', alpha=0.25)
for t in range(T):
ax.scatter(np.full(200, t), history[t][:200], s=1, color='#2a6b80', alpha=0.4)
ax.plot(true, 'k', lw=1.2, label='true position'); ax.set_ylim(0, 100)
ax.set_xlabel('second'); ax.set_ylabel('position in the corridor (m)'); ax.legend(loc='upper left', fontsize=8)
ax.set_title('particles (200 of 2000 shown per step); doors in orange', fontsize=10)
plt.tight_layout(); plt.show()
At the start the particles cover the corridor. When the robot sees its first door (step 7), the particles in front of every door survive: the belief has four peaks, which the plot shows as four bands, and the mean of the particles (47.6 m at step 10) is a meaningless average between them. When the second door comes 11 m later, only the hypothesis “between the first two doors” explains both, and by step 20 90% of the particles are within 1.6 m of each other, around the true position. They then follow the robot, the spread kept at about 3 m by the motion noise and the readings.
A Kalman filter would have represented the first belief as one wide Gaussian centred on the mean, in the middle of a wall. Particle filters handle any motion and sensor model, at the cost of many samples; in high dimensions the particles needed grow quickly, the same weakness as likelihood weighting.
Summary¶
An HMM’s model of time turns weak per-moment evidence into reliable labels; smoothing beats filtering when you can wait.
A Kalman filter estimates what is never measured (velocity) and, with a gate on the innovation, ignores reports that its own model calls impossible.
An MRF prior removes noise while keeping shapes, where a median filter erodes thin strokes; the coupling trades noise for detail.
A particle filter tracks beliefs with several peaks, by likelihood weighting and resampling at every step.