Chapter 26 — Lab: Temporal and Undirected Models
Lab Overview¶
You will implement the algorithms of the chapter and check each against brute force on small cases: the three HMM algorithms, learning an HMM by counting, a Kalman step, the Gibbs conditional of an Ising pixel, and the probability of a label sequence under a linear-chain CRF.
| Exercise | Topic | Points |
|---|---|---|
| 1 | The forward algorithm | 15 |
| 2 | Smoothing with forward–backward | 15 |
| 3 | Viterbi decoding | 15 |
| 4 | Learning an HMM by counting | 10 |
| 5 | One Kalman step | 15 |
| 6 | The conditional of an Ising pixel | 15 |
| 7 | A CRF’s probability of a labelling | 15 |
| Challenge | Systematic resampling | +10 |
How it works. States and observations are integers from 0. An HMM is (pi, A, B) with A[i, j] and B[i, k] . Complete each function where you see # TODO and run the check cell under it. Do not change the check cells.
import itertools
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
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]])
O = np.array([0, 0, 2, 2, 1, 2, 0])
def joint(z, o, pi=PI, A=A, B=B):
"""P(z, o) for one state sequence: the brute-force reference."""
p = pi[z[0]] * B[z[0], o[0]]
for t in range(1, len(o)): p *= A[z[t - 1], z[t]] * B[z[t], o[t]]
return p
ALL = list(itertools.product(range(3), repeat=len(O))) # all 3^7 = 2187 state sequences
print('Setup complete')Exercise 1: The Forward Algorithm (15 points)¶
forward(o, pi, A, B) returns (alpha, loglik): alpha[t] is the filtered distribution (each row sums to 1), and loglik is . Normalise at each step and add up the logarithms of the normalisers.
def forward(o, pi, A, B):
# TODO
raise NotImplementedErrorcheck('log-likelihood equals the brute-force sum over 2187 sequences', lambda: np.isclose(forward(O, PI, A, B)[1], np.log(sum(joint(z, O) for z in ALL))))
check('the last row is P(z_7 | o_1..7)', lambda: np.allclose(forward(O, PI, A, B)[0][-1],
np.array([sum(joint(z, O) for z in ALL if z[-1] == k) for k in range(3)]) / sum(joint(z, O) for z in ALL)))
check('no underflow on 5 000 steps', lambda: np.isfinite(forward(np.tile(O, 715)[:5000], PI, A, B)[1]))Exercise 2: Smoothing with Forward–Backward (15 points)¶
smooth(o, pi, A, B) returns gamma with gamma[t] . Compute the backward messages from the end (normalised as you like, as long as each row of gamma is renormalised to 1).
def smooth(o, pi, A, B):
# TODO
raise NotImplementedErrorZ = sum(joint(z, O) for z in ALL)
ref = np.array([[sum(joint(z, O) for z in ALL if z[t] == k) / Z for k in range(3)] for t in range(len(O))])
check('every smoothed distribution matches brute force', lambda: np.allclose(smooth(O, PI, A, B), ref))
check('the last step equals the filtered one', lambda: np.allclose(smooth(O, PI, A, B)[-1], forward(O, PI, A, B)[0][-1]))Exercise 3: Viterbi Decoding (15 points)¶
viterbi(o, pi, A, B) returns the most likely state sequence as an integer array. Work with logarithms (np.log(0) is -inf, which is fine: silence the warning with np.errstate(divide='ignore')).
def viterbi(o, pi, A, B):
# TODO
raise NotImplementedErrorbest = max(ALL, key=lambda z: joint(z, O))
check('matches the brute-force best sequence', lambda: list(viterbi(O, PI, A, B)) == list(best))
O2 = np.array([2, 1, 1, 0, 0, 2, 2])
check('a second sequence', lambda: list(viterbi(O2, PI, A, B)) == list(max(ALL, key=lambda z: joint(z, O2))))
check('never uses the impossible transition faulty -> worn', lambda: not any(a == 2 and b == 1 for a, b in zip(viterbi(np.array([2] * 6 + [1] * 6), PI, A, B)[:-1], viterbi(np.array([2] * 6 + [1] * 6), PI, A, B)[1:])))Exercise 4: Learning an HMM by Counting (10 points)¶
count_hmm(Z, Os, K, M, alpha=1.0) learns (pi, A, B) from labelled sequences (Z[n] the states, Os[n] the observations of sequence n), adding the pseudo-count alpha to every cell before normalising each row.
def count_hmm(Z, Os, K, M, alpha=1.0):
# TODO
raise NotImplementedErrordef sample_hmm(T, rng):
z, o = np.zeros(T, int), np.zeros(T, int); z[0] = rng.choice(3, p=PI)
for t in range(T):
if t: z[t] = rng.choice(3, p=A[z[t - 1]])
o[t] = rng.choice(3, p=B[z[t]])
return z, o
rng = np.random.default_rng(0); data = [sample_hmm(500, rng) for _ in range(40)]
check('tiny case: states 0, 0, 1, 1 with observations 2, 2, 0, 0 and alpha = 0',
lambda: np.allclose(count_hmm([np.array([0, 0, 1, 1])], [np.array([2, 2, 0, 0])], 2, 3, 0.0)[2][0], [0, 0, 1])
and np.allclose(count_hmm([np.array([0, 0, 1, 1])], [np.array([2, 2, 0, 0])], 2, 3, 0.0)[1], [[0.5, 0.5], [0, 1]]))
check('learned A and B within 0.03 of the truth from 20 000 steps',
lambda: np.abs(count_hmm([z for z, _ in data], [o for _, o in data], 3, 3)[1] - A).max() < 0.03 and np.abs(count_hmm([z for z, _ in data], [o for _, o in data], 3, 3)[2] - B).max() < 0.03)Exercise 5: One Kalman Step (15 points)¶
kalman_step(mu, P, y, F, Q, H, R) predicts and then updates with the measurement y, and returns the new (mu, P). If y is None, it only predicts.
, ; ; ; .
def kalman_step(mu, P, y, F, Q, H, R):
# TODO
raise NotImplementedErrorone = np.eye(1)
check('1-D, equal uncertainties: the estimate goes halfway and the variance halves', lambda: np.isclose(kalman_step(np.array([0.0]), 4 * one, np.array([10.0]), one, 0 * one, one, 4 * one)[0][0], 5) and np.isclose(kalman_step(np.array([0.0]), 4 * one, np.array([10.0]), one, 0 * one, one, 4 * one)[1][0, 0], 2))
check('no measurement: only the prediction, and the variance grows by Q', lambda: np.isclose(kalman_step(np.array([1.0]), one, None, 2 * one, one, one, one)[1][0, 0], 5) and kalman_step(np.array([1.0]), one, None, 2 * one, one, one, one)[0][0] == 2)
F2, H2 = np.array([[1.0, 1.0], [0.0, 1.0]]), np.array([[1.0, 0.0]])
def learns_speed():
mu, P = np.zeros(2), np.eye(2) * 100
for t in range(1, 30): mu, P = kalman_step(mu, P, np.array([3.0 * t]), F2, 0.01 * np.eye(2), H2, np.eye(1))
return abs(mu[1] - 3) < 0.1
check('from positions 3, 6, 9, ... it infers a speed of 3', learns_speed)Exercise 6: The Conditional of an Ising Pixel (15 points)¶
In the denoising model with , p_plus(x, y, i, j, beta, eta) returns . Only the 4 neighbours (fewer at the border) and matter: with the sum of the neighbours and the logistic function.
def p_plus(x, y, i, j, beta, eta):
# TODO
raise NotImplementedErrordef brute_p_plus(x, y, i, j, beta, eta):
def energy(xx):
return beta * ((xx[1:] * xx[:-1]).sum() + (xx[:, 1:] * xx[:, :-1]).sum()) + eta * (xx * y).sum()
xp, xm = x.copy(), x.copy(); xp[i, j], xm[i, j] = 1, -1
return 1 / (1 + np.exp(energy(xm) - energy(xp)))
rng = np.random.default_rng(1); X3, Y3 = rng.choice([-1, 1], (3, 3)), rng.choice([-1, 1], (3, 3))
check('centre pixel matches the ratio of the two full probabilities', lambda: np.isclose(p_plus(X3, Y3, 1, 1, 0.7, 0.5), brute_p_plus(X3, Y3, 1, 1, 0.7, 0.5)))
check('a corner pixel (two neighbours)', lambda: np.isclose(p_plus(X3, Y3, 0, 2, 1.2, 0.3), brute_p_plus(X3, Y3, 0, 2, 1.2, 0.3)))
check('beta = 0: only the observation counts', lambda: np.isclose(p_plus(X3, np.ones((3, 3), int), 1, 1, 0.0, 0.5), 1 / (1 + np.exp(-1.0))))Exercise 7: A CRF’s Probability of a Labelling (15 points)¶
A linear-chain CRF over positions and labels is given by its unary scores U (, already computed from the input) and transition scores Tm (). The score of a labelling is , and . crf_log_prob(U, Tm, z) returns , with computed by the forward algorithm in log space (use logsumexp).
from scipy.special import logsumexp
def crf_log_prob(U, Tm, z):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(2); U5, T5 = rng.normal(size=(6, 3)), rng.normal(size=(3, 3))
labellings = list(itertools.product(range(3), repeat=6))
check('the probabilities of all 729 labellings sum to 1', lambda: np.isclose(sum(np.exp(crf_log_prob(U5, T5, np.array(z))) for z in labellings), 1))
check('matches a brute-force normalisation', lambda: np.isclose(crf_log_prob(U5, T5, np.array([0, 1, 1, 2, 0, 0])),
(U5[np.arange(6), [0, 1, 1, 2, 0, 0]].sum() + T5[[0, 1, 1, 2, 0], [1, 1, 2, 0, 0]].sum())
- logsumexp([U5[np.arange(6), list(z)].sum() + T5[list(z[:-1]), list(z[1:])].sum() for z in labellings])))
check('no overflow with large scores', lambda: np.isfinite(crf_log_prob(U5 * 300, T5 * 300, np.zeros(6, int))))Challenge: Systematic Resampling (+10 points)¶
A particle filter resamples particles in proportion to their weights. Systematic resampling draws one uniform number and takes the particles at the positions of the cumulative weights. systematic(weights, rng) returns the chosen indices (sorted). Each particle is then chosen either or times, less random than independent draws.
def systematic(weights, rng):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(3); w = rng.dirichlet(np.ones(50))
idx = lambda: systematic(w, np.random.default_rng(4))
check('returns N sorted indices in range', lambda: len(idx()) == 50 and np.all(np.diff(idx()) >= 0) and idx().min() >= 0 and idx().max() < 50)
check('each particle is chosen floor or ceil of N w times', lambda: np.all(np.abs(np.bincount(idx(), minlength=50) - 50 * w) < 1 + 1e-9))
check('equal weights give every particle exactly once', lambda: list(systematic(np.full(8, 1 / 8), np.random.default_rng(0))) == list(range(8)))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: in Exercise 3, Viterbi’s path and the sequence of the most likely states at each step (from Exercise 2) can differ. Find an observation sequence where they do, and explain why both answers are correct for their own question.