ML fundamentals15 / 22

Lesson 15 · Thinking in probabilities

Bayesian networks

The problem

A delivery arrived late. The manager wants to know why. Two things usually cause a late delivery: heavy traffic, or a backlog at the oven. Rain also matters, because rain makes traffic worse.

So there are four yes/no questions about any evening:

  • Did it rain?
  • Was there heavy traffic?
  • Was the oven backed up?
  • Was the delivery late?

The manager only saw the last answer. What's the chance there was traffic? And if she then learns that the oven was backed up, how does that change her answer?

These questions run backwards, from an effect to its causes. This lesson builds a picture that holds everything the shop knows about the four questions. Then it gives a way to answer any question like these from it. Like the last two lessons, it runs on Bayes' rule and counting.

Drawing who influences whom

Start with what the shop knows from experience:

  • It rains on 25% of evenings.
  • Traffic is heavy on 60% of rainy evenings, and on 20% of dry ones.
  • The oven is backed up on 20% of evenings, whatever the weather.
  • A delivery is late exactly when there is heavy traffic, an oven backlog, or both.

The last rule is a simplification. Real lateness is less certain, and a figure below has a "noisy" version too.

Draw each question as a box, and an arrow from each thing to what it directly affects. Rain affects traffic. Traffic and the oven affect lateness. Nothing points at the oven, because the weather doesn't change it.

Rain ▾yes25%no75%Traffic ▾yes30%no70%Oven backlog ▾yes20%no80%Late ▾yes44%no56%
Chance of Late given Traffic and Oven backlog
TrafficOven backlogLate: yesLate: no
yesyes1.000.00
yesno1.000.00
noyes1.000.00
nono0.001.00

Late has 2 parents, so its table has 4 rows.

The four tables hold 8 numbers. The full joint table has 2⁴ = 16 rows.

The bars show each variable’s chance on an evening when nothing is known yet.

The delay network. Each box is a yes/no variable, with bars for its chance of each answer. Tap a name to see its table of chances given its parents (the boxes with arrows into it).

A box with arrows coming into it has parents: the boxes at the other ends of those arrows. Each box stores one small table: its chance of "yes" for every combination of its parents' answers. Traffic's table has two rows, one for rain and one for no rain. Late's table has four rows, one for each combination of traffic and oven.

A graph like this is a Bayesian network. The arrows show which variables influence which directly. The tables say by how much. The arrows never form a loop: you can't follow them round and come back to where you started.

From small tables to every combination

The small tables are enough to work out the chance of any full combination of answers. Multiply one number from each table:

P(rain,traffic,oven,late)=P(rain)×P(traffic∣rain)×P(oven)×P(late∣traffic,oven).P(\text{rain}, \text{traffic}, \text{oven}, \text{late}) = P(\text{rain}) \times P(\text{traffic} \mid \text{rain}) \times P(\text{oven}) \times P(\text{late} \mid \text{traffic}, \text{oven}) .

Read it back: one factor per box, and each box's factor depends only on its own parents. This is a joint probability, built from conditional probabilities.

Worked example

One evening: rain, traffic, no backlog, late

  1. Rain: P(rain)=0.25P(\text{rain}) = 0.25.

The rule for conditional probability explains the product. It says P(A and B)=P(A)×P(B∣A)P(A \text{ and } B) = P(A) \times P(B \mid A). Apply it one box at a time, in arrow order.

Usually P(B∣A)P(B \mid A) would need everything before BB. The network's promise is that each box needs only its parents. For example, the oven ignores rain, so P(oven∣rain)=P(oven)P(\text{oven} \mid \text{rain}) = P(\text{oven}).

Counting the numbers

With four yes/no variables there are 24=162^4 = 16 combinations, so a table of every combination has 16 rows. The network needs fewer numbers: 1 for rain, 2 for traffic, 1 for the oven and 4 for late. That's 8.

8 against 16 is a small saving. Watch what happens as the network grows.

