Causation, Confounding & Simpson's Paradox
After this lesson, you will be able to:
- Distinguish the three explanations for a correlation (X causes Y, Y causes X, Z causes both) and say what randomisation removes
- Work through a Simpson's paradox table from counts, and decide whether the pooled or the grouped table answers your question
- Simulate a confounder and show with a partial correlation that the link vanishes once you compare like with like
- Explain how selection bias and survivorship create a correlation, how shortcuts and observational data mislead a model, and which audits expose them
Before you start
#Spurious Correlation and Confounders
Here is a confounder in a simulation. All numbers are synthetic. Let temperature Z drive both ice-cream sales X and sunburn cases Y over 500 days:
ice = 40 × temp + noiseburn = 3 × temp + noiseiceappears nowhere in the formula forburn. By construction, ice cream does not cause sunburn.
residual computes the leftovers.Running the simulation (seed 7) gives:
| quantity | value |
|---|---|
| r(temp, ice) | 0.928 |
| r(temp, burn) | 0.854 |
| r(ice, burn) | 0.784 |
| r(ice, burn) restricted to days between 24 and 26 degrees (102 days) | −0.032 |
| partial correlation (temperature regressed out of both) | −0.043 |
| r(ice, burn) after randomly shuffling which day gets which ice-cream figure | 0.032 |
A strong 0.784 correlation between ice cream and sunburn, with zero causal link. Hold temperature fixed (look at days of similar temperature) and the correlation vanishes. This is the signature of confounding: the association lives in the pooled data and disappears once you compare like with like.
The partial correlation has a closed form in the three plain correlations, which you can read straight off the table: (0.784 minus 0.928 times 0.854), divided by the square root of (1 minus 0.928 squared) times (1 minus 0.854 squared), is about −0.04 (−0.043 with the unrounded values). Open the derivation to see where it comes from.
#Correlation vs Causation: Three Explanations
When X and Y are correlated, at least one of these must be true (or several together):
- X causes Y. Studying more raises scores.
- Y causes X. Reverse causation. People with higher scores feel confident and study more, or sicker patients are given more medication so medication correlates with sickness.
- Z causes both. A common cause. Temperature raises both ice-cream sales and sunburn.
(A fourth, chance, is handled by sample size and the inference tools of the next lessons.) A correlation alone cannot tell the three apart. The scatter plot looks the same under all three.
The simulation shows the effect: shuffling the ice-cream column, which mimics assigning it at random, drops r from 0.784 to 0.032. The confounder's link is cut.
Here is the same idea in symbols, for the case where Z, X and Y are categories (for example severity, treatment, recovery). The derivation uses the Simpson table from the next section, where severity Z is split half mild and half severe.
| tool | breaks which explanation | what it needs |
|---|---|---|
| randomisation (an A/B test) | Z causes both, and Y causes X | the ability to assign X |
| conditioning on a measured confounder | Z causes both | you measured Z, and Z is truly a common cause |
| time order (X before Y) | Y causes X | careful timing data |
| domain knowledge and mechanism | all of them | a credible causal story |
When you cannot randomise (you cannot assign people to smoke), you need the observational methods in the Causal Inference Basics lesson, and each one rests on assumptions you must argue for, since the data cannot verify them.
#Simpson's Paradox: When the Pooled Table Lies
| mild cases | severe cases | pooled | |
|---|---|---|---|
| Treatment A | 270 / 300 | 20 / 50 | 290 / 350 |
| Treatment B | 46 / 50 | 135 / 300 | 181 / 350 |
#Step 1: Compare inside the mild group
A recovered 270 of 300, which is 270 / 300 = 90.0 percent. B recovered 46 of 50, which is 46 / 50 = 92.0 percent.
#Step 2: Compare inside the severe group
A recovered 20 of 50, which is 20 / 50 = 40.0 percent. B recovered 135 of 300, which is 135 / 300 = 45.0 percent.
#Step 3: Pool the groups
A: (270 + 20) / (300 + 50) = 290 / 350 = 82.9 percent. B: (46 + 135) / (50 + 300) = 181 / 350 = 51.7 percent.
#Step 4: Find the reason
Look at who got which treatment. A treated 300 mild and only 50 severe patients. B treated 50 mild and 300 severe. A was handed mostly easy cases, which recover at high rates whatever you do. The pooled A rate is a weighted average, 300/350 = 86 percent weight on the easy group, while B's weights are 14 percent easy and 86 percent hard. The comparison was never like for like.
Why can a pooled rate point the opposite way from every subgroup, and exactly when? The next derivation answers both with one line of algebra.
Drag the group-mix slider to change how many of A's patients are mild, and watch the pooled bars: find the mix where A's pooled lead flips to B, while B stays ahead inside both groups.
#Which table do you trust?
The arithmetic cannot tell you. The causal story does.
- Severity was decided before treatment and influences both who got which treatment and the outcome. Severity is a confounder. Use the grouped (or standardised) table. B is better.
- Suppose instead the grouping variable is something the treatment itself changes, for example "developed a complication", where treatment A causes complications that then lower recovery. Then splitting by that variable throws away part of the very effect you want to measure, and the pooled table is the honest one.
Same numbers, opposite advice. What changes is the direction of the arrows between treatment, the grouping variable and the outcome. That is why "just control for everything" is not a safe default.
Ask one question about the grouping variable. Did it exist before the treatment, or did the treatment cause it? If it came before, it is a confounder, so compare inside the groups. If the treatment caused it, it sits on the treatment's own path, so compare the pooled totals.
In the synthetic table, treatment A looks better pooled but worse in both subgroups. What most directly produces this reversal?
#Simpson's paradox in a model's accuracy
pivot lays out accuracy by segment, and groupby(...).sum() pools the counts.Per segment, B wins both: 0.96 against 0.95 on easy requests and 0.40 against 0.30 on hard ones. Pooled, A wins by a mile, 885 / 1000 = 0.885 against 456 / 1000 = 0.456, only because A was handed mostly easy requests. On the same 50/50 mix, B scores 0.680 and A 0.625. Shipping A because of the pooled number would pick the worse model. The fix is the habit from the ML section below: report accuracy by segment, on the same segment mix, before declaring a model better.
#Selection Bias and Survivorship
Sometimes the correlation is created by how the data was collected, not by nature. Two common forms:
- Survivorship bias. You only see the units that survived a filter. If you study only funds that still exist after ten years, average returns look better than the full set of funds that were ever launched, because the poor performers closed and vanished from your data. If you study only the bullet holes on bombers that returned, you miss that planes hit elsewhere never came back.
- Selection into the dataset. Suppose a hiring model is trained only on people who were hired. Among hired people, test score and interview score can look negatively correlated even if they are positively correlated in the applicant pool, because anyone who was weak on both was rejected. Selecting on a variable that both depend on (here, being hired) manufactures a correlation. This is the collider effect described in the confounder section, arriving through the data pipeline: being hired is an effect of both scores, and you looked only at the hired.
A quick synthetic check you can run: draw 100,000 pairs of independent standard normals X and Y (seed 0, r = 0.002), keep only the rows where X + Y is above 1, and the kept rows (24,041 of them) show r of −0.61. Nothing about X and Y changed. Only the filter did.
That −0.61 is not an accident of the seed. For independent normals it can be derived exactly, and the derivation shows why any filter on the sum bends the correlation negative.
Drag the threshold line (or use the slider) to raise and lower the bar c, and watch the correlation of all points stay near 0 while the kept points show a clear negative correlation that matches the exact value printed beside it.
#Connection to ML: Shortcuts and Observational Data
Almost all ML training data is observational, and almost all ML objectives reward correlation. A model minimises prediction error, and any feature that helps predict, causal or not, is fair game.
- Correlated features are not causal features. A feature with high |r| to the label is useful for prediction in the data you have. It is a safe lever only if it causes the label. A hospital risk model may learn that patients who got an intensive-care bed are higher risk, which is true in the data and useless as advice ("withhold the bed").
- Spurious shortcuts. A classifier can learn the background instead of the object if the two are confounded in training (for example, camels photographed on sand, cows on grass). It scores well on a test set drawn from the same collection, then fails when the background changes. The shortcut is a confounder that lives in the dataset, and the standard test split does not expose it because the test set has the same confounder.
- Distribution shift is a broken correlation. If a feature predicted the label only through a common cause, the prediction fails when that cause changes. Features whose relationship to the label is stable under change are the ones to prefer, which is one motivation for causal and invariant representation learning.
- Observational data can mislead a model about interventions. Predicting what will happen if we do X (a recommendation, a price change) is a different question from predicting what we will see given X. Models trained on logged data inherit the logging policy's confounding, which is why recommender teams run randomised experiments and use counterfactual evaluation.
- Simpson's paradox appears in metrics. An overall accuracy that rises while accuracy falls inside every user segment is entirely possible when the segment mix shifts, as the pandas table above showed (A pooled 0.885 against B 0.456, yet B better in both segments). Always report metrics by segment before declaring a model better.
For the causal tools that go beyond spotting the problem, see Causal Inference Basics in the classical ML track.
Run the confounder and the Simpson table yourself in one cell.
rng.normal(0, 80, n) to rng.normal(0, 800, n) so ice cream becomes much noisier. The pooled r drops, but the within-band r is still near zero. Noise weakens a confounded correlation without changing the fact that it is confounded.#Try It Yourself
Two short exercises put this lesson's main numbers in your hands: a Simpson reversal from counts, and a partial correlation that makes a confounded link disappear. The pearson helper is given. Fill in the TODOs, then compare with the solution.
Tests: Plan Q beats Plan P in both the young and old groups (94 percent vs 90 percent, 45 percent vs 20 percent), Plan P beats Plan Q pooled (76.0 percent vs 54.8 percent), and with a 50/50 mix Q gets 69.5 percent against P's 55.0 percent. The cafes and pharmacies correlation is about 0.706 and the partial correlation with city size removed is about -0.001.
When you run the solution you should see, in the first part, Q beats P inside both groups (94.0 against 90.0 percent young, 45.0 against 20.0 percent old), yet P wins pooled, 76.0 against 54.8 percent, because P treated 200 young and only 50 old patients. At a 50/50 mix Q scores 69.5 percent and P 55.0 percent. In the second part, cafes and pharmacies correlate at 0.706 although neither causes the other, and with city size regressed out the partial correlation is −0.001.
#Key Takeaways
- A confounder can manufacture a strong correlation — in the synthetic simulation ice cream and sunburn correlate at 0.784 with no causal link, yet inside a 24 to 26 degree band r is −0.032 and the partial correlation with temperature removed is −0.043
- Three explanations, and randomisation removes two — X causes Y, Y causes X, Z causes both; assigning X at random (r from 0.784 to 0.032 in the simulation) cuts the common-cause and reverse-cause routes
- Simpson's paradox is unequal group mix — in the synthetic table B wins mild (92.0 vs 90.0) and severe (45.0 vs 40.0), yet A wins pooled (82.9 vs 51.7); whether to trust the pooled or grouped table depends on the causal story, not the arithmetic
- Metrics can reverse too — in the synthetic model table A pools at 0.885 against B's 0.456 while B wins both segments (0.96 vs 0.95 and 0.40 vs 0.30), so compare models by segment
- Selection can manufacture one too — 100,000 independent pairs have r = 0.002, and keeping only the 24,041 rows where X + Y exceeds 1 gives r = −0.61
- Models learn correlation, so audit the data — ask who is missing, test on data where the suspected shortcut is broken, and report metrics per segment
#Quick Check
In a hospital, patients who receive a drug have worse outcomes than those who do not. Sicker patients were more likely to be given the drug. What is the best description?