Bayesian Networks

Four yes-or-no facts about a lawn need a table of 15 numbers. A Bayesian network stores 9 and answers the same questions. Wet grass lifts the chance of rain from 0.50 to 0.71. Learn that the sprinkler ran, and rain falls to 0.32.

Pick what you saw, or tap a node to set it true, false or unknown. Watch every other bar move from its warm tick. Then we build, piece by piece, the graph, its small tables, the independences it promises, and three ways to answer a question.

You need Bayes' rule and the idea that probabilities add up to 1. We build the rest from zero.

Ask the lawn

Illustrative textbook numbers: the sprinkler network of Russell and Norvig, Artificial Intelligence: A Modern Approach (3rd edition, chapter 14), not measured weather. Every bar is exact: the page adds up all 16 rows of the full table.

Chapter 0

The Table That Explodes

Count the numbers a full table needs, and watch them double with every new fact

You look out at the lawn. Four facts matter: cloud, sprinkler, rain and wet grass.

Each fact is yes or no. You want to ask things like "the grass is wet, so did it rain?"

One complete answer is a table with a row for every combination of the four facts. Four yes-or-no facts make 2 × 2 × 2 × 2 = 16 rows. Each row holds a probability, and the 16 add up to 1. This table is the full joint distribution. Any question about the lawn is a sum of some of its rows.

Call the number of yes-or-no variables n. Each new variable doubles the rows. The last row is 1 minus all the others, so it costs nothing to store.

Say it aloud

N full equals 2 to the n, minus 1.

Nfull
N full how many numbers the full table needs: each one stored, and each one estimated from data.
2n
2 to the n the number of rows. n is the number of yes-or-no variables: 4 for the lawn.
− 1
minus 1 the rows must add up to 1, so the last row follows from the rest.
In plain words

Double 1 once for each of the n variables to count the rows. Take away 1 for the row that the sum fixes. The result is N full.

With numbers

The lawn: n = 4, so N full = 16 − 1 = 15. A model with n = 20 causes and symptoms needs 1,048,575 numbers. At n = 40, about 1.1 trillion.

Count the numbers

Each bar is a count on a log scale: one step right is 10 times more. Add variables and watch the grey full-table bar run past the yellow memory line. Then cap how many parents each variable may have.

20
3

Exact counts. The network bound is n × 2k numbers for n variables with at most k parents each (Chapter 2 derives it). The memory line assumes 8 bytes per number and 16 GB = 16 × 109 bytes, so 2 billion numbers.

A Bayesian network stores a small table for each variable instead. Each table looks only at a few other variables, the ones that directly influence it. With 20 variables and at most 3 influences each, that is at most 160 numbers, about 6,550 times fewer than 1,048,575. The rest of this lesson shows when that loses nothing.

Symptom: a model fitted from records gives probability 0 to every combination it has not seen.

Measure: count the empty rows. With 1,000 records and 1,048,576 rows, at least 99.9% of the rows have no data.

Fix: estimate many small tables instead of one big one. Each small table gets most of the records.

The road

  1. Factor: arrows, and any row as a product of small numbers.
  2. Tables: one small table per node, and how many numbers it needs.
  3. Independence: what stops mattering once you know something.
  4. Junctions: chain, fork and collider decide whether news can travel.
  5. Explaining away: one cause found makes another less likely.
  6. Enumerate: answer any question by adding rows.
  7. Eliminate: sum early and keep the tables small.
  8. Sample: answer by simulation, and see rare evidence break it.
  9. Showcase: the burglar alarm, every knob.
  10. Field guide: the failure table, the numbers and the code.
A model has 30 yes-or-no variables. Why not store the full table?

Chapter 1

Each Variable Listens to Its Parents

Draw the arrows, then multiply four small numbers to get any row of the table

Draw each variable as a box, a node. Draw an arrow from A to B when A directly influences B. Clouds make rain likely and make you skip the sprinkler. Rain and the sprinkler both wet the grass. So the arrows run Cloudy to Sprinkler, Cloudy to Rain, Sprinkler to Wet, and Rain to Wet.

