---
title: Graphical models
heading: Bayesian networks as factorizations, the parameters they save, conditional independence read from the graph, explaining away, Markov random fields and factor graphs, and exact inference on chains and trees by passing messages
eyebrow: S14 · Lesson 31 · Graphical models
xp: 50
---

::: hook
A joint distribution over 20 binary variables, written as a table, needs over a million numbers, and summing it to answer one question takes as many operations. Most real systems are sparse, though: a sensor depends on the quantity it measures, not on every other sensor. A graphical model draws those dependencies as a graph, and the graph both cuts the number of parameters and tells you which sums can be done locally.
:::

::: play
- A power fault (A) or a sensor fault (B) can each trigger an alarm (noisy-OR: 95% and 90%, with a 0.1% false-alarm leak). The faults are independent a priori.
- The solid curve is the probability of a power fault given the alarm, against its prior; the dashed curve adds that the sensor has been found faulty.
- Finding the sensor fault "explains away" the alarm, and the power fault's probability drops nearly back to its prior: two independent causes become dependent once their common effect is seen.
:::

```sim plot
view: graph
x: a = 0.001..0.5 log
y: p = 0..1
slider: b = 0.001..0.5 = 0.05 log
plot: a*(1 - 0.999*0.05*(1 - b*0.9))/(a*(1 - 0.999*0.05*(1 - b*0.9)) + (1 - a)*(1 - 0.999*(1 - b*0.9))) | label: P(A | alarm)
plot: a*(1 - 0.999*0.05*0.1)/(a*(1 - 0.999*0.05*0.1) + (1 - a)*(1 - 0.999*0.1)) | dashed | label: P(A | alarm, sensor fault)
```

::: predict
## The power fault has prior 1% and the sensor fault 5%. The alarm sounds, and the power fault's probability rises to 17%. Then the sensor is found to be faulty. What is the power fault's probability now?

- [ ] Still about 17%
- [ ] Higher, about 30%: two faults are worse than one
- [x] About 1.1%, nearly back to its prior
- [ ] Zero

::: reveal
The sensor fault alone accounts for the alarm, so the alarm no longer argues for a power fault: P(A | alarm, sensor fault) = 1.1%. The faults were independent before anything was observed, but conditioning on their common effect couples them. That's explaining away, and it's why a graph's arrows matter for reading off independence.
:::
:::

::: nameit
## Bayesian networks

A directed acyclic graph whose nodes are variables states that the joint distribution factorizes as
$$p(x_1, \ldots, x_K) = \prod_k p(x_k \mid \text{pa}_k)$$
where $\text{pa}_k$ are node k's parents. A binary node with m binary parents needs $2^m$ numbers, one probability per parent configuration, so a sparse graph needs far fewer than the $2^K - 1$ of a full table. Naive Bayes (lesson 17) is a class node with every feature as a child; a hidden Markov model (lesson 42) is a chain of hidden states, each with an observed child.

## Reading independence from the graph

Three junctions decide everything. In a **chain** a → c → b and a **fork** a ← c → b, a and b are dependent, but independent given c. In a **collider** a → c ← b, a and b are independent, but become dependent once c, or any descendant of c, is observed: explaining away. **d-separation** applies these rules along every path: two sets of variables are conditionally independent if every path between them is blocked. A node's **Markov blanket**, its parents, children and children's other parents, makes it independent of everything else.

## Markov random fields and factor graphs

An undirected graph writes the joint as a product of nonnegative potentials over its cliques, divided by a normalizing constant Z: natural for pixels in an image or spins in a magnet, where no direction is meaningful. A **factor graph** draws variables and factors as two kinds of node, covering both forms.

## Passing messages

On a tree-shaped graph, marginals come from passing **messages**: each node sums out its own variable and passes the result to its neighbor. On a chain of N variables with K states each, every message is a K × K matrix–vector product, so all marginals cost about $2(N - 1)K^2$ operations instead of the $K^N$ terms of the full sum. This is the forward–backward algorithm of hidden Markov models, and replacing sums by maxima gives the Viterbi algorithm. On graphs with loops the same updates, iterated, give **loopy belief propagation**, inexact in general but the basis of decoding LDPC and turbo codes.
:::