Predict first

A network has 30 yes/no variables, and each has at most 3 parents. About how many rows does a table of every combination need?

Joint: 24 = 16. Network: 4 variables × 22 rows each = 16.

Bar lengths are on a log scale: each step to the right is ten times more. On a normal scale the network’s bar would be invisible.

Rows in one table of every combination, against the numbers a network needs when each variable has at most k parents. Bars use a log scale.

Things to notice:

  • Each extra variable doubles the joint table. Each extra variable adds only a few numbers to the network.
  • More parents make the network's tables bigger. A variable with many parents is expensive, so good networks keep the arrows few.
  • Fewer numbers also means fewer numbers to estimate from data. Each table can be filled in by counting, the same maximum likelihood as in the last two lessons.

Reasoning backwards

The manager saw a late delivery. Working out the chances of the things you didn't see, given the things you did, is called probabilistic inference. The direct way to do it is to list every combination and count.

Start with a smaller network, leaving out rain: Traffic → Late ← Oven. Traffic is heavy on 30% of evenings. (Rain has been averaged out: 0.25×0.6+0.75×0.2=0.30.25 \times 0.6 + 0.75 \times 0.2 = 0.3.)

Worked example

P(traffic | late) by hand

  1. List the combinations where the delivery is late, with their chances:

    TrafficOvenChance
    yesyes0.3×0.2=0.060.3 \times 0.2 = 0.06
    yesno0.3×0.8=0.240.3 \times 0.8 = 0.24
    noyes0.7×0.2=0.140.7 \times 0.2 = 0.14

    The fourth combination, no traffic and no backlog, is never late, so it drops out.

Step 2 added up rows over every value of the oven. Getting the chance of some variables by adding the joint probability over all the values of the others is called marginalisation. The name comes from old paper tables, where these totals were written in the margin.

The full network works the same way, in three moves. Keep the rows that agree with what you saw, and add them up. Then take the share where the thing you're asking about is true.

RainTrafficOvenLateP
····0.48
···yes0.00
··yes·0.00
··yesyes0.12
·yes··0.00
·yes·yes0.12
·yesyes·0.00
·yesyesyes0.03
yes···0.08
yes··yes0.00
yes·yes·0.00
yes·yesyes0.02
yesyes··0.00
yesyes·yes0.12
yesyesyes·0.00
yesyesyesyes0.03
Step 0 of 4

The joint table: every combination of the four variables, with its probability. The 16 numbers add up to 1.

· means no. Highlighted rows had traffic. Rows with probability 0 are combinations the network rules out.

Inference by enumeration on the full network. Step through: cross out rows that disagree with what you saw, add up the rest, and take the share with traffic.

Things to notice:

  • Many rows have probability 0. The strict rule says a delivery with traffic or a backlog is always late, so "traffic, not late" never happens.
  • With rain in the network, the answer is still 0.68. Rain is marginalised: its rows are added together.
  • It's the area picture from Bayes' rule again, with more pieces: the share of the "late" area where there was traffic.

As a formula, with rr and oo running over yes and no:

P(traffic∣late)=∑r, oP(r,traffic,o,late)∑r, t, oP(r,t,o,late).P(\text{traffic} \mid \text{late}) = \frac{\sum_{r,\,o} P(r, \text{traffic}, o, \text{late})}{\sum_{r,\,t,\,o} P(r, t, o, \text{late})} .

The top adds the late rows with traffic. The bottom adds all the late rows. Each P(⋅)P(\cdot) is one product of four table entries.

Explaining away

Now use the whole network. Tap a value to observe it, and watch every other box update.

Rainyes25%no75%Trafficyes30%no70%Oven backlogyes20%no80%Lateyes44%no56%

Tap a value to observe it (✓); tap it again to forget it.

Nothing observed yet.

Rain 25% · Traffic 30% · Oven backlog 20% · Late 44%

Here a delivery is late exactly when there is traffic or an oven backlog.

