All lessons in Machine Learning Engineering: Reliable Predictive Models
Graphical Models and Conditional Structure
Factor a joint distribution and distinguish conditional independence from causal claims.
35 minutes · Free lesson
What you will learn
- Factor a joint distribution over late-delivery variables with the chain rule, apply stated conditional independences, and count the free parameters saved.
- Compute marginal and conditional late probabilities from the factors of a small directed graph and verify a claimed conditional independence numerically.
- Explain why a conditional independence found in data or in a fitted model is a statement about a distribution, not evidence of a causal mechanism.
A dispatch model answers one question: given what the carrier knows when a van leaves, how likely is this parcel to be late? Behind that single number sits a joint distribution over everything the carrier records. Graphical models are a bookkeeping language for that joint distribution. They state which variables still carry information about which others once a third variable is known, and they let you count how many numbers a model actually needs. This optional lesson builds the language from four binary variables and then uses it to keep two ideas apart that are easy to blur: a conditional independence, which you can check with arithmetic, and a causal claim, which you cannot.
The joint table and the chain rule
Let W be the weekend flag, L a heavy-load indicator (1 when dispatch_load is above the carrier's heavy threshold), X a bad-weather indicator from weather_risk, and Y the late flag. All four are binary in this hand fixture. The full joint distribution P(W, L, X, Y) is a table with 2 × 2 × 2 × 2 = 16 cells, and because the cells sum to one it has 15 free numbers. Every operational question, such as the late rate on weekends or the late rate for heavy vans in bad weather, is a sum or ratio of those cells.
The chain rule writes any joint as a product of conditionals in any chosen variable order. In the order W, L, X, Y it reads P(W, L, X, Y) = P(W) × P(L given W) × P(X given W, L) × P(Y given W, L, X). Count the free numbers: 1 for P(W), 2 for P(L given W) because W takes two values, 4 for P(X given W, L), and 8 for P(Y given W, L, X). The total is 15, the same as the full table. The chain rule reorganises; it saves nothing by itself.
Savings appear only when you assert conditional independences.
Suppose the carrier's analyst asserts two things. First, weather does not depend on weekend or load, so X is independent of the pair (W, L). Second, lateness depends on the weekend only through the load it creates, so Y is independent of W given L and X. The product collapses to P(W) × P(L given W) × P(X) × P(Y given L, X), with 1 + 2 + 1 + 4 = 8 free numbers instead of 15.
A directed graphical model, also called a Bayesian network, draws exactly this: one node per variable, an arrow from W to L, arrows from L and from X into Y, and no other arrows. Each node receives one factor, the probability of that node given its parents. The missing arrow from W to Y is the assumption that Y is independent of W given L and X. The graph is a compact list of which factors you need. It does not say that an arrow is a physical cause.
The fixture values used below are:
| Factor | Values |
|---|---|
| P(W = 1) | 0.3 |
| P(L = 1 given W = 1), P(L = 1 given W = 0) | 0.6, 0.3 |
| P(X = 1) | 0.2 |
| P(Y = 1 given L = 0, X = 0) | 0.05 |
| P(Y = 1 given L = 1, X = 0) | 0.20 |
| P(Y = 1 given L = 0, X = 1) | 0.15 |
| P(Y = 1 given L = 1, X = 1) | 0.50 |
Worked example
Late rate by weekend, and checking the missing arrow
- The late rate on a weekend is the sum over L and X of P(L given W = 1) times P(X) times P(Y = 1 given L, X). The four terms are 0.4 × 0.8 × 0.05 = 0.016, 0.6 × 0.8 × 0.20 = 0.096, 0.4 × 0.2 × 0.15 = 0.012, and 0.6 × 0.2 × 0.50 = 0.060. The sum is 0.184.
- On a weekday P(L = 1 given W = 0) is 0.3, so the terms become 0.7 × 0.8 × 0.05 = 0.028, 0.3 × 0.8 × 0.20 = 0.048, 0.7 × 0.2 × 0.15 = 0.021, and 0.3 × 0.2 × 0.50 = 0.030. The sum is 0.127.
- The overall late rate is 0.3 × 0.184 + 0.7 × 0.127 = 0.0552 + 0.0889 = 0.1441.
- Now condition on load. For a heavy van on a weekend, P(Y = 1 given W = 1, L = 1) sums over X only: 0.8 × 0.20 + 0.2 × 0.50 = 0.16 + 0.10 = 0.26. For a heavy van on a weekday the factor P(Y given L, X) does not mention W, so the result is the same 0.26.
- Interpretation: weekends raise the late rate from 12.7 percent to 18.4 percent in this fixture, entirely because weekends make heavy loads more common. Once the load is known, the weekend flag adds nothing. That is the numerical content of the missing arrow, and it holds only because the fixture was built that way.
Reading independences off the graph
Three local patterns cover every path in a directed graph. In a chain, A points to B and B points to C: the path can transmit association from A to C, and conditioning on B blocks it. The weekend-load-late path is a chain, which is why conditioning on L removed the weekend effect above. In a fork, B points to both A and C: A and C are associated through their shared parent, and conditioning on B blocks the path. In a collider, both A and C point into B: A and C are not associated through this path when nothing is conditioned, but conditioning on B, or on anything downstream of B, opens the path and can create an association; particular parameter values may still cancel it.
Y is a collider for L and X. Load and weather are independent in the dispatch population by construction, yet among late parcels they are not.
Worked example
Explaining away inside the late pile
- First get P(L = 1) in the population: 0.3 × 0.6 + 0.7 × 0.3 = 0.18 + 0.21 = 0.39, so P(L = 0) is 0.61. Because X is independent of L, P(X = 1 given L = 1) and P(X = 1 given L = 0) are both 0.2.
- The joint P(L, X, Y = 1) has four cells: L = 0, X = 0 gives 0.61 × 0.8 × 0.05 = 0.0244; L = 1, X = 0 gives 0.39 × 0.8 × 0.20 = 0.0624; L = 0, X = 1 gives 0.61 × 0.2 × 0.15 = 0.0183; L = 1, X = 1 gives 0.39 × 0.2 × 0.50 = 0.0390. The cells sum to 0.1441, matching the marginal late rate from the first example, which confirms the arithmetic.
- Among late parcels with a heavy load, the bad-weather share is 0.0390 divided by (0.0624 + 0.0390) = 0.0390 / 0.1014 = 0.3846.
- Among late parcels with a light load it is 0.0183 divided by (0.0244 + 0.0183) = 0.0183 / 0.0427 = 0.4286.
- Interpretation: within the late pile, a heavy load makes bad weather less likely, 0.385 against 0.429. Nothing about weather changed. Selecting on the common effect Y created the association, because a heavy load already explains the lateness and so weather is less needed as an explanation. Any analysis that starts from outcome-selected rows, such as a complaint log, inherits this distortion.
What the graph does not say
The same list of conditional independences is usually compatible with several graphs. For the three-node chain W, L, Y, the graphs W to L to Y, Y to L to W, and L pointing to both W and Y all imply exactly one independence, Y independent of W given L. Observational data that confirms this independence cannot choose among them. Only collider structures leave a distinctive fingerprint, and even then unmeasured variables can mimic it. So a graph learned or confirmed from the dispatch table encodes which conditionals you need; it is not a proof that heavy loads cause lateness.
The same caution applies to a fitted model. If a forest leans on dispatch_load and barely on load_proxy, that is a statement about how the forest divided reliance between two correlated columns, not that one of them is the operative cause. If the workbook's generator makes load_proxy a noisy copy of dispatch_load, then Y is independent of the proxy given the true load in this generator, because the proxy noise is independent of all other draws, and either column can carry the model's reliance depending on noise and tree randomness. This is why the workbook's grouped permutation shuffles the two columns together.
Naive Bayes is itself a graphical model: Y is the single parent of every feature, which asserts that all features are mutually conditionally independent given the outcome. That is stronger than each pair being independent. In the fixture above it fails, as the computed unequal conditional weather shares show; arrow direction alone would not establish that failure, yet naive Bayes may still rank parcels usefully because ranking tolerates errors in the probability scale that calibration does not.
Two recurring mistakes
Treating a missing arrow as a finding rather than an assumption. The 8-parameter factorisation was asserted by the analyst, then checked against a fixture that satisfied it by construction. On real dispatch data a missing arrow is a hypothesis that finite samples can only fail to reject with limited power.
Testing independence on a subset chosen by outcome. Example two shows that two independent variables look dependent once you restrict to late parcels. The same trap appears more quietly when rows are filtered on anything downstream of the outcome, such as parcels that triggered a customer refund.
Investigation
Download the Machine learning investigation workbook, unzip it, create a Python 3.12 environment, install requirements.txt, and run python ml_workbook.py --development-only --output development-results so no final test scores are produced while you explore. Load synthetic-parcels.csv with NumPy and retain only the row indices in report.json under manifest.split.train. On those training rows compute the late rate for weekend equal to 1 and 0. Then bin dispatch_load into quartiles and recompute the weekend late rate inside each bin. If the weekend-late association shrinks sharply inside bins, the data behave like the chain in the fixture; if it persists, possible explanations include other open paths, coarse binning, or sampling error; the observation does not establish a direct causal path. Repeat the check within weather_risk strata. Separately, compute the correlation between dispatch_load and load_proxy and compare the individual and grouped entries under grouped_permutation in report.json. Remember that the synthetic rows are independent and identically distributed with no timestamps or depots, that these checks describe the forest regardless of which model was selected, and that a small sample difference in rates is not a demonstration of independence or dependence.
Exercise
A separate hand fixture adds a binary noise code N (the workbook noise_code is continuous) that has no arrows to or from any other node, giving five binary variables W, L, X, N, Y under the graph with arrows W to L, L to Y, X to Y. How many free parameters does the full joint table have, how many does the factored model have, and how many are saved?
Check your answer
The full table has 2 to the power 5 = 32 cells and 31 free parameters. The factored model needs P(W) with 1 number, P(L given W) with 2, P(X) with 1, P(N) with 1, and P(Y given L, X) with 4, for 9 in total. The saving is 31 minus 9 = 22 parameters. The noise code costs one parameter to describe and contributes nothing to predicting Y, because no path connects it to Y.
Exercise
Using the fixture values, compute P(Y = 1 given W = 1, X = 1) and P(Y = 1 given W = 0, X = 1). Does conditioning on weather make the weekend flag and the late flag independent?
Check your answer
With X fixed at 1, sum over L only. For W = 1: 0.4 × 0.15 + 0.6 × 0.50 = 0.06 + 0.30 = 0.36. For W = 0: 0.7 × 0.15 + 0.3 × 0.50 = 0.105 + 0.15 = 0.255. The two rates differ, so weekend and lateness remain dependent given weather. Conditioning on X blocks nothing on the path from W through L to Y; only conditioning on L, the middle of the chain, blocks it.
Exercise
An analyst pulls 1,000 late parcels from the complaint log: 270 had heavy load and bad weather, 430 heavy load and good weather, 130 light load and bad weather, 170 light load and good weather. The analyst concludes that heavy loads protect against bad weather. Diagnose the reasoning and state what data would be needed instead.
Check your answer
Among heavy-load late parcels the bad-weather share is 270 / 700 = 0.386; among light-load late parcels it is 130 / 300 = 0.433. The difference is real within the late pile, but the pile was selected on Y, which is a collider for load and weather. In the fixture, load and weather are independent at dispatch, with bad-weather share 0.2 regardless of load, and conditioning on lateness induces exactly this kind of gap. The claim needs the dispatch-time population, meaning all parcels with their load and weather recorded before the outcome, where the bad-weather share by load group can be compared directly. Even then, equality of shares supports independence only up to sampling error and says nothing about a protective mechanism.
Further reading
Probabilistic Machine Learning: An Introduction — the chapters on directed graphical models and conditional independence, including the chain, fork, and collider patterns.
scikit-learn naive Bayes user guide — read the stated assumption and relate it to the single-parent graph described above.
Summary
A joint distribution over dispatch variables can always be written as a product of conditionals; conditional independence assumptions remove factors and parameters, and a directed graph records which assumptions were made. Chains and forks are blocked by conditioning on the middle node, while colliders are opened by it, which is why outcome-selected subsets manufacture associations. The independences a graph encodes are compatible with several causal stories, so neither a confirmed independence nor a model's reliance pattern establishes a mechanism.
Next action
Run the workbook in development-only mode, compute the weekend late rate inside dispatch-load quartiles using only manifest training rows from synthetic-parcels.csv, and write two sentences on whether the data behave like the chain fixture and what a single sample cannot settle.