The nodes with arrows into a node are its parents. The graph may have no loop: you can never follow the arrows back to where you started. A graph of arrows with no loop is a directed acyclic graph, or DAG.

Now the payoff. The chain rule splits any joint probability: put the variables in an order, and condition each one on all the ones before it. That is always true. Put parents before children. The network then claims that each node, given its parents, ignores every other earlier node. So each long condition shrinks to the parents.

P(C and S and R and W) = P(C) × P(S | C) × P(R | C, S) × P(W | C, S, R)
the chain rule: no assumption yet
= P(C) × P(S | C) × P(R | C) × P(W | S, R)
the graph: Rain listens only to Cloudy, and Wet only to Sprinkler and Rain

Call the variables x1 to xn, in an order with parents first. Call the parents of xi Pa(xi).

Say it aloud

P of x-one through x-n equals the product over i of P of x-i given the parents of x-i.

P(x1, …, xn)
P of x-one through x-n one row of the full table: the chance of one setting of every variable.
Πi
the product over i multiply one factor for each variable, from 1 to n.
P(xi | Pa(xi))
P of x-i given its parents one entry of node i's own small table.
Pa(xi)
the parents of x-i the nodes with arrows into x-i. Cloudy has none; Wet has Sprinkler and Rain.
In plain words

To get one row, visit each variable x-i. Look up its own table at its value and its parents' values. Multiply the n numbers you found. The product is the row's probability.

With numbers

Cloudy, sprinkler off, rain, wet grass: P(C) = 0.5, P(no S | C) = 0.9, P(R | C) = 0.8, P(W | no S, R) = 0.9. The row is 0.5 × 0.9 × 0.8 × 0.9 = 0.324, the largest of the 16 rows.

Build one row

Set each fact yes or no. Each box shows the one entry its table gives for your choice. The four entries multiply into one row; the strip below shows all 16 rows, yours in full warm.

