Chapter 22: Probabilistic Graphical Models — Implementation
We build a small Bayesian-network toolkit from scratch, in plain Python and NumPy, and use it on the chapter’s examples:
A
BayesNetclass: joint probabilities and inference by enumerationVariable elimination with factors, and why it is faster
Sampling: rejection, likelihood weighting and Gibbs
Learning the tables from data
Hidden Markov models: forward, backward, Viterbi and Baum–Welch
import itertools, time
import numpy as np
import matplotlib.pyplot as plt
np.set_printoptions(precision=4, suppress=True)1. A Bayesian Network and Enumeration¶
All variables are Boolean. Each node stores its parents and a table mapping each combination of parent values to .
class BayesNet:
def __init__(self):
self.parents, self.cpt, self.order = {}, {}, [] # order: a topological order
def add(self, name, parents, table):
"""table: {tuple of parent values: P(name = True | parents)}; a float if there are no parents."""
self.parents[name] = list(parents)
self.cpt[name] = table if parents else {(): table}
self.order.append(name)
def prob(self, name, value, assignment):
"""P(name = value | its parents' values in assignment)."""
p_true = self.cpt[name][tuple(assignment[p] for p in self.parents[name])]
return p_true if value else 1 - p_true
def joint(self, assignment):
return np.prod([self.prob(v, assignment[v], assignment) for v in self.order])
def enumerate_query(self, query, evidence):
"""P(query = True | evidence), summing the joint over every hidden variable."""
hidden = [v for v in self.order if v != query and v not in evidence]
totals = {}
for q in (True, False):
totals[q] = sum(self.joint({**evidence, query: q, **dict(zip(hidden, values))})
for values in itertools.product((True, False), repeat=len(hidden)))
return totals[True] / (totals[True] + totals[False])
alarm = BayesNet()
alarm.add('B', [], 0.001)
alarm.add('E', [], 0.002)
alarm.add('A', ['B', 'E'], {(True, True): 0.95, (True, False): 0.94, (False, True): 0.29, (False, False): 0.001})
alarm.add('J', ['A'], {(True,): 0.90, (False,): 0.05})
alarm.add('M', ['A'], {(True,): 0.70, (False,): 0.01})
print('P(j, m, a, ¬b, ¬e) =', round(alarm.joint({'J': True, 'M': True, 'A': True, 'B': False, 'E': False}), 6))
print('P(b | j, m) =', round(alarm.enumerate_query('B', {'J': True, 'M': True}), 4))
print('P(b | j) =', round(alarm.enumerate_query('B', {'J': True}), 4))
print('explaining away: P(b | a) =', round(alarm.enumerate_query('B', {'A': True}), 4),
' P(b | a, e) =', round(alarm.enumerate_query('B', {'A': True, 'E': True}), 4))P(j, m, a, ¬b, ¬e) = 0.000628
P(b | j, m) = 0.2842
P(b | j) = 0.0163
explaining away: P(b | a) = 0.3736 P(b | a, e) = 0.0033
All the chapter’s numbers come out. Enumeration loops over combinations of the hidden variables: fine here ( or 3), hopeless for 40 hidden variables.
2. Variable Elimination¶
A factor is a table over some variables. Two operations suffice:
multiply two factors (a table over the union of their variables);
sum out a variable (add the rows that differ only in it).
We store a factor as a list of variable names and a NumPy array with one axis of size 2 per variable (index 1 = True).
class Factor:
def __init__(self, variables, table):
self.vars, self.table = list(variables), np.asarray(table, float)
def multiply(self, other):
all_vars = self.vars + [v for v in other.vars if v not in self.vars]
return Factor(all_vars, self._expand(all_vars) * other._expand(all_vars))
def _expand(self, all_vars):
"""This factor's table broadcast over all_vars (axes in all_vars order)."""
t = np.moveaxis(self.table, range(len(self.vars)), [all_vars.index(v) for v in self.vars])
return t.reshape([2 if v in self.vars else 1 for v in all_vars])
def sum_out(self, var):
i = self.vars.index(var)
return Factor(self.vars[:i] + self.vars[i + 1:], self.table.sum(axis=i))
def node_factor(net, name, evidence):
"""The CPT of `name` as a factor, with evidence variables fixed (their axes removed)."""
variables = net.parents[name] + [name]
table = np.zeros([2] * len(variables))
for values in itertools.product((False, True), repeat=len(variables)):
assignment = dict(zip(variables, values))
table[tuple(int(v) for v in values)] = net.prob(name, assignment[name], assignment)
factor = Factor(variables, table)
for var, val in evidence.items():
if var in factor.vars:
i = factor.vars.index(var)
factor = Factor(factor.vars[:i] + factor.vars[i + 1:], np.take(factor.table, int(val), axis=i))
return factor
def eliminate_query(net, query, evidence, order=None):
factors = [node_factor(net, v, evidence) for v in net.order]
hidden = order or [v for v in net.order if v != query and v not in evidence]
for var in hidden:
involved = [f for f in factors if var in f.vars]
product = involved[0]
for f in involved[1:]:
product = product.multiply(f)
factors = [f for f in factors if var not in f.vars] + [product.sum_out(var)]
result = factors[0]
for f in factors[1:]:
result = result.multiply(f)
p = result.table / result.table.sum()
return p[1]
print('variable elimination: P(b | j, m) =', round(eliminate_query(alarm, 'B', {'J': True, 'M': True}), 4))variable elimination: P(b | j, m) = 0.2842
Same answer. The difference shows on a bigger network: a chain where each variable copies its parent with probability 0.9. We ask for .
def chain(n):
net = BayesNet()
net.add('X1', [], 0.5)
for i in range(2, n + 1):
net.add(f'X{i}', [f'X{i-1}'], {(True,): 0.9, (False,): 0.1})
return net
for n in [8, 12, 16, 20]:
net = chain(n)
t = time.perf_counter(); ve = eliminate_query(net, f'X{n}', {'X1': True}); t_ve = time.perf_counter() - t
if n <= 16:
t = time.perf_counter(); en = net.enumerate_query(f'X{n}', {'X1': True}); t_en = time.perf_counter() - t
print(f'n = {n:2d}: enumeration {en:.4f} in {t_en:7.3f} s elimination {ve:.4f} in {t_ve:.4f} s')
else:
print(f'n = {n:2d}: enumeration skipped (2^{n - 2} terms) elimination {ve:.4f} in {t_ve:.4f} s')n = 8: enumeration 0.6049 in 0.002 s elimination 0.6049 in 0.0004 s
n = 12: enumeration 0.5429 in 0.027 s elimination 0.5429 in 0.0005 s
n = 16: enumeration 0.5176 in 0.622 s elimination 0.5176 in 0.0008 s
n = 20: enumeration skipped (2^18 terms) elimination 0.5072 in 0.0010 s
Enumeration’s time doubles with each extra variable; elimination stays almost instant, because each step only handles a factor over two variables. (The exact answer, , slowly forgets the first variable, just like the RNN memory of Chapter 18.)
3. Sampling¶
def prior_sample(net, rng):
sample = {}
for v in net.order:
sample[v] = rng.random() < net.prob(v, True, sample)
return sample
def rejection_sampling(net, query, evidence, n, rng):
kept = [s for s in (prior_sample(net, rng) for _ in range(n)) if all(s[k] == v for k, v in evidence.items())]
return (np.mean([s[query] for s in kept]) if kept else np.nan), len(kept)
def likelihood_weighting(net, query, evidence, n, rng):
total = {True: 0.0, False: 0.0}
for _ in range(n):
sample, w = {}, 1.0
for v in net.order:
if v in evidence:
sample[v] = evidence[v]
w *= net.prob(v, evidence[v], sample)
else:
sample[v] = rng.random() < net.prob(v, True, sample)
total[sample[query]] += w
return total[True] / (total[True] + total[False])
def gibbs_sampling(net, query, evidence, n, rng, burn_in=1000):
hidden = [v for v in net.order if v not in evidence]
state = {**evidence, **{v: bool(rng.random() < 0.5) for v in hidden}}
children = {v: [c for c in net.order if v in net.parents[c]] for v in net.order}
count = 0
for step in range(n + burn_in):
v = hidden[step % len(hidden)]
weights = []
for value in (True, False): # P(v | Markov blanket) ∝ P(v | parents) Π P(child | its parents)
state[v] = value
weights.append(net.prob(v, value, state) * np.prod([net.prob(c, state[c], state) for c in children[v]]))
state[v] = rng.random() < weights[0] / sum(weights)
if step >= burn_in:
count += state[query]
return count / n
rng = np.random.default_rng(0)
ev = {'J': True, 'M': True}
est, kept = rejection_sampling(alarm, 'B', ev, 100_000, rng)
print(f'exact 0.2842')
print(f'rejection sampling {est:.4f} (kept {kept} of 100,000 samples)')
print(f'likelihood weighting {likelihood_weighting(alarm, "B", ev, 100_000, rng):.4f}')
print(f'Gibbs sampling {gibbs_sampling(alarm, "B", ev, 100_000, rng):.4f}')exact 0.2842
rejection sampling 0.3062 (kept 209 of 100,000 samples)
likelihood weighting 0.2608
Gibbs sampling 0.2839
Rejection sampling (left with about 200 usable samples) and likelihood weighting are still off by about 0.02 after 100,000 samples, because the evidence is rare. Gibbs sampling, which keeps the evidence fixed and wanders through the likely states, lands much closer here. Sampling shines on networks far too large for exact inference, where a rough answer is far better than none.
4. Learning the Tables from Data¶
We generate 5,000 “days” from the alarm network, forget its tables, and re-estimate each entry by counting, with Laplace smoothing (one pseudo-count for each value).
rng = np.random.default_rng(1)
data = [prior_sample(alarm, rng) for _ in range(5000)]
def learn_cpt(data, name, parents, pseudo=1.0):
table = {}
for values in itertools.product((True, False), repeat=len(parents)):
rows = [d for d in data if all(d[p] == v for p, v in zip(parents, values))]
table[values] = (sum(d[name] for d in rows) + pseudo) / (len(rows) + 2 * pseudo)
return table, {values: sum(all(d[p] == v for p, v in zip(parents, values)) for d in data) for values in table}
for name in ['A', 'J']:
learnt, counts = learn_cpt(data, name, alarm.parents[name])
for values, p in learnt.items():
print(f'P({name} | {dict(zip(alarm.parents[name], values))}): true {alarm.cpt[name][values]:.3f} learnt {p:.3f} ({counts[values]} matching days)')P(A | {'B': True, 'E': True}): true 0.950 learnt 0.500 (0 matching days)
P(A | {'B': True, 'E': False}): true 0.940 learnt 0.875 (6 matching days)
P(A | {'B': False, 'E': True}): true 0.290 learnt 0.273 (9 matching days)
P(A | {'B': False, 'E': False}): true 0.001 learnt 0.001 (4985 matching days)
P(J | {'A': True}): true 0.900 learnt 0.692 (11 matching days)
P(J | {'A': False}): true 0.050 learnt 0.052 (4989 matching days)
Where data is plentiful (no burglary, no earthquake: almost every day) the estimate is excellent. Where it is rare it is poor: , from only 11 days with an alarm, is off by 0.2, and for a burglary and an earthquake (never seen in 5,000 days) the estimate is just the smoothing prior, 0.5. Rare combinations are exactly where expert knowledge, or much more data, is needed.
5. Hidden Markov Models¶
The machine of the chapter: states OK (0) and Worn (1), readings Low (0) and High (1).
pi0 = np.array([0.9, 0.1])
A = np.array([[0.90, 0.10], # from OK
[0.05, 0.95]]) # from Worn
B = np.array([[0.8, 0.2], # OK emits Low, High
[0.3, 0.7]]) # Worn emits Low, High
def forward(obs, pi0, A, B):
alpha = np.zeros((len(obs), len(pi0)))
alpha[0] = pi0 * B[:, obs[0]]
for t in range(1, len(obs)):
alpha[t] = (alpha[t - 1] @ A) * B[:, obs[t]] # predict, then weight by the evidence
return alpha
def backward(obs, A, B):
beta = np.ones((len(obs), A.shape[0]))
for t in range(len(obs) - 2, -1, -1):
beta[t] = A @ (B[:, obs[t + 1]] * beta[t + 1])
return beta
def viterbi(obs, pi0, A, B):
delta = np.log(pi0 * B[:, obs[0]])
pointers = []
for o in obs[1:]:
scores = delta[:, None] + np.log(A) # scores[i, j]: best path ending i, then i -> j
pointers.append(scores.argmax(axis=0))
delta = scores.max(axis=0) + np.log(B[:, o])
path = [int(delta.argmax())]
for p in reversed(pointers):
path.append(int(p[path[-1]]))
return path[::-1], np.exp(delta.max())
obs = [0, 1, 1] # Low, High, High
alpha = forward(obs, pi0, A, B)
print('forward messages:\n', alpha)
print('filtered P(Worn):', (alpha[:, 1] / alpha.sum(axis=1)).round(3), ' P(readings) =', round(alpha[-1].sum(), 5))
gamma = alpha * backward(obs, A, B); gamma /= gamma.sum(axis=1, keepdims=True)
print('smoothed P(Worn) (using all three readings):', gamma[:, 1].round(3))
path, p = viterbi(obs, pi0, A, B)
print('Viterbi path:', ['OK' if s == 0 else 'Worn' for s in path], f' probability {p:.4f}')forward messages:
[[0.72 0.03 ]
[0.1299 0.0703]
[0.0241 0.0559]]
filtered P(Worn): [0.04 0.351 0.699] P(readings) = 0.07996
smoothed P(Worn) (using all three readings): [0.169 0.594 0.699]
Viterbi path: ['OK', 'Worn', 'Worn'] probability 0.0335
Smoothing uses the future readings too (the backward messages): knowing that readings 2 and 3 were high raises the probability that the machine was already worn at step 2, from the filtered 0.351 to the smoothed value above.
Learning the model: Baum–Welch¶
We simulate 5,000 readings from the true machine, start from a wrong guess, and let Baum–Welch (EM) re-estimate the transition and emission tables from the readings alone. Messages are normalised at each step to avoid numerical underflow.
def simulate_hmm(T, pi0, A, B, rng):
states, readings = [rng.choice(2, p=pi0)], []
for t in range(T):
if t: states.append(rng.choice(2, p=A[states[-1]]))
readings.append(rng.choice(2, p=B[states[-1]]))
return np.array(states), np.array(readings)
def baum_welch(obs, pi0, A, B, iterations=100):
obs = np.asarray(obs)
for _ in range(iterations):
T, n = len(obs), len(pi0)
alpha, c = np.zeros((T, n)), np.zeros(T)
alpha[0] = pi0 * B[:, obs[0]]; c[0] = alpha[0].sum(); alpha[0] /= c[0]
for t in range(1, T):
alpha[t] = (alpha[t - 1] @ A) * B[:, obs[t]]; c[t] = alpha[t].sum(); alpha[t] /= c[t]
beta = np.ones((T, n))
for t in range(T - 2, -1, -1):
beta[t] = A @ (B[:, obs[t + 1]] * beta[t + 1]) / c[t + 1]
gamma = alpha * beta # P(X_t | all readings)
xi = alpha[:-1, :, None] * A[None] * (B[:, obs[1:]].T * beta[1:])[:, None, :] / c[1:, None, None]
pi0 = gamma[0]
A = xi.sum(0) / gamma[:-1].sum(0)[:, None] # expected transitions
B = np.stack([gamma[obs == k].sum(0) for k in range(B.shape[1])], axis=1) / gamma.sum(0)[:, None]
return pi0, A, B, np.log(c).sum()
rng = np.random.default_rng(2)
true_states, readings = simulate_hmm(5000, pi0, A, B, rng)
guess_A = np.array([[0.7, 0.3], [0.3, 0.7]]); guess_B = np.array([[0.6, 0.4], [0.4, 0.6]])
_, A_hat, B_hat, loglik = baum_welch(readings, np.array([0.5, 0.5]), guess_A, guess_B)
print('true A:\n', A, '\nlearnt A:\n', A_hat)
print('true B:\n', B, '\nlearnt B:\n', B_hat)true A:
[[0.9 0.1 ]
[0.05 0.95]]
learnt A:
[[0.8967 0.1033]
[0.0488 0.9512]]
true B:
[[0.8 0.2]
[0.3 0.7]]
learnt B:
[[0.7997 0.2003]
[0.2989 0.7011]]
From readings alone, without ever seeing the machine’s true state, Baum–Welch recovers transition and emission tables close to the true ones. (EM finds a local optimum, and the two hidden states could have come out in swapped order; the starting guess, which makes state 1 emit High more often, settles that.)
Summary¶
| Section | Result |
|---|---|
| 1 | enumeration reproduces the chapter: , and explaining away |
| 2 | variable elimination gives the same answers, and stays fast as a chain grows while enumeration doubles |
| 3 | rejection sampling, likelihood weighting and Gibbs sampling approach the exact value |
| 4 | counting recovers well-observed CPT entries; rare combinations fall back on the smoothing prior |
| 5 | forward, backward and Viterbi reproduce the chapter’s HMM example; Baum–Welch learns the machine’s tables from readings alone |