Tap a value to observe it (✓), and tap it again to forget it. Every box's bars are recomputed by enumeration. The tabs switch between the strict rule for lateness and a noisy one.

Predict first

A delivery was late. Then you learn that the oven was backed up. Does the chance that there was traffic go up, go down, or stay the same?

Nothing known

Stage 0 of 3

An ordinary evening: traffic 30% of the time, an oven backlog 20%.

The thin line across each bar marks its chance before anything was observed.

Explaining away, one observation at a time. The thin line across each bar marks its chance before anything was observed.

Things to notice:

  • Seeing lateness raises both causes: traffic to 68%, the oven to 45%. Rain rises too, from 25% to 39%, because rain makes traffic likelier.
  • Learning about the oven moves traffic, even though no arrow joins them.
  • If the oven turns out to be fine, traffic becomes certain. Something had to cause the late delivery.

When two causes share an effect, seeing the effect makes them compete. Learning that one cause happened makes the other less likely. This is explaining away. People do it without thinking: the grass is wet, you learn the sprinkler was on, and you stop suspecting rain.

The noisy tab keeps the same pattern with softer numbers. There, lateness raises traffic to 66%, and the backlog brings it back to 34%.

Reading independence off the graph

In naive Bayes, the shortcut was conditional independence: two things that are related, but independent once you know a third. A Bayesian network makes these facts visible. Three patterns cover the cases.

A chain, like Rain → Traffic → Late. Rain and lateness are related: rainy evenings are late more often (68% against 36%). But rain only matters through traffic. Once you know whether there was traffic, rain tells you nothing more about lateness.

A shared cause, like naive Bayes: the class points at every word, Complaint → "cold" and Complaint → "late". The words are related, because each hints at the class. Once you know the class, they're independent. Naive Bayes is a small Bayesian network of this shape.

A shared effect, like Traffic → Late ← Oven. This one works the other way round. Traffic and the oven are independent until you see lateness. Seeing the shared effect makes them dependent: that's explaining away.

Rain → Traffic → Late

Different: learning about rain changes the chance of late. Dependent.

Rain only matters to lateness through traffic. Once you know the traffic, rain adds nothing.

Pick a pattern, and choose whether the variable between the pair is known. If the two bars are equal, learning one variable tells you nothing about the other.

Things to notice:

  • In the chain, knowing the traffic makes the two bars equal. The middle of a chain blocks the link.
  • In the shared effect, the bars are equal until the effect is known. Knowing the middle opens the link.
  • In the third tab, rain and the oven are two steps apart. Seeing lateness still links them.

This is why the arrows matter. They say which variables can be left out of each table, and the same arrows say which questions can be answered without looking at everything.

DigressionArrows are not always causesA network can predict well with arrows that point the wrong way. · 2 min

The delay network's arrows run from causes to effects, because that's how the shop thinks about it. But inference only uses the probabilities. A network with Late → Traffic instead of Traffic → Late can describe the same chances, with different tables.

So a Bayesian network fitted to data shows which variables are related, not what causes what. Asking "what happens if we fix the oven?" is a different question from "what do we expect when the oven happens to be fine?". The first needs the arrows to be real causes.

Judea Pearl, who named and developed Bayesian networks, went on to build a theory of exactly that difference. It's the subject of the Causal inference course.

DigressionWhere Bayesian networks come fromPearl named them in 1985 and wrote the book on them in 1988. · 1 min

The computer scientist Judea Pearl used the name "Bayesian networks" in a 1985 conference paper about reasoning from evidence. His 1988 book, Probabilistic Reasoning in Intelligent Systems, made them a standard tool in AI. Earlier expert systems such as MYCIN scored uncertainty with ad hoc "certainty factors". Pearl showed how to use real probabilities and still keep the arithmetic manageable.

He received the Turing Award in 2011 for this work and for his later work on causal reasoning.

In PyTorch