Illustrative textbook tables (the hero's). The strip lists rows in binary order, Cloudy first.

Symptom: a graph with a loop, such as Rain → Wet → Rain. The product no longer defines a distribution.

Measure: try to list the nodes so every arrow points forward. If no order works, there is a loop.

Fix: unroll feedback over time: Rain today → Wet today → Rain tomorrow. That chain of copies is a dynamic network, the shape of the Bayes filter.

In the lawn network, which factor does Wet grass add to every row?

Chapter 2

One Small Table per Node

Count the free numbers in each table, then change one and watch the network's beliefs follow

Each node stores a conditional probability table, or CPT: the chance the node is true, for each setting of its parents. Cloudy has no parents, so its table is one number, P(C) = 0.5. Sprinkler has one parent, so it has two rows: 0.1 when cloudy, 0.5 when clear. The "false" chance is 1 minus the "true" chance, so we store only "true".

SprinklerRainP(Wet grass)
onyes0.99
onno0.90
offyes0.90
offno0.00

Wet grass has two parents, so its table has four rows. Call the number of parents of node i ki. With yes-or-no variables, node i has 2ki rows and one free number per row.

Say it aloud

N net equals the sum over i of 2 to the k-i.

Nnet
N net the free numbers the whole network stores.
Σi
the sum over i add one term for each node.
2ki
2 to the k-i the rows in node i's table. k-i is its number of parents: 0 for Cloudy, 2 for Wet.
In plain words

For each node, double 1 once per parent, k-i times. Add the results over all nodes. That sum is N net.

With numbers

The lawn: Cloudy 20 = 1, Sprinkler 21 = 2, Rain 2, Wet 22 = 4. N net = 9, against 15 for the full table. The burglar alarm of Chapter 5 has five nodes: 1 + 1 + 4 + 2 + 2 = 10, against 31.

Where do the numbers come from? From an expert, or from counts. P(W | sprinkler on, rain) is the share of sprinkler-and-rain days that had wet grass. Each table needs counts only for its own few columns, so the same records go much further.

Edit one table

Pick a node. Its rows appear as sliders. Each box shows that node's chance before any evidence (warm), with a yellow tick at the textbook value.

0.99
0.90
0.90
0.00

Exact: the page multiplies your tables into all 16 rows and adds them. Illustrative numbers.

Symptom: a node with 10 parents needs 210 = 1,024 rows, and most never appear in the data.

Measure: compute 2k for each node; a large one is the node to fix.

Fix: a noisy-OR. Each parent that is on causes the effect alone with its own chance, and the causes fail independently. The effect is absent only if every cause fails, so 10 parents need 10 numbers, plus 1 for a leak (causes outside the graph).

The lawn's Wet table is a noisy-OR with no leak. Sprinkler and rain each wet the grass with chance 0.9. Both fail together with chance 0.1 × 0.1 = 0.01, so both on gives 0.99, as the table says.

A yes-or-no node has 3 yes-or-no parents. How many free numbers does its table need?

Chapter 3

What Stops Mattering Once You Know

Compare two bars for each question and see which facts become irrelevant

Does the sprinkler tell you about rain? In this network, yes. A running sprinkler hints at a clear day, and clear days rarely bring rain. P(R | S) = 0.30, but P(R | no S) = 0.59.

Now say you know it is cloudy. The sprinkler has nothing left to tell you: rain is 0.80 either way. The link ran only through Cloudy, and you have pinned Cloudy down.

This is conditional independence. Call the thing you ask about X, a fact you might learn Y, and what you already know Z.

Say it aloud

X is independent of Y given Z exactly when P of X given Y and Z equals P of X given Z.

X
X the variable you ask about: here Rain.
⊥
is independent of learning one does not change your belief in the other.
Y
Y a fact you might learn: here Sprinkler.
| Z
given Z what you already know: here Cloudy. Z can be empty.
⇔
exactly when each side implies the other.
P(X | Y, Z)
P of X given Y and Z your belief in X if you learn Y on top of Z.
P(X | Z)
P of X given Z your belief in X from Z alone.
In plain words

Fix what you know, Z. Compute your belief in X with Y added, for each value of Y. If every value of Y leaves the number where Z alone put it, X and Y are independent given Z.

With numbers

X = Rain, Y = Sprinkler, Z = cloudy: P(R | S, C) = 0.8 and P(R | C) = 0.8. Equal, so independent. With Z empty: P(R | S) = 0.30 against P(R) = 0.50. Not equal, so dependent.

Does learning Y change X?

Pick a question. Blue boxes are what you already know; the dashed blue box is Y, the fact you might learn; the purple box is X. The two bars are X's chance if Y turns out yes or no. Equal bars mean independent.

Exact sums over the hero's tables. "Force" sets the sprinkler by a timer and cuts the arrow from Cloudy, as Pearl's do() does.

The network makes one such promise per node, the local Markov property. Given its parents, a node is independent of every node that does not descend from it. Wet grass, given Sprinkler and Rain, ignores Cloudy: 0.99 either way.

Dependence is not cause. Put the sprinkler on a timer, and rain stays at 0.50. Forcing cuts the arrow from Cloudy, so the sprinkler no longer carries news about clouds. Judea Pearl writes this P(R | do(S)): watching gives 0.30, forcing gives 0.50.

Symptom: a model treats Sprinkler and Rain as independent, and its answers drift from the records.

Measure: compare P(R | S) with P(R) in the records: 0.30 against 0.50.

Fix: add the shared cause, Cloudy, as a node. Then the independence holds given it.

P(X | Y, Z) = 0.42 and P(X | Z) = 0.42, for every value of Y. What follows?

Chapter 4

Three Junctions Decide Every Path

Observe the middle of a chain, a fork and a collider, and watch the path close or open

Can news travel from one node to another? Follow each path between them, ignoring which way the arrows point. Every node in the middle of a path sits in one of three junctions:

  1. A chain, A → B → C, like Cloudy → Rain → Wet. B passes news along. Knowing B blocks it.
  2. A fork, A ← B → C, like Sprinkler ← Cloudy → Rain. B is a shared cause. Knowing B blocks it.
  3. A collider, A → B ← C, like Sprinkler → Wet ← Rain. B is a shared effect. It blocks on its own. Knowing B, or any descendant of B, opens it.

Open or block the path

Pick a junction, then observe the middle node. Blue pulses mean news can travel; a yellow bar marks a blocked path. The bars are the last node's chance if the first is yes or no.

Illustrative toys. Chain: P(C) = 0.5, P(R | C) = 0.8 or 0.2, P(W | R) = 0.9 or 0.1. Fork: the hero's Cloudy, Sprinkler and Rain tables. Collider: P(S) = 0.3 and P(R) = 0.5, independent, with the hero's Wet table.

In numbers: along the chain, learning Cloudy moves Wet from 0.26 to 0.74; once you know Rain, Wet sits at 0.90 either way. Through the collider, Sprinkler and Rain start independent at 0.50 and 0.50. Once you see wet grass, rain is 0.52 if the sprinkler ran and 1.00 if it did not.

Put the junctions together and you get d-separation. X and Y are d-separated by a set Z when something blocks every path between them. A chain or fork node in Z blocks a path. So does a collider outside Z with no descendant in Z. Then the network guarantees X ⊥ Y | Z, whatever numbers fill the tables.

The chain, the reversed chain and the fork make the same promise: A and C are dependent, and independent given B. Records alone cannot tell them apart. Only the collider differs. So a program that learns a graph from data can find the colliders, but some arrows stay unsure. The graphs it cannot separate form a Markov equivalence class.

Symptom: an analysis "controls for" a variable and finds a link that was not there.

Measure: check whether that variable is a collider, or a descendant of one, on the path.

Fix: do not condition on a shared effect unless you mean to.

The graph is A → B → C ← D. You know C. Are A and D independent?

Chapter 5

Explaining Away

Hear an alarm, learn of an earthquake, and watch the burglar fade

A house alarm rings for two reasons: a burglar or an earthquake. Both are rare and independent: P(B) = 0.001 and P(E) = 0.002. The alarm rings with chance 0.95 if both happen, 0.94 for a burglar alone, 0.29 for an earthquake alone, and 0.001 for neither.

The alarm rings. The chance of a burglar jumps from 0.001 to 0.37. Then the radio reports an earthquake, and the burglar drops to 0.0033. The earthquake explains away the alarm: once you find one cause, you need the other less.

Finding one cause does not always lower the other. Name the alarm's four rows. Call the chance of the effect with both causes a and with the first cause only b. Call it c with the second cause only, and d with neither.

Say it aloud

a times d is less than b times c.

a
a P(effect | both causes): 0.95 for the alarm.
d
d P(effect | neither cause): 0.001, a false alarm.
b
b P(effect | first cause only): 0.94, a burglar alone.
c
c P(effect | second cause only): 0.29, an earthquake alone.
<
is less than when it holds, learning one cause lowers the other. When it flips, learning one cause raises the other.
In plain words

Multiply the "both" row a by the "neither" row d. Multiply the two "one cause only" rows b and c. If a times d is smaller, finding one cause lowers the other. The priors of the causes do not enter.

With numbers

The alarm: a × d = 0.95 × 0.001 = 0.00095, and b × c = 0.94 × 0.29 = 0.273. So explaining away holds. A lamp that needs both a switch and power has a = 0.9, b = c = 0.1, d = 0.05: a × d = 0.045 is more than 0.01. Seeing it lit and learning the power is on raises the switch from 0.69 to 0.79.

Where the rule comes from

Write the first cause's prior as p, the second's as q, and compare odds, which skip the divide. The second cause known: the odds of the first are p × a over (1 − p) × c. The second cause unknown: they are p × (q a + (1 − q) b) over (1 − p) × (q c + (1 − q) d).

a / c < (q a + (1 − q) b) / (q c + (1 − q) d)
⇔ a (q c + (1 − q) d) < c (q a + (1 − q) b)
⇔ (1 − q) a d < (1 − q) b c  ⇔  a d < b c

The terms with q × a × c cancel, and p never appears. This assumes the two causes are independent before the effect. Wellman and Henrion (1993) study this condition in depth.

Find one cause, watch the other

Pick a story and drag the "both" and "neither" rows. A third bar below the second means explained away.

0.95
0.001

Alarm: the numbers of Russell and Norvig (3rd edition, chapter 14), with b = 0.94 and c = 0.29 fixed. Lamp: illustrative, priors 0.3 and 0.3, b = c = 0.1 fixed. Exact arithmetic.

Symptom: in hospital records, two unrelated diseases look negatively linked.

Measure: ask how someone chose the records. Admission is a shared effect of both diseases, and every record has it.

Fix: compare in the whole population, or model admission as a collider you condition on. Joseph Berkson described this trap in 1946.

A symptom has two independent causes. You see the symptom, then confirm cause 1. When does cause 2 become less likely?

Chapter 6

Ask Any Question by Adding Rows

Keep the rows that match what you saw, add them up, then divide

The network can rebuild any row of the full table, so it can answer any question the table could. Split the variables into three groups. The query Q is what you ask about. The evidence e is what you saw. The hidden variables h are the rest.

Say it aloud

P of Q given e equals alpha times the sum over h of P of Q, e and h.

P(Q | e)
P of Q given e the answer: the query's chance after the evidence.
α
alpha 1 over P(e). It makes the answers for every value of Q add up to 1.
Σh
the sum over h add one term for each setting of the hidden variables.
P(Q, e, h)
P of Q, e and h one row of the full table, built as the product of Chapter 1.
In plain words

For each value of the query Q, add every row that agrees with the evidence e, over all settings of the hidden h. Add those sums to get P(e). Divide each sum by it: that divide is alpha.

With numbers

P(Rain | wet). The hidden variables are Cloudy and Sprinkler. Rain rows: 0.045 + 0.0495 + 0.324 + 0.0396 = 0.4581. No-rain rows: 0 + 0.18 + 0 + 0.009 = 0.189. P(wet) = 0.6471, so P(R | W) = 0.4581 / 0.6471 = 0.708.

Add the matching rows

Each line is one row of the full table: four squares (filled means yes) and its probability in warm. Press Step to strike the rows the evidence rules out, add the rest, then divide.

Exact arithmetic on the hero's tables; the rows are the products of Chapter 1.

Enumeration touches every row that matches. Each row costs n − 1 multiplications. Here that is 8 rows × 3 = 24. With 30 hidden variables, it is a billion rows for every question.

Symptom: a query that took a millisecond at 10 nodes takes hours at 40.

Measure: rows visited = 2 to the number of hidden variables.

Fix: push the sums inside the product (Chapter 7) or sample (Chapter 8).

The sprinkler rows with wet grass add to 0.2781, and P(wet) = 0.6471. What is P(Sprinkler | wet)?

Chapter 7

Sum Early, Keep the Tables Small

Move each sum next to the only tables that mention its variable, then pick the order

Enumeration repeats work. In the sum for P(rain, wet), the part P(c) P(r | c) does not mention the sprinkler. Yet enumeration computes it again for both sprinkler values. Pull it out of the sprinkler's sum. Write lower-case letters for values: c for a value of Cloudy, s, r and w for the others.

Say it aloud

P of r and w equals the sum over c of P of c times P of r given c, times the sum over s of P of s given c times P of w given s and r.

P(r, w)
P of r and w the chance of one rain value together with the wet grass you saw.
Σc
the sum over c add the cloudy and the clear case.
P(c) P(r | c)
P of c times P of r given c the tables that do not mention the sprinkler: outside its sum.
Σs
the sum over s add sprinkler on and off.
Σs P(s | c) P(w | s, r)
the inner sum a new 4-entry table over c and r. Call it f(c, r), a factor.
In plain words

First sum out the sprinkler s: for each c and r, add P(s | c) P(w | s, r) over both values of s. That builds f(c, r). Then sum out the cloud c: multiply P(c) P(r | c) f(c, r) and add over c.

With numbers

f(cloudy, rain) = 0.1 × 0.99 + 0.9 × 0.9 = 0.909; f(cloudy, no rain) = 0.09; f(clear, rain) = 0.945; f(clear, no rain) = 0.45. Then P(rain, wet) = 0.5 × 0.8 × 0.909 + 0.5 × 0.2 × 0.945 = 0.4581, as enumeration found, with 16 multiplications instead of 24.

This is variable elimination. Pick a hidden variable. Multiply the factors that mention it. Sum it out. Repeat until only the query is left, then normalise.

Eliminate, one variable at a time

Each chip is a factor with its number of entries. Press Step: the chips that mention the next variable merge into one purple chip without that variable. Try the star both ways.

Lawn: P(Rain | wet), exact values. Star: a hub H with 10 leaves L1 to L10, query P(L1 | L10); sizes only, which do not depend on the numbers.

The order matters. In the star, a hub has 10 children; ask about leaf 1, given leaf 10. Sum out the other 8 leaves first: each sums to a table of ones, and the largest table has 4 entries. Sum out the hub first: you multiply 11 tables into one with 210 = 1,024 entries.

Exact inference in a general network is NP-hard (Cooper, 1990), and so is finding the best order. On a tree you can answer every query at once by passing small tables along the edges both ways. That is belief propagation; on a chain of hidden states it is the forward-backward algorithm of a hidden Markov model.

Symptom: elimination runs out of memory on a network of 50 nodes.

Measure: the largest factor the order builds: 2 to the number of variables in it.

Fix: a greedy order: eliminate the variable with the fewest neighbours first. If the largest factor is still too big, sample.

Why does summing out the star's hub first cost so much?

Chapter 8

Answer by Simulation

Roll the network forward thousands of times and count, then see why rare evidence breaks it

Some networks are too tangled for exact sums. Then simulate. Visit the nodes parents first, and draw each one with a weighted coin from its table, given the values drawn so far. One pass gives one imagined day: one sample.

To ask P(rain | wet), keep only the samples where the grass came out wet, and count the share with rain. This is rejection sampling. Of 1,000 samples, about 647 come out wet. Our seeded run keeps 656 and answers 0.710, close to the exact 0.708.

Rejection wastes every sample that misses the evidence. In the alarm network, John and Mary both call with chance 0.0021, so about 2 samples in 1,000 survive. Our seeded run keeps 2, and both had a burglar: an answer of 1.00 against the exact 0.284.

Likelihood weighting keeps every sample. It does not draw the evidence nodes. It writes in what you saw, and weighs the sample by how likely that was. Call the value seen at evidence node j ej, and the sample's weight w.

Say it aloud

w equals the product over the evidence nodes j of P of e-j given the parents of node j.

w
w the sample's weight: how much it counts in the final average.
Πj
the product over j multiply one factor for each evidence node.
P(ej | Pa(Ej))
P of e-j given its parents the table entry for the seen value, at this sample's parent values.
ej
e-j the value you saw at evidence node j: here, wet grass is yes.
Pa(Ej)
the parents of node j their values as drawn in this sample.
In plain words

Draw the hidden nodes as before. At each evidence node, write in the seen value e-j and multiply w by its table entry. To answer, divide the total weight of the rainy samples by the total weight of all samples.

With numbers

One sample draws clear, sprinkler on, no rain: w = P(wet | sprinkler on, no rain) = 0.90. Another draws cloudy, sprinkler off, no rain: w = 0. Our seeded run of 1,000 weighted samples answers 0.712.

Sample, then count

The squares are the first 200 samples: filled purple had the query true, hollow purple had it false, and grey ones missed the evidence. Under weighting, a square's size shows its weight. Raise the samples, or switch to the alarm.

1,000

Seeded runs; the first seed gives the numbers in the text. The exact answers come from adding every row.

Weighting has its own failure. In the alarm, most samples draw no alarm, and both calls then weigh 0.05 × 0.01 = 0.0005. The rare samples with an alarm weigh 0.63 and carry almost everything. The effective sample size is the square of the total weight over the sum of the squared weights. Our 1,000 alarm samples count as about 3.

Symptom: the estimate jumps around from one run to the next.

Measure: the kept count under rejection, or the effective sample size under weighting.

Fix: more samples, or a sampler that moves through the evidence, such as Gibbs sampling (MCMC).

Why does rejection sampling fail on P(Burglary | John and Mary call)?

Chapter 9

The Burglar Alarm, Every Knob

Set any evidence on five nodes, compare exact answers with two samplers, and doubt a table

Judea Pearl's story, with the numbers of Russell and Norvig. You are at work. Your neighbour John calls to say your alarm is ringing. John calls 90% of the time it rings, and 5% of the time it does not, when he mistakes the phone for the alarm. Mary calls 70% of the time it rings and 1% of the time it does not. The network stores 10 numbers; the full table needs 31.

Run the alarm

Tap a node to set it yes, no or unknown. Warm ticks show each node before any evidence. Purple bars show the chosen method's answer; under a sampler, the yellow tick is the exact answer.

1,000
0.010

Russell and Norvig's alarm tables (3rd edition, chapter 14): P(B) = 0.001, P(E) = 0.002; the alarm 0.95, 0.94, 0.29, 0.001; John 0.90 or 0.05; Mary 0.70 or 0.01. Each sampler uses a fixed seed; "New samples" changes it.

Things to try. Each sentence is a number the device gives.

  1. John and Mary both call: burglary 0.284, earthquake 0.176, alarm 0.761. Russell and Norvig give the same 0.284.
  2. Only John calls: 0.016. Only Mary: 0.056. Mary's call carries more news, because she rarely calls by mistake.
  3. Both call, and the radio reports an earthquake: burglary falls to 0.0033. Explaining away, two levels down.
  4. Set the alarm itself to yes: burglary is 0.374, and John's call no longer changes it. The alarm blocks the chain.
  5. Both call, under rejection with 1,000 samples: 2 samples survive. Weighting keeps all 1,000, but they count as about 3.

Now doubt a table. Mary's false-call rate, 0.01, is a guess. At 0.001 the answer to "both call" is 0.362; at 0.05 it is 0.145. A network is only as right as its smallest, rarest numbers.

Symptom: two teams with the same graph report 0.36 and 0.15 for the same question.

Measure: move each table entry over its plausible range and record how far the answer moves.

Fix: spend data on the entries the answer is most sensitive to, here the false-call rates.

You know the alarm rang. Why does John's call no longer change the chance of a burglary?

Chapter 10

Field Guide

Keep the failure table, the numbers and the code in one place

A Bayesian network is a graph with no loops plus one small table per node. The full table is the product of those tables, and every missing arrow is a promise of independence. Read the promises with the three junctions: chains and forks close when you know the middle, colliders open. Answer questions exactly by adding rows, faster by summing early in a good order, and roughly by sampling.

FailureSymptomCheck that names it
Full table2n rows, most never seencount empty rows
A loop in the graphno order puts parents firsttry a topological order
Too many parentsa 1,024-row table2k per node; use a noisy-OR
A hard 0 in a tablesome evidence becomes impossible or certainsearch the tables for 0 and 1
Missing shared causeanswers drift from the recordsP(X | Y) against P(X) in the data
Conditioning on a collidera link appears after "controlling"is it a shared effect on the path?
Watching read as forcing"a timer will change the weather"P(R | S) against P(R | do(S))
Bad elimination orderout of memorythe largest factor built
Rejection on rare evidenceanswers from 2 samplesthe kept count
Weights on late evidence1,000 samples act like 3effective sample size
A guessed rare entryteams disagree by more than a factor of 2move each entry, watch the answer
python
import itertools
import numpy as np

# Each node: (parents, P(node is true | parent values)), parents listed first
LAWN = {
    "C": ((), lambda: 0.5),
    "S": (("C",), lambda c: 0.1 if c else 0.5),
    "R": (("C",), lambda c: 0.8 if c else 0.2),
    "W": (("S", "R"), lambda s, r: 0.99 if s and r else 0.9 if s or r else 0.0),
}

def row_prob(net, x):
    """One row of the full table: the product of one CPT entry per node."""
    p = 1.0
    for v, (par, cpt) in net.items():
        q = cpt(*(x[u] for u in par))
        p *= q if x[v] else 1 - q
    return p

def enumerate_query(net, query, evidence):
    """P(query is true | evidence): add the matching rows, then normalise."""
    names = list(net)
    num = den = 0.0
    for vals in itertools.product([0, 1], repeat=len(names)):
        x = dict(zip(names, vals))
        if any(x[k] != v for k, v in evidence.items()):
            continue
        p = row_prob(net, x)
        den += p
        num += p * x[query]
    return num / den

def likelihood_weighting(net, query, evidence, n, seed=0):
    """Draw hidden nodes parents first; weigh each sample by its evidence."""
    rng = np.random.default_rng(seed)
    total = hit = 0.0
    for _ in range(n):
        x, w = {}, 1.0
        for v, (par, cpt) in net.items():
            q = cpt(*(x[u] for u in par))
            if v in evidence:
                x[v] = evidence[v]
                w *= q if x[v] else 1 - q
            else:
                x[v] = int(rng.random() < q)
        total += w
        hit += w * x[query]
    return hit / total

print(round(row_prob(LAWN, {"C": 1, "S": 0, "R": 1, "W": 1}), 3))  # 0.324
print(round(enumerate_query(LAWN, "R", {"W": 1}), 3))               # 0.708
print(round(enumerate_query(LAWN, "R", {"W": 1, "S": 1}), 3))       # 0.32
print(round(enumerate_query(LAWN, "S", {"W": 1, "R": 1}), 3))       # 0.194
print(round(likelihood_weighting(LAWN, "R", {"W": 1}, 100_000), 3))  # 0.705

We ran every line above with numpy; the comments are its output.

NumberValueWhere it comes from
Full table, lawn and alarm15, 3124 − 1, 25 − 1
Network, lawn and alarm9, 101 + 2 + 2 + 4; 1 + 1 + 4 + 2 + 2
20 variables, at most 3 parents160 vs 1,048,57520 × 23; 220 − 1
Largest row: cloudy, no sprinkler, rain, wet0.3240.5 × 0.9 × 0.8 × 0.9
P(Rain | wet), P(Sprinkler | wet)0.708, 0.4300.4581 and 0.2781 over 0.6471
Explaining away on the lawn0.430 → 0.194P(S | W) to P(S | W, R)
Watching against forcing0.30, 0.50P(R | S), P(R | do(S))
Alarm: burglar after the alarm, then the earthquake0.374 → 0.0033a × d = 0.00095 < b × c = 0.273
P(Burglary | John and Mary call)0.284enumeration over 32 rows
Star of 10: largest factor4 vs 1,024leaves first; hub first, 210
Rejection on the alarm, 1,000 samples2 keptP(both call) = 0.0021

Where it sits. A Bayes filter is a network unrolled over time, and a hidden Markov model is the same chain with discrete states. Make every table a linear Gaussian and the chain becomes the Kalman filter. Undirected cousins, the factor graphs of robot mapping, carry the same products of small factors.

Keep going

Read next

The habit. Before you trust a link between two facts, find every path between them. Ask which nodes you know, and whether any of them is a shared effect.
A survey of restaurants still open after five years finds that good food and a good location are negatively linked. What should you check first?

Now teach it: press Present or Teach and explain why wet grass makes rain likely, and why the sprinkler then makes it less likely. Then go back to the lawn, choose "Wet, it rained", and predict the sprinkler's bar before you look.

microBayesNet · Reasoning Under Uncertainty with Graphs
Previous: Bayes Filter · Back to Gleams