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 22: Probabilistic Graphical Models — Implementation

Open in Colab

We build a small Bayesian-network toolkit from scratch, in plain Python and NumPy, and use it on the chapter’s examples:

  1. A BayesNet class: joint probabilities and inference by enumeration

  2. Variable elimination with factors, and why it is faster

  3. Sampling: rejection, likelihood weighting and Gibbs

  4. Learning the tables from data

  5. Hidden Markov models: forward, backward, Viterbi and Baum–Welch

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 P(node=True∣parents)P(\text{node} = \text{True} \mid \text{parents}).

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 2h2^h combinations of the hh hidden variables: fine here (h=2h = 2 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).

variable elimination: P(b | j, m) = 0.2842

Same answer. The difference shows on a bigger network: a chain X1→X2→⋯→XnX_1 \to X_2 \to \dots \to X_n where each variable copies its parent with probability 0.9. We ask for P(Xn∣X1=True)P(X_n \mid X_1 = \text{True}).

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, 0.5+0.5×0.8n−10.5 + 0.5 \times 0.8^{n-1}, slowly forgets the first variable, just like the RNN memory of Chapter 18.)

3. Sampling

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).

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: P(J∣A)P(J \mid A), 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).

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.

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

SectionResult
1enumeration reproduces the chapter: P(b∣j,m)=0.284P(b \mid j, m) = 0.284, and explaining away
2variable elimination gives the same answers, and stays fast as a chain grows while enumeration doubles
3rejection sampling, likelihood weighting and Gibbs sampling approach the exact value
4counting recovers well-observed CPT entries; rare combinations fall back on the smoothing prior
5forward, backward and Viterbi reproduce the chapter’s HMM example; Baum–Welch learns the machine’s tables from readings alone