No new library is needed. Each table is a tensor with one axis per variable, and index 0 means "no", 1 means "yes". Broadcasting multiplies the four tables into the full joint table: a 2×2×2×22 \times 2 \times 2 \times 2 tensor with 16 entries.

The joint table by broadcasting
def joint_table(t: dict[str, torch.Tensor]) -> torch.Tensor:
    """P(rain, traffic, oven, late) for all 16 combinations, as a (2, 2, 2, 2) tensor."""
    return (
        t["rain"][:, None, None, None]  # (2, 1, 1, 1)  P(rain)
        * t["traffic"][:, :, None, None]  # (2, 2, 1, 1)  P(traffic | rain)
        * t["oven"][None, None, :, None]  # (1, 1, 2, 1)  P(oven)
        * t["late"][None, :, :, :]  # (1, 2, 2, 2)  P(late | traffic, oven)
    )


tables = delay_tables()
joint = joint_table(tables)  # axes: rain, traffic, oven, late
print(joint.shape, joint.sum().item())  # torch.Size([2, 2, 2, 2]) 1.0

# The same product with einsum: each letter names an axis.
same = torch.einsum("r,rt,o,tol->rtol", tables["rain"], tables["traffic"], tables["oven"], tables["late"])
print(torch.allclose(joint, same))  # True
torch.Size([2, 2, 2, 2]) 1.0
True

What to notice:

  • Each table gets None axes for the variables it doesn't mention, so its axes line up with (rain, traffic, oven, late). The product then has every combination.
  • The 16 entries add up to 1, as a joint table must.
  • torch.einsum does the same product. Its string names each tensor's axes, and the letters after -> are the axes to keep.

Inference is indexing and adding. Indexing with late picks the rows that agree with what you saw (conditioning). .sum(dim=...) adds over the variables you don't care about (marginalisation). Dividing by the total turns the result back into probabilities.

Inference by enumeration
def p_traffic(joint: torch.Tensor, late: int, oven: int | None = None) -> float:
    """P(traffic = yes | late, and oven if given), by enumeration."""
    rows = joint[:, :, :, late]  # condition on late: keep those rows → (rain, traffic, oven)
    if oven is not None:
        rows = rows[:, :, oven]  # condition on oven too → (rain, traffic)
        by_traffic = rows.sum(dim=0)  # marginalise rain → (traffic,)
    else:
        by_traffic = rows.sum(dim=(0, 2))  # marginalise rain and oven → (traffic,)
    return (by_traffic[YES] / by_traffic.sum()).item()  # normalise: divide by P(evidence)


print(round(joint.sum(dim=(0, 1, 2))[YES].item(), 4))  # P(late) = 0.44
print(round(p_traffic(joint, late=YES), 4))  # 0.6818: lateness makes traffic likelier
print(round(p_traffic(joint, late=YES, oven=YES), 4))  # 0.3: the oven explains it away
print(round(p_traffic(joint, late=YES, oven=NO), 4))  # 1.0: something had to cause it
0.44
0.6818
0.3
1.0

These are the lesson's numbers. Lateness happens on 44% of evenings, and seeing it puts traffic at 68%. Traffic falls back to 30% when the oven explains it, and is certain when the oven was fine.

DeeperWhen enumeration is too slow: a glimpse of samplingSimulate many evenings and count. It works for networks too big to list. · 3 min

Enumeration lists every combination. With 30 variables that's a billion rows, and real networks can have hundreds. There are cleverer exact methods that add up in a good order, but for large networks people often switch to sampling.

The simplest version follows the arrows. To simulate one evening, draw rain from its table. Then draw traffic from the row for that rain, the oven from its table, and lateness from the row for that traffic and oven. Repeat 10,000 times. Then keep the late evenings and count how many had traffic.