::: example
## Ten binary variables form a chain, each depending only on the one before. How many numbers specify the joint distribution, compared with a full table? And five binary sensors that each depend only on a hidden three-valued state?

::: solution
1. **The chain.** 1 for the first variable and 2 for each of the other nine (one per value of its parent):
   $$1 + 9 \times 2 = 19$$
   against $2^{10} - 1$ = 1023 for a table.
2. **The sensor model.** 2 for the hidden state's distribution and 3 for each sensor (one per state):
   $$2 + 5 \times 3 = 17$$
   against $3 \times 2^5 - 1$ = 95 for the full joint.
3. **Growth.** The gap grows exponentially with the number of variables.

**Answer:** the chain needs 19 numbers against 1023 for a table, and the sensor model 17 against 95.
:::
:::

::: example
## In the sim's alarm model with the default priors (1% and 5%), find the probability of each fault given the alarm.

::: solution
1. **Alarm with a power fault.**
   $$\begin{aligned} &P(\text{alarm} \mid A = 1) \\ &= 1 - 0.999 \times 0.05 \\ &\qquad \times (1 - 0.05 \times 0.9) \\ &= 0.952 \end{aligned}$$
2. **Alarm without one.**
   $$\begin{aligned} &P(\text{alarm} \mid A = 0) \\ &= 1 - 0.999 \times (1 - 0.045) \\ &= 0.046 \end{aligned}$$
3. **Power fault given the alarm.** P(alarm) = 0.0550, so
   $$\begin{aligned} P(A \mid \text{alarm}) &= \frac{0.01 \times 0.952}{0.0550} \\ &= 17\% \end{aligned}$$
4. **Sensor fault given the alarm.** The same calculation gives 82%: the alarm most likely comes from the more common fault.
5. **Explaining away.** Finding the sensor faulty then drops the power fault to 1.1%, as the predict question showed.

**Answer:** given the alarm, the power fault has probability 17% and the sensor fault 82%.
:::
:::

::: example
## A chain of 20 variables with 10 states each. How many terms does the full sum for one marginal have, and how many operations do messages take for all marginals?

::: solution
1. **The full sum.** It has $10^{20}$ terms (strictly $10^{19}$ for one marginal, still hopeless).
2. **Messages.** They pass in both directions along the 19 links, each a 10 × 10 matrix–vector product of about 100 multiply-adds:
   $$2 \times 19 \times 100 = 3800$$
   operations for every marginal at once.
3. **What the structure buys.** The graph's structure turns an exponential sum into a linear one.

**Answer:** the full sum has $10^{20}$ terms, while messages give every marginal in about 3800 operations.
:::
:::

::: check
kind: parts
given: K = 8 | 12 | 20; m = 1 | 2 | 3

## {K} binary variables form a Bayesian network in which every variable but the first {m} has exactly {m} binary parents (the first {m} have none).

::: part
answer: m + (K - m)*2^m
unit: parameters
tolerance: 0

### How many numbers specify it?

::: misses
- [K*2^m] The first m nodes have no parents and need one number each.
- [any] One per root, $2^m$ per node with m parents.
:::
:::

::: part
answer: 2^K - 1
unit: parameters
tolerance: 0

### How many does a full table need?

::: misses
- [2^K] The probabilities sum to 1.
- [any] $2^K - 1$.
:::
:::
:::

::: check
kind: parts
given: N = 5 | 20 | 100; K = 2 | 10 | 50

## A chain of {N} variables with {K} states each.

::: part
answer: 2*(N - 1)*K^2
unit: operations
tolerance: 0

### About how many multiply-adds do forward and backward messages take to give every marginal?

::: misses
- [(N - 1)*K^2] Messages run in both directions.
- [any] Each of the 2(N − 1) messages is a K × K product.
:::
:::

