Chapter 22: Probabilistic Graphical Models
22.1 Reasoning Under Uncertainty¶
The logic of Chapters 4 and 5 deals in true and false. Real knowledge is rarely that clean: a symptom makes a disease more likely, an alarm probably means a burglar. Probability extends logic to degrees of belief.
A short refresher¶
For random variables and :
| Rule | Formula |
|---|---|
| Conditional probability | |
| Product rule | |
| Marginalisation (sum rule) | |
| Independence | , i.e. |
| Conditional independence | |
| Bayes’ rule |
Bayes’ rule turns what we know (how evidence depends on a hypothesis ) into what we want (how likely is, given ).
Example. A disease affects 1% of people. A test detects it 90% of the time, and gives a false positive in 5% of healthy people. You test positive:
Only 15%: because the disease is rare, most positives are false alarms (Chapter 8 met the same effect as low precision).
Why we need structure¶
A full joint distribution over binary variables needs numbers: about a million for 20 variables, 1030 for 100. It cannot be stored, estimated from data, or understood. Graphical models use independence to describe the same distribution with a handful of small tables.
22.2 Bayesian Networks¶
A Bayesian network is:
a directed acyclic graph whose nodes are random variables and whose arrows mean “directly influences”;
for each node, a conditional probability table (CPT) .
The joint distribution is the product of the local tables:
Example: the burglar alarm¶
A house alarm can be set off by a burglary or by an earthquake; two neighbours, John and Mary, may call when they hear it. (The example is Judea Pearl’s, made famous by Russell and Norvig’s textbook.)
| 0.001 | 0.002 |
| T | T | 0.95 |
| T | F | 0.94 |
| F | T | 0.29 |
| F | F | 0.001 |
| T | 0.90 | 0.70 |
| F | 0.05 | 0.01 |
The network needs numbers, against for the full joint. With 100 variables and at most 3 parents each, it would need at most 800 instead of 1030.
A joint probability is a product of table entries. The probability that the alarm sounds and both neighbours call, with no burglary and no earthquake:
22.3 Independence in a Network¶
The graph tells us which variables are independent, without looking at the numbers. Every path is built from three patterns:
| Pattern | Example | Independent? |
|---|---|---|
| Chain | Burglary → Alarm → JohnCalls | and are dependent, but independent given : once we know the alarm rang, a burglary tells us nothing more about John calling |
| Fork | JohnCalls ← Alarm → MaryCalls | dependent (John’s call makes Mary’s more likely), independent given |
| Collider | Burglary → Alarm ← Earthquake | independent, but dependent given (or a descendant of ) |
The collider is the surprising one: explaining away. Burglaries and earthquakes are unrelated. But if the alarm rang, learning that there was an earthquake makes a burglary much less likely:
The earthquake explains the alarm away. The general rule for reading independences off a graph from these three patterns is called d-separation. A useful consequence: a node is independent of all other nodes given its Markov blanket (its parents, its children, and its children’s other parents).
22.4 Exact Inference¶
Inference answers queries such as : the probability of a query variable given evidence.
Enumeration¶
Sum the joint over the hidden variables (here and ), then normalise:
For true the sum is 0.000592; for false it is 0.001492. Normalising:
Even when both neighbours call, a burglary is only 28% likely: false alarms are far more common than burglaries. (With only John calling it is 1.6%.)
Enumeration is simple, but it sums over every combination of the hidden variables: exponential in their number.
Variable elimination¶
Enumeration repeats the same products many times. Variable elimination computes them once: it treats each table as a factor, and eliminates hidden variables one at a time by multiplying the factors that mention the variable and summing it out. Pushing sums inwards,
the inner sum over produces a small factor that is computed once and reused. On networks shaped like trees (polytrees) this is linear in the size of the network. In general, exact inference is NP-hard: the cost depends on the elimination order and on how densely the network is connected.
22.5 Approximate Inference by Sampling¶
When exact inference is too expensive, we simulate. Draw many samples from the network and count:
Prior (forward) sampling: sample each variable in topological order, given its sampled parents.
Rejection sampling: throw away the samples that disagree with the evidence; count the rest. Wasteful when the evidence is rare: here, only about 2 samples in 1000 have both neighbours calling.
Likelihood weighting: fix the evidence variables instead of sampling them, and give each sample a weight, the probability of the evidence given its sampled parents.
Gibbs sampling (a Markov chain Monte Carlo method): start from any state consistent with the evidence, and repeatedly resample one hidden variable given its Markov blanket. The visited states come, in the long run, from the right distribution.
Here both estimates need tens of thousands of samples. Rejection sampling keeps only about 2 samples in 1000. Likelihood weighting uses every sample, but the evidence sits at the bottom of the network: Burglary is still sampled ignoring it, so almost all the weight comes from the rare samples with a burglary, and it gains little. Likelihood weighting helps most when the evidence is near the top (on causes rather than effects). For a network this small, exact inference is the right tool; sampling earns its keep on networks too large for it.
Source
import numpy as np
import matplotlib.pyplot as plt
PB, PE = 0.001, 0.002
PA = {(1, 1): 0.95, (1, 0): 0.94, (0, 1): 0.29, (0, 0): 0.001}
PJ, PM = {1: 0.90, 0: 0.05}, {1: 0.70, 0: 0.01}
rng = np.random.default_rng(0)
N = 200_000
def rejection(n):
b = rng.random(n) < PB; e = rng.random(n) < PE
a = rng.random(n) < np.vectorize(lambda x, y: PA[(int(x), int(y))])(b, e)
j = rng.random(n) < np.where(a, PJ[1], PJ[0]); m = rng.random(n) < np.where(a, PM[1], PM[0])
keep = j & m
return np.cumsum(b & keep) / np.maximum(np.cumsum(keep), 1), keep.sum()
def likelihood_weighting(n):
b = rng.random(n) < PB; e = rng.random(n) < PE
a = rng.random(n) < np.vectorize(lambda x, y: PA[(int(x), int(y))])(b, e)
w = np.where(a, PJ[1] * PM[1], PJ[0] * PM[0])
return np.cumsum(w * b) / np.cumsum(w)
est_rej, kept = rejection(N)
est_lw = likelihood_weighting(N)
plt.figure(figsize=(8.5, 3.3))
plt.semilogx(np.arange(1, N + 1), est_rej, label=f'rejection sampling (kept {kept} of {N:,} samples)')
plt.semilogx(np.arange(1, N + 1), est_lw, label='likelihood weighting')
plt.axhline(0.284, c='k', ls='--', label='exact: 0.284')
plt.ylim(0, 0.8); plt.xlabel('number of samples'); plt.ylabel('estimate of P(b | j, m)'); plt.legend(fontsize=8)
plt.title('Both estimates approach the exact answer, but slowly'); plt.tight_layout(); plt.show()
22.6 Learning from Data¶
Parameters. With complete data, each CPT entry is a count ratio: . With little data, add a pseudo-count to every cell (Laplace smoothing, as for Naive Bayes in Chapter 8) so that unseen combinations do not get probability 0. With missing values, the EM algorithm (Chapter 13) alternates between filling them in probabilistically and re-estimating.
Structure. Learning the graph itself is harder: search over graphs, scoring each by how well it fits the data with a penalty for complexity (for example the BIC score). Data alone often cannot tell from ; experts usually supply at least part of the structure.
Naive Bayes is a Bayesian network: a class node with an arrow to every feature, and nothing else. Its “naive” assumption is exactly the independence that this graph encodes.
22.7 Hidden Markov Models¶
Many problems are sequences in which the true state is hidden and only noisy observations are seen: the words behind a speech signal, the position of a robot behind its sensor readings, the health of a machine behind its vibrations. A hidden Markov model (HMM) has:
hidden states that follow a Markov chain: transition probabilities ;
observations that depend only on the current state: emission probabilities ;
an initial distribution .
Example: a machine that wears out¶
A machine is OK or Worn; we only measure its vibration, Low or High.
| to OK | to Worn | Low | High | ||
|---|---|---|---|---|---|
| from OK | 0.90 | 0.10 | OK emits | 0.8 | 0.2 |
| from Worn | 0.05 | 0.95 | Worn emits | 0.3 | 0.7 |
It starts OK with probability 0.9. We observe Low, High, High.
Filtering: the forward algorithm¶
Filtering computes , our belief about the current state. The forward message is updated in two steps, predict then weight by the evidence:
| evidence | predict (OK, Worn) | (OK, Worn) | normalised: | |
|---|---|---|---|---|
| 1 | Low | (0.9, 0.1) | 0.04 | |
| 2 | High | 0.35 | ||
| 3 | High | 0.70 |
After two high readings the machine is probably worn (70%). The sum of the last , 0.080, is the probability of the whole observation sequence (the evaluation problem). The cost is , instead of summing over all state sequences.
Decoding: the Viterbi algorithm¶
Sometimes we want the single most likely sequence of hidden states. Viterbi replaces the sum of the forward algorithm by a max, and remembers which predecessor gave the max:
| (OK) | (Worn) | |
|---|---|---|
| 1 | 0.72 | 0.03 |
| 2 | (from OK) | (from OK) |
| 3 | (from OK) | (from Worn) |
The best final state is Worn (0.0335); following the back-pointers: OK → Worn → Worn. The machine probably wore out at the second step.
Learning: Baum–Welch¶
When the transition and emission probabilities are unknown, the Baum–Welch algorithm (EM again) estimates them from observation sequences alone, using the forward and backward messages to compute the expected number of each transition and emission.
Source
pi0 = np.array([0.9, 0.1]); A = np.array([[0.9, 0.1], [0.05, 0.95]]); Bm = np.array([[0.8, 0.2], [0.3, 0.7]])
rng = np.random.default_rng(57); T = 60
x = [rng.choice(2, p=pi0)]
for _ in range(T - 1): x.append(rng.choice(2, p=A[x[-1]]))
e = [rng.choice(2, p=Bm[s]) for s in x]
alpha = pi0 * Bm[:, e[0]]; filt = [alpha[1] / alpha.sum()]
for o in e[1:]:
alpha = (alpha @ A) * Bm[:, o]; alpha /= alpha.sum(); filt.append(alpha[1])
delta = np.log(pi0 * Bm[:, e[0]]); back = []
for o in e[1:]:
cand = delta[:, None] + np.log(A); back.append(cand.argmax(0)); delta = cand.max(0) + np.log(Bm[:, o])
path = [int(delta.argmax())]
for bp in reversed(back): path.append(int(bp[path[-1]]))
path = path[::-1]
fig, ax = plt.subplots(figsize=(10, 3.2))
ax.fill_between(range(T), x, step='mid', alpha=0.2, color='C3', label='true state (1 = Worn)')
ax.plot(filt, 'C0', label='filtered P(Worn | readings so far)')
ax.step(range(T), np.array(path) * 0.96 + 0.02, 'k--', where='mid', label='Viterbi path')
ax.scatter(range(T), np.array(e) * 1.08 - 0.04, marker='|', c=['C2' if v == 0 else 'C1' for v in e], s=60, label='reading (low / high)')
ax.set_xlabel('time'); ax.set_yticks([0, 0.5, 1]); ax.legend(loc='center left', fontsize=8, bbox_to_anchor=(1, 0.5))
ax.set_title('An HMM tracks a hidden state from noisy readings'); plt.tight_layout(); plt.show()
The filtered probability rises and falls with the readings: a single high reading barely moves it, a run of them convinces it that the machine has worn out, and it drops again after the repair; the Viterbi path is a clean, all-or-nothing explanation of the whole sequence. HMMs powered speech recognition for decades, and are still used in bioinformatics (gene finding), finance and fault detection. The same predict–update idea with continuous states and Gaussian noise is the Kalman filter, used in every GPS receiver and aircraft autopilot.
22.8 Markov Random Fields¶
Some relations have no natural direction: neighbouring pixels in an image tend to have the same colour; friends tend to share opinions. A Markov random field (MRF) uses an undirected graph and assigns each clique (fully connected group) a potential , a non-negative score of how compatible its values are:
, the partition function, makes the probabilities sum to 1; it is usually intractable to compute, which makes learning MRFs harder than Bayesian networks. In an MRF, a node is independent of everything else given its neighbours.
Example: image denoising. Each pixel of a binary image is a node, linked to its 4 neighbours and to its observed noisy value. Potentials reward agreement with the neighbours and with the observation. Finding a likely image (here with a simple greedy method, iterated conditional modes) removes much of the noise:
Source
rng = np.random.default_rng(1)
H, W = 60, 90
yy, xx = np.mgrid[:H, :W]
clean = (((xx - 25) ** 2 + (yy - 30) ** 2 < 18 ** 2) | ((xx > 50) & (xx < 82) & (yy > 12) & (yy < 48))).astype(int) * 2 - 1
noisy = np.where(rng.random(clean.shape) < 0.15, -clean, clean)
img = noisy.copy()
for sweep in range(5):
for i in range(H):
for j in range(W):
nb = sum(img[i2, j2] for i2, j2 in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)) if 0 <= i2 < H and 0 <= j2 < W)
img[i, j] = 1 if 1.0 * nb + 1.5 * noisy[i, j] > 0 else -1
fig, axes = plt.subplots(1, 3, figsize=(12, 2.8))
for ax, im, t in zip(axes, [clean, noisy, img], ['original', f'noisy: {np.mean(noisy != clean):.0%} of pixels flipped', f'MRF denoised: {np.mean(img != clean):.1%} wrong']):
ax.imshow(im, cmap='gray'); ax.set_title(t); ax.axis('off')
plt.tight_layout(); plt.show()
Conditional random fields (CRFs) are MRFs conditioned on the input; they were the standard model for labelling sequences (names in text, parts of speech) before deep learning, and are still used on top of neural networks.
22.9 Graphical Models Today¶
| Idea | Where it lives now |
|---|---|
| Bayesian networks | medical and technical diagnosis, risk analysis, spam filters (Naive Bayes) |
| Sequential models | Kalman filters (navigation, tracking), HMMs (genomics, fault detection) |
| Probabilistic programming | languages such as PyMC and Stan: write the generative model as a program, get inference automatically |
| Causal inference | Judea Pearl’s causal graphs: the arrows as causes, to answer “what if we intervene?” (does a drug help?) rather than “what do we observe?” |
| Deep generative models | VAEs (Chapter 13) and diffusion models are graphical models whose factors are neural networks |
Judea Pearl received the 2011 Turing Award for the foundations of probabilistic and causal reasoning.
22.10 Summary¶
Probability extends logic to uncertainty; Bayes’ rule turns into , and base rates matter.
A Bayesian network factorises the joint: , with far fewer numbers.
Chains and forks are blocked by observing the middle node; a collider is opened by it: explaining away.
Exact inference: enumeration, variable elimination (NP-hard in general, linear on polytrees). Approximate: rejection sampling, likelihood weighting, Gibbs sampling.
Parameters are learnt by counting (with smoothing); EM handles missing data.
HMMs: hidden Markov chain + emissions; forward algorithm for filtering and evaluation, Viterbi for the most likely path, Baum–Welch for learning.
MRFs use undirected potentials and a partition function ; causal and probabilistic programming carry these ideas forward.
Exercises¶
Recompute the disease example with a prevalence of 10%. What changes, and why?
How many numbers does the alarm network need if Alarm also had a third parent with two values? And the full joint?
Compute in the alarm network.
In the alarm network, are JohnCalls and MaryCalls independent? And given Alarm? Are Burglary and Earthquake independent given MaryCalls?
Continue the machine HMM with a fourth reading, Low. Compute the filtered .
Run Viterbi on the readings High, High, Low for the machine HMM.
Why does rejection sampling waste most of its samples for , and how does likelihood weighting avoid that?
Further Reading¶
S. Russell, P. Norvig, Artificial Intelligence: A Modern Approach, 4th ed., 2020, Chapters 12–14.
D. Koller, N. Friedman, Probabilistic Graphical Models: Principles and Techniques, MIT Press, 2009.
J. Pearl, D. Mackenzie, The Book of Why, Basic Books, 2018: causal reasoning for a general audience.
L. Rabiner, “A tutorial on hidden Markov models and selected applications in speech recognition”, Proceedings of the IEEE, 1989.
C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 11.