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.
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
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.
N full equals 2 to the n, minus 1.
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.
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.
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.
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.
Chapter 1
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.
Call the variables x1 to xn, in an order with parents first. Call the parents of xi Pa(xi).
P of x-one through x-n equals the product over i of P of x-i given the parents of x-i.
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.
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.
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.
Chapter 2
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".
| Sprinkler | Rain | P(Wet grass) |
|---|---|---|
| on | yes | 0.99 |
| on | no | 0.90 |
| off | yes | 0.90 |
| off | no | 0.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.
N net equals the sum over i of 2 to the k-i.
For each node, double 1 once per parent, k-i times. Add the results over all nodes. That sum is N net.
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.
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.
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.
Chapter 3
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.
X is independent of Y given Z exactly when P of X given Y and Z equals P of X given Z.
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.
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.
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.
Chapter 4
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:
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.
Chapter 5
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.
a times d is less than b times c.
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.
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.
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).
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.
Pick a story and drag the "both" and "neither" rows. A third bar below the second means explained away.
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.
Chapter 6
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.
P of Q given e equals alpha times the sum over h of P of Q, e and h.
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.
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.
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).
Chapter 7
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.
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.
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.
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.
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.
Chapter 8
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.
w equals the product over the evidence nodes j of P of e-j given the parents of node j.
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.
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.
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.
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).
Chapter 9
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.
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.
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.
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.
Chapter 10
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.
| Failure | Symptom | Check that names it |
|---|---|---|
| Full table | 2n rows, most never seen | count empty rows |
| A loop in the graph | no order puts parents first | try a topological order |
| Too many parents | a 1,024-row table | 2k per node; use a noisy-OR |
| A hard 0 in a table | some evidence becomes impossible or certain | search the tables for 0 and 1 |
| Missing shared cause | answers drift from the records | P(X | Y) against P(X) in the data |
| Conditioning on a collider | a 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 order | out of memory | the largest factor built |
| Rejection on rare evidence | answers from 2 samples | the kept count |
| Weights on late evidence | 1,000 samples act like 3 | effective sample size |
| A guessed rare entry | teams disagree by more than a factor of 2 | move 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.
| Number | Value | Where it comes from |
|---|---|---|
| Full table, lawn and alarm | 15, 31 | 24 − 1, 25 − 1 |
| Network, lawn and alarm | 9, 10 | 1 + 2 + 2 + 4; 1 + 1 + 4 + 2 + 2 |
| 20 variables, at most 3 parents | 160 vs 1,048,575 | 20 × 23; 220 − 1 |
| Largest row: cloudy, no sprinkler, rain, wet | 0.324 | 0.5 × 0.9 × 0.8 × 0.9 |
| P(Rain | wet), P(Sprinkler | wet) | 0.708, 0.430 | 0.4581 and 0.2781 over 0.6471 |
| Explaining away on the lawn | 0.430 → 0.194 | P(S | W) to P(S | W, R) |
| Watching against forcing | 0.30, 0.50 | P(R | S), P(R | do(S)) |
| Alarm: burglar after the alarm, then the earthquake | 0.374 → 0.0033 | a × d = 0.00095 < b × c = 0.273 |
| P(Burglary | John and Mary call) | 0.284 | enumeration over 32 rows |
| Star of 10: largest factor | 4 vs 1,024 | leaves first; hub first, 210 |
| Rejection on the alarm, 1,000 samples | 2 kept | P(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.
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.