::: part
answer: N*log(K)
tolerance: 0.5%

### How many digits long is the number of terms in the full sum (log₁₀ of $K^N$)?

::: misses
- [any] $N\log_{10}K$.
:::
:::
:::

::: check
kind: parts
given: a = 0.01 | 0.05; b = 0.02 | 0.1; q = 0.9 | 0.99; r = 0.8 | 0.95

## Two independent causes A and B (priors {a} and {b}) each set off an effect E, with probabilities {q} and {r}; nothing else does (deterministic OR otherwise, no leak).

::: part
answer: a*(q + (1 - q)*b*r)/(1 - (1 - a*q)*(1 - b*r))
tolerance: 0.5%

### What is P(A | E)?

::: misses
- [a*q/(a*q + b*r)] That treats the causes as exclusive; both can happen.
- [any] $P(A)P(E|A)/P(E)$ with $P(E|A) = 1 - (1 - q)(1 - b\,r)$ and $P(E) = 1 - (1 - aq)(1 - br)$.
:::
:::

::: part
answer: a*(1 - (1 - q)*(1 - r))/(a*(1 - (1 - q)*(1 - r)) + (1 - a)*r)
tolerance: 0.5%

### What is P(A | E, B)?

::: misses
- [a] Not quite back to the prior: A still makes E slightly more likely.
- [any] Condition on B = 1: $P(E|A, B) = 1 - (1 - q)(1 - r)$, $P(E|\bar A, B) = r$.
:::
:::
:::

::: check
kind: choice

## In the graph rain → wet grass ← sprinkler, which statement is true?

- [ ] Rain and the sprinkler are dependent, but independent given wet grass
- [x] Rain and the sprinkler are independent, but become dependent once wet grass is observed
- [ ] They are dependent whatever is observed
- [ ] They are independent whatever is observed

::: misses
- [1] That's the rule for chains and forks; this is a collider.
- [3] With nothing observed, a collider blocks the path.
- [4] Observing the common effect couples the causes.
:::
:::

::: check
kind: choice

## Which variables make up a node's Markov blanket in a Bayesian network?

- [ ] Its parents only
- [ ] Its parents and children
- [x] Its parents, its children, and its children's other parents
- [ ] Every node connected to it by any path

::: misses
- [1] Children carry information about it too.
- [2] The children's other parents matter through explaining away.
- [4] The blanket is local; it shields the node from the rest.
:::
:::

::: check
kind: parts
given: p = 0.1 | 0.3; s = 0.7 | 0.9; e = 0.05 | 0.2; f = 0.6 | 0.9

## A hidden state x₁ is 1 with probability {p} and persists to x₂ with probability {s} (and from 0 to 1 with probability 1 − {s}). A sensor on x₂ reads 1 with probability {f} when x₂ = 1 and {e} when x₂ = 0; it reads 1.

::: part
answer: p*s + (1 - p)*(1 - s)
tolerance: 0.5%

### What is the message from x₁ to x₂, the prior P(x₂ = 1)?

::: misses
- [p*s] x₂ can also be 1 after x₁ = 0.
- [any] Sum over x₁.
:::
:::

::: part
answer: f*(p*s + (1 - p)*(1 - s))/(f*(p*s + (1 - p)*(1 - s)) + e*(1 - (p*s + (1 - p)*(1 - s))))
tolerance: 0.5%

### What is P(x₂ = 1 | reading)?

::: misses
- [any] Multiply the incoming message by the sensor's likelihood and normalize.
:::
:::
:::

::: check
kind: derivation
vars: a = 0.001..0.5, b = 0.001..0.5, q = 0.5..1, r = 0.5..1

## Causes A and B with priors a and b independently set off E with probabilities q and r; nothing else does.

::: step
answer: 1 - (1 - a*q)*(1 - b*r)

### What is P(E)?
:::