Simulating evenings
def sample_evenings(t: dict[str, torch.Tensor], n: int, generator: torch.Generator) -> dict[str, torch.Tensor]:
    """Simulate n evenings by drawing each variable after its parents (ancestral sampling)."""
    draw = lambda p_yes: torch.bernoulli(p_yes, generator=generator).long()  # noqa: E731
    rain = draw(t["rain"][YES].expand(n))  # (n,)
    traffic = draw(t["traffic"][rain, YES])  # P(traffic | each evening's rain)
    oven = draw(t["oven"][YES].expand(n))
    late = draw(t["late"][traffic, oven, YES])
    return {"rain": rain, "traffic": traffic, "oven": oven, "late": late}


g = torch.Generator().manual_seed(0)
evenings = sample_evenings(tables, 10_000, g)
was_late = evenings["late"] == YES
print(was_late.sum().item())  # how many of the 10,000 evenings were late (about 4,400)
print(evenings["traffic"][was_late].double().mean().item())  # about 0.68
4384
0.6802007299270073

4,384 of the 10,000 evenings were late, and 68.0% of those had traffic: close to the exact 0.68. This is a Monte Carlo estimate, so more samples give a closer answer.

There's a catch. Every evening that wasn't late is thrown away. If you condition on something rare, almost every sample is wasted. Better sampling methods avoid that, but they're beyond this lesson.

Putting it together

The manager now hears that it rained, and the delivery was late. Was the oven backed up?

  1. The network: Rain → Traffic → Late ← Oven, with the four tables above.
  2. What she saw: rain, and late.
  3. Chance of lateness on a rainy evening: traffic is heavy with chance 0.6, and the oven is backed up with chance 0.2. A delivery is on time only if neither happens: 0.4×0.8=0.320.4 \times 0.8 = 0.32. So P(late∣rain)=0.68P(\text{late} \mid \text{rain}) = 0.68.
  4. Chance of a backlog and lateness, given rain: a backlog always makes the delivery late, so that's 0.20.2.
  5. Divide: P(oven∣rain,late)=0.2/0.68≈0.29P(\text{oven} \mid \text{rain}, \text{late}) = 0.2 / 0.68 \approx 0.29.

Without the rain, a late delivery put the oven at 45%. Rain makes traffic a likelier explanation, so it explains part of the lateness away, and the oven drops to 29%. To check, tap rain "yes" and late "yes" in the figure under "Explaining away".

Common misconceptions

"An arrow means one thing causes the other." An arrow means a direct dependence in the probabilities. Networks are often drawn with causes pointing at effects because that's easy to think about, but the maths doesn't check that the arrows are causes.

"Two variables with no arrow between them are independent." Not always. Rain and lateness have no direct arrow, but they're related through traffic. And traffic and the oven, independent on their own, become dependent once you see lateness.

"Knowing more always makes things more independent." Knowing the middle of a chain or a shared cause breaks the link. Knowing a shared effect creates one.

"A network can only answer questions in the direction of its arrows." Inference works in any direction. The tables are written from causes to effects, but enumeration answers "effect seen, how likely is the cause?" equally well. That's the whole point of the manager's question.

"P(traffic | late) = 0.68 means traffic caused 68% of late deliveries." It's the share of late evenings that had traffic. Some of those also had a backlog, and either would have made the delivery late.

Recap

  • A Bayesian network draws variables as boxes and direct influences as arrows. Each box has a small table: its chances given its parents.
  • The chance of any full combination is the product of one entry from each table.
  • The network needs far fewer numbers than a table of every combination, which doubles with each variable.
  • Probabilistic inference finds the chances of what you didn't see from what you did. Enumeration keeps the matching rows, marginalises the rest, and takes a share.
  • Explaining away: two causes of one seen effect compete, so learning about one changes the other.
  • Chains and shared causes are blocked by knowing the middle; a shared effect is opened by knowing it.
  • PyTorch names in this lesson: tensors as probability tables, broadcasting with None axes, torch.einsum, indexing to condition, .sum(dim=...) to marginalise, and torch.bernoulli with a generator for sampling.