Part 3: Machine learning Lesson 13 of 20 in this part
Cause and effect, an introduction to causal inference
What you will learn. Explain why a plain comparison of treated and untreated groups can mislead, remove the bias by adjusting for a confounder or by randomising, and read a simple causal diagram.
Before this lesson: Measuring models honestly. Already know these? Carry on.
In plain words
A model can learn that two things go together. It cannot, by itself, tell whether one causes the other. Ice-cream sales and drowning both rise in summer, but ice cream does not drown anyone. Heat drives both. That hidden driver is a confounder. Causal questions are the ones businesses care about: does this discount raise sales, does this treatment help patients, does this feature keep users? A plain comparison of the people who got the discount with those who did not can be badly wrong, because the people who got it may differ in other ways. Two honest fixes exist. In a randomised experiment a coin decides who gets the treatment, so no hidden factor can line up with it. When you cannot randomise, you can adjust: compare like with like, within groups of people who are similar on the confounder. A causal diagram draws the arrows you believe in, so you know what to adjust for. Uplift modelling estimates the effect of an action on each person, so you act only where it helps.
Correlation
- Two things move together
- Good enough to predict
Causation
- Changing one changes the other
- Needed to decide what to do
Prediction asks what goes with what. Causal inference asks what would change if we acted.
- RiskA hidden factor, such as how severe a case isIt affects who gets treated
- ProcessMore severe cases get the treatment more oftenTreated and untreated groups differ
- ProblemSevere cases also have different outcomesThe difference gets blamed on the treatment
The confounder drives both the treatment and the outcome, so the comparison is unfair.
Randomise
- A coin decides who is treated
- Groups are alike on everything, measured or not
Adjust
- Compare like with like within groups
- Only fixes confounders you have recorded
Randomising is the strongest. Adjusting only handles the factors you measured.
- InputDraw each variable as a nodeTreatment, outcome and other factors
- ProcessDraw arrows for the effects you believe inFrom cause to effect
- ModelFind factors with arrows into both endsThese are the confounders
- OutputAdjust for them, or randomiseThen the comparison is fair
Draw an arrow from cause to effect. A factor with arrows into both is a confounder.
Real-world example
A hospital compares patients who got a new treatment with those who did not, and finds that the treated patients did worse. The treatment looks harmful. But doctors gave the treatment mainly to the most seriously ill patients, and serious illness is what makes outcomes worse. Severity is the confounder. When the analysts compare treated and untreated patients with the same severity, the treatment helps. A randomised trial would have avoided the problem by deciding treatment with a coin. A marketing team uses the same idea with discounts: if the discount was sent mostly to loyal customers, the raw comparison overstates its effect.
How it works
- Write the question as an effect. Compare the outcome with and without the treatment for the same kind of person.
- Draw the diagram. List the factors that affect both the treatment and the outcome.
- Choose the fix. Randomise if you can. Otherwise compare within groups of the confounder and combine the group effects, weighting each group by its size.
- Check what you assumed. Adjusting only removes the bias from the factors you included. A confounder you did not measure still biases the answer.
- Use it. For each person, an uplift model predicts how much the action changes the outcome, so you contact only those who will respond because of it.
Live simulation
Averages can hide a cause. Simpson's paradox is the clearest example.
The question. How can a treatment that is better in every group look worse overall?
What to watch
- Look at the split view first. Treatment A beats treatment B for easy cases and for hard cases.
- Then look at everyone together. The result changes because A is mostly given hard cases and B mostly easy ones.
- Move the sliders so both treatments get the same mix of cases, and the overall result agrees with the groups.
This simulation needs JavaScript, which is switched off or not loaded. The lists above say what it shows, and the example programs below print the same kind of numbers.
Try this
- Make the mix of cases within five percentage points the same for A and B and see A come out ahead overall.
What this leaves out. Made-up counts for 100 patients per treatment, and one hidden cause (how hard the case is). Real studies have many such causes, some unknown. Randomly assigning treatments, as a trial does, evens out the mix of cases; with data from ordinary practice, extra care is needed before saying a treatment causes an outcome.
Python program that prints the same headline numbers: examples/sim-ai/ai.py.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
200 patients from a repeatable rule. A hidden factor z (1 means a more severe case) raises the outcome by 4 and makes treatment more likely. The treatment adds exactly 2, so the true effect is 2. The program compares treated and untreated in three ways: plainly, adjusted for z, and in a randomised version where a coin decides treatment.
"""Why a plain comparison can mislead: a confounder, an adjustment, and a randomised experiment.
200 patients. A hidden factor z (1 = a more severe case) raises the outcome by 4 and makes treatment more likely.
The treatment itself adds exactly 2 to the outcome, so the true effect is 2. Data come from a repeatable rule.
Run: python causal.py (needs numpy)
"""
import numpy as np
n = 200
i = np.arange(n)
z = ((i * 0.6180339887498949) % 1.0 < 0.5).astype(int) # 1 = more severe case
u = (i * 0.7548776662466927) % 1.0
treated = (u < np.where(z == 1, 0.8, 0.2)).astype(int) # severe cases are treated more often
wobble = 0.5 * np.sin(5.0 * i)
outcome = 10 + 4 * z + 2 * treated + wobble # higher is better here
naive = outcome[treated == 1].mean() - outcome[treated == 0].mean()
print("treated %d, untreated %d" % (treated.sum(), n - treated.sum()))
print("naive difference in average outcome: %.3f" % naive)
effects, weights = [], []
for g in (0, 1):
m = z == g
e = outcome[m & (treated == 1)].mean() - outcome[m & (treated == 0)].mean()
effects.append(e); weights.append(m.sum() / n)
print(" within group z=%d (%d patients): effect %.3f" % (g, m.sum(), e))
print("adjusted for z (weighted by group size): %.3f true effect: 2" % sum(e * w for e, w in zip(effects, weights)))
coin = ((i * 0.5698402909980532) % 1.0 < 0.5).astype(int) # treatment decided by a coin flip instead
outcome2 = 10 + 4 * z + 2 * coin + wobble
print("randomised experiment, plain difference: %.3f" % (outcome2[coin == 1].mean() - outcome2[coin == 0].mean()))treated 100, untreated 100
naive difference in average outcome: 4.312
within group z=0 (100 patients): effect 2.000
within group z=1 (100 patients): effect 1.981
adjusted for z (weighted by group size): 1.990 true effect: 2
randomised experiment, plain difference: 2.005The plain difference is 4.312, more than twice the true effect of 2, because treated patients were mostly severe. Within each group of z the effect is 2.000 and 1.981. Combined with weights for the group sizes it gives 1.990, close to 2. In the randomised version the plain difference is 2.005, because the coin makes the groups alike.
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
Plain comparison, adjustment and randomisation written from scratch in C#, with no packages, printing the same output. Microsoft's ecosystem has no mainstream causal-inference library for .NET, so causal modelling is usually done in Python with libraries such as DoWhy or EconML, and the results are used from .NET.
// Confounding, adjustment and a randomised experiment, from scratch. Same output as causal.py. No packages.
const int n = 200;
int[] z = new int[n], treated = new int[n], coin = new int[n];
double[] outcome = new double[n], outcome2 = new double[n];
for (int i = 0; i < n; i++)
{
z[i] = (i * 0.6180339887498949) % 1.0 < 0.5 ? 1 : 0; // 1 = more severe case
double u = (i * 0.7548776662466927) % 1.0;
treated[i] = u < (z[i] == 1 ? 0.8 : 0.2) ? 1 : 0; // severe cases are treated more often
double wobble = 0.5 * Math.Sin(5.0 * i);
outcome[i] = 10 + 4 * z[i] + 2 * treated[i] + wobble; // higher is better here
coin[i] = (i * 0.5698402909980532) % 1.0 < 0.5 ? 1 : 0; // treatment decided by a coin flip instead
outcome2[i] = 10 + 4 * z[i] + 2 * coin[i] + wobble;
}
double Mean(IEnumerable<int> rows, double[] y) => rows.Average(i => y[i]);
var all = Enumerable.Range(0, n);
double naive = Mean(all.Where(i => treated[i] == 1), outcome) - Mean(all.Where(i => treated[i] == 0), outcome);
Console.WriteLine($"treated {treated.Sum()}, untreated {n - treated.Sum()}");
Console.WriteLine($"naive difference in average outcome: {naive:F3}");
double adjusted = 0;
foreach (int g in new[] { 0, 1 })
{
var m = all.Where(i => z[i] == g).ToList();
double e = Mean(m.Where(i => treated[i] == 1), outcome) - Mean(m.Where(i => treated[i] == 0), outcome);
adjusted += e * m.Count / n;
Console.WriteLine($" within group z={g} ({m.Count} patients): effect {e:F3}");
}
Console.WriteLine($"adjusted for z (weighted by group size): {adjusted:F3} true effect: 2");
Console.WriteLine($"randomised experiment, plain difference: {Mean(all.Where(i => coin[i] == 1), outcome2) - Mean(all.Where(i => coin[i] == 0), outcome2):F3}");Maths behind it
- Averages and differences of averages (statistics)
- Weighted averages by group size (arithmetic)
- Conditional comparison: within a group (probability)
- Randomisation: a coin removes the link between treatment and other factors (probability)
Common mistakes
- Reading a difference between treated and untreated groups as the effect of the treatment.
- Adjusting for a factor that is caused by the treatment, which can hide part of the real effect.
- Believing an adjusted result removes every confounder. It only removes the ones you measured.
- Running a model that predicts the outcome and using it to choose actions without asking what the action changes.
- Using an uplift model without checking it on a randomised sample.
Quick check
What is a confounder?
Show answer
A factor that affects both who gets the treatment and the outcome, so it can make a comparison of treated and untreated groups unfair.
Why does randomisation give a fair comparison?
Show answer
A coin decides who is treated, so the groups are alike on every other factor, measured or not.
In the example, the plain difference was 4.312 and the true effect was 2. Why?
Show answer
The treated group had far more severe cases, and severe cases score higher on the outcome for reasons unrelated to the treatment. The plain difference mixed the two.
What can adjusting not do?
Show answer
It cannot remove the bias from a confounder you did not measure.
Completion
Evidence of completion. A table showing the naive effect, the adjusted effect and the randomised effect for one dataset, with a sentence saying which you trust and why.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.