::: step
answer: a*(1 - (1 - q)*(1 - b*r))/(1 - (1 - a*q)*(1 - b*r))

### What is P(A | E)?
:::

::: step
answer: a*(1 - (1 - q)*(1 - r))/(a*(1 - (1 - q)*(1 - r)) + (1 - a)*r)

### What is P(A | E, B)?
:::

::: right
Right. Observing B lowers A's probability: the second cause explains away the first.
:::
:::

::: check
kind: python

## Write `chain_posteriors(p1, T, L)` for a chain of binary states: P(x₁ = 1) = p1, `T[i][j]` = P(next = j | now = i), and `L[t]` = (P(observation t | x = 0), P(observation t | x = 1)). Return P(x_t = 1 | all observations) for every t, by forward and backward messages.

```python starter
def chain_posteriors(p1, T, L):
    return [l[1] / (l[0] + l[1]) for l in L]
```

```python solution
def chain_posteriors(p1, T, L):
    n = len(L)
    a = [[(1 - p1) * L[0][0], p1 * L[0][1]]]
    for t in range(1, n):
        a.append([sum(a[-1][i] * T[i][j] for i in (0, 1)) * L[t][j] for j in (0, 1)])
    b = [[1.0, 1.0] for _ in range(n)]
    for t in range(n - 2, -1, -1):
        b[t] = [sum(T[i][j] * L[t + 1][j] * b[t + 1][j] for j in (0, 1)) for i in (0, 1)]
    return [a[t][1] * b[t][1] / (a[t][0] * b[t][0] + a[t][1] * b[t][1]) for t in range(n)]
```

```python tests
import itertools
T = [[0.95, 0.05], [0.3, 0.7]]
L = [(0.9, 0.3), (0.1, 0.7), (0.1, 0.7), (0.9, 0.3), (0.1, 0.7), (0.9, 0.3)]
post = chain_posteriors(0.1, T, L)
num, Z = [0.0] * 6, 0.0
for path in itertools.product((0, 1), repeat=6):
    p = (0.1 if path[0] else 0.9) * L[0][path[0]]
    for t in range(1, 6):
        p *= T[path[t - 1]][path[t]] * L[t][path[t]]
    Z += p
    for t in range(6):
        num[t] += p * path[t]
assert all(abs(post[t] - num[t] / Z) < 1e-12 for t in range(6)), "Messages match the sum over all 64 paths."
assert abs(post[2] - 0.715841) < 1e-6, "At the second alarm, given all six readings, the fault is 72% likely."
```

::: right
Right. Two passes of messages give every marginal at once, at a cost linear in the chain's length.
:::
:::

::: explain
## Why do two independent causes become dependent once their common effect is observed?

::: model
Before anything is observed, knowing one cause tells you nothing about the other, because they arise separately. Observing the effect says that at least one cause is probably present, which raises both their probabilities. If you then learn that one of them is present, it already accounts for the effect, so the evidence for the other falls back toward its prior; if you learn the first is absent, the second must explain the effect and its probability rises. Either way, information about one cause now changes your belief about the other, so they are dependent given the effect, the collider rule that d-separation encodes.
:::
:::

::: practice
::: check
given: K = 10 | 30; m = 1 | 2
answer: m + (K - m)*2^m
unit: parameters
tolerance: 0

## Parameters: {K} binary nodes, {m} parents each?

::: misses
- [any] m roots plus $2^m$ per other node.
:::
:::

::: check
given: N = 10 | 50; K = 4 | 20
answer: 2*(N - 1)*K^2
unit: operations
tolerance: 0

## Message cost on a chain: N = {N}, K = {K}?

::: misses
- [any] $2(N - 1)K^2$.
:::
:::

::: check
given: p = 0.2 | 0.5; s = 0.8 | 0.95
answer: p*s + (1 - p)*(1 - s)
tolerance: 0.5%

## Message P(x₂ = 1): p = {p}, persistence {s}?

::: misses
- [any] $ps + (1 - p)(1 - s)$.
:::
:::
:::
