Counterfactuals and mediation: questions about single cases and causal paths
Before this lesson: potential outcomes (lesson 02); structural causal models and graphs (lesson 03); the do-operator and graph surgery (lesson 04); conditional distributions and Bayes' rule (probability 10 helps for abduction). Time: about 90 minutes, plus the notebook. The folded blocks can be skipped on a first reading.
Why this matters #
- Law and responsibility. Courts ask "but for" questions: would the harm have happened without the exposure? The probability of necessity is the formal version, and it explains the rule "a risk ratio above 2 makes causation more probable than not".
- Medicine and public health. Mediation analysis asks how a treatment works: does a drug lower heart attacks through blood pressure or through another path? Does a smoking ban work through fewer smokers or through less second-hand smoke?
- Fair machine learning. Counterfactual fairness (Kusner et al. 2017) asks whether a decision would stay the same if a person's protected attribute were different and everything it causes changed with it. Path-specific effects separate fair and unfair paths.
- Explanations and recourse. "You would have got the loan if your income were 500 higher" is a counterfactual statement about a model. It is useful only if acting on it works in the real world, which needs a causal model of the features (Karimi, Schölkopf and Valera 2021).
- Data augmentation. Some NLP and vision pipelines create counterfactual examples (swap a gender word, change a background) so that a model cannot rely on the changed attribute.
1. Predict first #
2. The picture #
2.1 Three rungs, three kinds of question #
Lesson 01 introduced Pearl's ladder of causation. Rung 1 is association: , "what do we expect to see?". Rung 2 is intervention: , "what happens if we act?". Rung 3 is the counterfactual: "given what actually happened, what would have happened if…?".
The difference between rung 2 and rung 3 is the population. An interventional question is about everybody (or a group): "what is the average recovery if all patients get the drug?". A counterfactual question is about the units that we observed, with what we know about them: "would Ann, who took the drug and recovered, have recovered without it?". The evidence about Ann (, ) and the hypothetical action () contradict each other. They live in two different worlds.
In this lesson, as in Pearl's books, in sections 2–3.3 is the variable we change (a cause), not a vector of covariates. A structural causal model (SCM, lesson 03) gives every variable an equation with an exogenous noise . For one unit, the noises fix everything: they are the unit's background, the things that make it special. A counterfactual keeps the unit's and changes the equations.
Take the model , with , and one unit with , :
- Abduction. Solve the equation of for the noise: . This unit has a large positive noise: its is 1 above the average of units with the same .
- Action. Replace the equation of by (graph surgery, as for ).
- Prediction. .
The counterfactual ("the value would have had if had been 0") is 1 for this unit. The interventional mean is . The two answers differ because the counterfactual uses what we learned about this unit. That answers question 1. ( is Pearl's notation; in the notation of lesson 02 it is the potential outcome of this unit.)
Press "Next step" three times. The yellow nodes are observed or inferred, hidden noises are dashed violet, and the variable we set is blue. In step 1 the wide prior of (grey) becomes a single value: . In step 3 the counterfactual is a single value, , while the interventional distribution (grey) is wide and centered at 0. Now choose "two noises": the effect of also varies between units, so one equation cannot fix two unknowns. The counterfactual becomes a narrow distribution, still much narrower than the interventional one. Set : the counterfactual is exactly the observed (consistency).
Why can the graph alone not answer rung 3? The graph says only that may affect . Two models with the same graph and the same distributions can disagree about single units (section 3.2). The counterfactual depends on how the noise enters the equation, for example whether the effect of is the same for every unit.
Which question is a counterfactual (rung 3) question?
The third question conditions on what happened to Bob (he took the drug, his value is 130) and asks about a world in which he did not take it. The first is rung 1 (a conditional mean). The second and fourth are rung 2: they are about the effect of an action on a population, which a randomized trial identifies.
2.2 Who was helped, who would have been fine anyway #
For a binary cause and a binary outcome , each unit has two potential outcomes , so it is one of four response types: never , always , caused : the outcome happens only with the exposure, and prevented . Ann was exposed and had the outcome, so she is an "always" or a "caused" unit. The probability of necessity (PN) asks how likely she is "caused": would the outcome have been absent without the exposure?
A randomized trial gives two numbers: and . There are four shares and only two equations (and the shares add up to 1), so one number stays free.
Move the last slider. The grid shows 100 units by type: caused (aqua), always (dark), prevented (violet) and never (light). The two bars are what a randomized trial measures; they do not change when you move the slider, but the share of "caused" among the exposed who had the outcome does. The dot is PN for this model, the yellow interval is everything the data allow. Try "no average effect": with , PN can be anything from 0 to 1.
The free number is the share of "prevented" units. If we can argue that the exposure never prevents the outcome (monotonicity), it is 0 and PN is fixed. Section 3.3 gives the formulas.
In the figure, and . With no "prevented" units, what share of all units is "caused", and what is PN?
With prevented : always , so caused . Among the exposed, the ones with the outcome are always + caused (exposure is randomized, so types do not depend on it). PN is the share of caused among them: . The first option forgets to condition on "had the outcome".
2.3 Direct and indirect paths #
Now take a treatment , a mediator (a variable on a causal path from to ) and an outcome , with and . The total effect of mixes two paths. Mediation analysis splits it. The natural indirect effect asks: keep the treatment at 1, and move only the mediator from the value it would have without treatment to the value it has with treatment. The natural direct effect asks: change the treatment, but keep the mediator at the value it would have without treatment.
Choose "no interaction" first. The bars show NDE, NIE and TE: truth (aqua), the estimate of the mediation formula (dark) and the product of coefficients (magenta) from 500 simulated units with a randomized . Without an interaction all three agree: NIE , NDE . Choose "interaction": the effect of depends on , so NIE and the product rule is wrong (magenta readout). The controlled direct effects CDE(0) and CDE(2) now differ too. Choose "hidden confounder": a hidden (dashed violet) affects and . The total effect is still right (T is randomized), but both splits are biased.
In the figure with the hidden confounder , and a randomized , why is the total effect still estimated well while the NDE is not?
Randomizing makes independent of everything before it, so is the total effect. The split compares units with the same ; but is not randomized, and affects both and . Conditioning on also opens the path (a collider). Without the NDE is identified (section 3.5).
3. Definitions and main results #
3.1 Counterfactuals in an SCM #
Definition. The counterfactual " had been " for a unit with noise is , the solution for of the modified model with . Given evidence , the counterfactual distribution is
Theorem (three steps; Pearl 2009, Theorem 7.1.7). is computed by
- Abduction: replace by the posterior ;
- Action: replace the equation of by , giving ;
- Prediction: compute the distribution of in with the noise distribution .
This is the definition written as a recipe: the sum over is step 3, the weights are step 1, and is computed in the model of step 2.
Special cases.
- With no evidence, : rung 3 contains rung 2.
- Consistency: if the evidence includes and , then . The modified model with the same reproduces the factual world.
- In an additive-noise model , abduction for fully observed variables is exact: . Then every counterfactual is a single number.
- Variables that are not descendants of keep their factual values in . Descendants change, through their equations, with their own abducted noise.
A binary example. Let and with independent , . In words: the drug () works for people with , and people with recover anyway. Ann has , . Would she have recovered without the drug?
- Abduction: with means , which has probability . So .
- Action: , so .
- Prediction: .
With probability Ann would not have recovered without the drug: the drug was necessary for her with probability . This number is her probability of necessity (section 3.3).
3.2 Rung 3 is not identified by rungs 1 and 2 #
Theorem (two models, one experiment). Two SCMs can give the same observational and interventional distributions but different counterfactuals.
Proof by example. with , and independent of .
- Model A: (exclusive or). Half the units are "caused" (: ), half are "prevented" (: ).
- Model B: . Half the units are "always", half are "never".
In both models for , and is independent of with : every rung-1 and rung-2 quantity is equal. Now take a unit with , . In model A abduction gives , so : the exposure was necessary (PN ). In model B, : it was not (PN ).
So no amount of experimental data alone fixes a counterfactual. We need extra assumptions about the functions (for example monotonicity or additive noise), or we must report bounds.
Twin networks
Balke and Pearl (1994) draw a counterfactual query as one graph. Copy every endogenous node: one copy for the factual world, one for the counterfactual world. The two copies share the exogenous noises . In the counterfactual copy, cut the arrows into and set . Now "" is an ordinary conditional probability in this larger network, and d-separation in the twin network tells us which counterfactual independences hold. For example, in with independent , the counterfactual (in the second copy) is d-separated from the factual (in the first copy), which gives the potential-outcome condition of a randomized experiment. Shpitser and Pearl (2007) extend this to "counterfactual graphs" and give a complete identification algorithm for counterfactual queries.
3.3 Probability of necessity and sufficiency #
Definitions (Pearl 1999; Tian and Pearl 2000), for binary and :
- Probability of necessity: . Among the exposed who had the outcome, the share who would not have had it without the exposure. ("But for" causation.)
- Probability of sufficiency: . Among the unexposed without the outcome, the share who would have had it with the exposure.
- Probability of necessity and sufficiency: , the share of "caused" units in the population.
Assumptions. Exogeneity: is independent of the response type, as in a randomized trial (then ). Monotonicity: for every unit; no unit is "prevented". Exogeneity can be secured by design; monotonicity is a claim about the science and cannot be tested with these data.
Theorem (bounds under exogeneity; Tian and Pearl 2000). With and ,
Under monotonicity PN equals the lower bound,
the excess risk ratio; also .
Proof. Let the type shares be (always), (caused), (prevented), (never).
- Exogeneity: the types have the same shares among the exposed. Exposed units with are always or caused, so .
- The data give and , so .
- The free share must keep every share in : gives ; gives ; gives .
- grows with . At the smallest , , it is . At the largest , , it is .
- Monotonicity means , which gives the lower bound and .
Now question 2 of section 1: , , . The data alone give . Under monotonicity, . So the honest answer is "at least 50%"; it is exactly 50% only if the drug never prevents recovery. This is the reason behind the legal rule of thumb: when , under monotonicity, so causation is "more probable than not". Check the binary example of 3.1: , , and that model is monotone, so , as computed by the three steps.
Combining experimental and observational data
With confounding, . Tian and Pearl (2000) show that the two kinds of data together can narrow PN:
Here and come from observational data. Under monotonicity PN equals the lower bound. Sometimes the bounds even collapse to one value. (We checked these bounds against a linear program over the eight cells "exposure × response type" for 2000 random models; the notebook shows the method.)
A randomized trial gives and . What does it say about PN for an exposed person with the outcome?
Lower bound ; upper bound . Under monotonicity . The risk difference is the PNS under monotonicity (a share of the whole population), not the PN (a share of the exposed people with the outcome).
3.4 Mediation: direct and indirect effects #
Let be binary, a mediator, the outcome. Write for the mediator under treatment and for the outcome when is set to and to .
Definitions.
- Total effect: , the usual ATE.
- Controlled direct effect: . The mediator is fixed at for everybody. It is a rung-2 quantity: .
- Natural direct effect: . Change , but keep each unit's mediator at its natural value without treatment.
- Natural indirect effect: . Keep , and move each unit's mediator from to .
Theorem (decomposition). .
Proof. Add and subtract inside the expectation: . Take expectations.
The term is a cross-world quantity: the treatment is 1, but the mediator takes the value it would have under treatment 0. No experiment can ever observe it, not even a randomized one, because a unit cannot be treated and untreated at the same time.
Theorem (linear models). Let and , with noises of mean 0. Then
Without the interaction (): for every , and , the product of coefficients (Baron and Kenny 1986), with .
Proof.
- , so . Take expectations: .
- Put : , so .
- , because for every unit. So .
- With steps 1–3 give , and .
Now question 3 of section 1: with , , , the indirect effect is , not . The product rule fails as soon as the effect of the mediator depends on the treatment. (With and , and : the first figure's default.)
3.5 Identification: the mediation formula #
Assumptions (Pearl 2001; Imai, Keele and Tingley 2010), possibly given pre-treatment covariates :
- No unmeasured confounding of .
- No unmeasured confounding of , given .
- No unmeasured confounding of .
- Cross-world assumption: no confounder of is itself affected by . Formally for all .
If is randomized, 1 and 3 hold by design. Assumptions 2 and 4 do not: the mediator is not randomized. Assumption 4 involves two worlds ( and ) at once, so no experiment can test it.
Theorem (mediation formula; Pearl 2001). Under 1–4 (shown without ; with , apply it within each stratum and average over ), for a discrete :
Proof sketch for the NIE. . By assumption 4, , and by 1–2 this equals . By 3, . Subtract the cases and . The NDE is the same computation.
A randomized job-training program raises income . Some of the effect goes through a certificate . Motivation affects both getting the certificate and income; it is not measured. Which quantity can you still estimate without bias?
Randomization of identifies the total effect. All the other quantities fix or compare the mediator, whose relation with is confounded by . Even the CDE, a rung-2 quantity, needs , which is not identified when and share a hidden cause.
3.6 Counterfactuals in machine learning #
Counterfactual fairness (Kusner, Loftus, Russell and Silva 2017). Let be a protected attribute in an SCM. A predictor is counterfactually fair if for every individual (every consistent with their data) and every value ,
"Would the decision be the same if this person's attribute were different, and everything it causes changed with it?" Kusner et al. show a simple sufficient condition: a predictor that uses only non-descendants of (and abducted noises) is counterfactually fair. A model that uses a descendant of , such as income in a world where affects income, is not, even if it never sees . This is different from "fairness through unawareness" (dropping ), which ignores the paths through other features.
Counterfactual explanations (Wachter, Mittelstadt and Russell 2017). For a classifier and an input with an unwanted decision, a counterfactual explanation is the closest point with the wanted decision: subject to . This is a statement about the model, and it treats every feature as an independent knob. It is not a causal counterfactual: it uses no SCM of the features. If a person follows it, the features they change move other features through the real causal links.
Algorithmic recourse (Karimi, Schölkopf and Valera 2021) asks the causal question: which action on the features, at the smallest cost, leads to the wanted decision, when the other features respond through the SCM? The person's own noise is kept (abduction), so recourse is a counterfactual computation.
Drag the applicant, then change . The model approves when (grey region). The explanation (magenta arrow) is the nearest approved point, which changes only income . In the feature SCM income causes savings with strength , so acting on income also moves savings along the aqua dashed direction; the dashed magenta arrow shows where a person who follows the explanation really ends. With the explanation overshoots: the recourse (dark arrow) reaches the boundary with a smaller change (1.64 instead of 2.30 for the default applicant). Choose "income lowers savings": following the explanation leaves the applicant rejected.
Counterfactual data augmentation. In NLP, Kaushik, Hovy and Lipton (2020) asked people to edit texts minimally so that the label flips; models trained with these pairs rely less on spurious words. Automatic versions swap attribute words ("he" ↔ "she") to reduce gender bias. These are counterfactuals only in a loose sense: the edit changes the attribute but usually does not model what the attribute causes.
4. Worked example #
We do one counterfactual in a three-variable linear model by hand, and then one mediation analysis from a table.
(a) Joe's homework (after Pearl, Glymour and Jewell, Primer, section 4.2). is time in an after-school program, is homework time, is the exam score (standardized units):
We observe Joe: , , . What would his score have been had he done ?
- Abduction. . . .
- Action. Replace the equation of by . is not a descendant of , so stays.
- Prediction. .
The counterfactual rises by , the coefficient times the change. Now a different question: what would his score have been had he not been in the program ()?
- Abduction: the same noises .
- Action: .
- Prediction: is a descendant of , so it changes: . Then .
The score falls by : the direct part plus the indirect part through homework.
(b) A mediation table. A randomized program , a binary mediator (a certificate) and a binary outcome (employed after a year). Assume 1–4 of section 3.5 hold. The data give
| 0.4 | 0.2 | 0.4 | |
| 0.8 | 0.3 | 0.7 |
- Total effect. . . .
- Controlled direct effects. and . They differ, so there is an interaction.
- NDE: weight the CDEs by the mediator distribution without treatment: .
- NIE: with , the mediator moves from to : .
- Check: .
About half of the effect () goes through the certificate. With the other convention (indirect effect at ) the indirect part would be : the reference level matters when there is an interaction.
5. In code #
NumPy checks the worked examples, the binary counterfactual and the linear mediation formulas.
import numpy as np
# (a) Joe: X := U_X, H := 0.5 X + U_H, Y := 0.7 X + 0.4 H + U_Y
def f_H(x, uH): return 0.5 * x + uH
def f_Y(x, h, uY): return 0.7 * x + 0.4 * h + uY
X, H, Y = 0.5, 1.0, 1.5
uX, uH, uY = X, H - 0.5 * X, Y - 0.7 * X - 0.4 * H # abduction
print(uX, uH, round(uY, 3)) # 0.5 0.75 0.75
print(round(f_Y(X, 2.0, uY), 3)) # 1.9 (Y had H been 2)
h0 = f_H(0.0, uH) # H changes: it is a descendant of X
print(h0, round(f_Y(0.0, h0, uY), 3)) # 0.75 1.05 (Y had X been 0)
# binary counterfactual: Y := (X and U1) or U2, by enumerating the noises
pU1, pU2 = 0.5, 0.2
num = den = 0.0
for u1 in (0, 1):
for u2 in (0, 1):
p = (pU1 if u1 else 1 - pU1) * (pU2 if u2 else 1 - pU2)
if (1 and u1) or u2: # evidence X = 1, Y = 1
den += p
num += p * (u2 == 0) # Y_{X=0} = U2 = 0: the drug was necessary
print(round(num / den, 4)) # 0.6667 = PN
p1, p0 = 1 - (1 - pU1) * (1 - pU2), pU2
print(round(p1, 3), p0, round((p1 - p0) / p1, 4)) # 0.6 0.2 0.6667 (excess risk ratio)
# (b) mediation formula on the table
PM = {0: 0.4, 1: 0.8} # P(M = 1 | T)
EY = {(0, 0): 0.2, (0, 1): 0.4, (1, 0): 0.3, (1, 1): 0.7} # E[Y | T, M]
pm = lambda m, t: PM[t] if m else 1 - PM[t]
TE = sum(EY[1, m] * pm(m, 1) - EY[0, m] * pm(m, 0) for m in (0, 1))
NDE = sum((EY[1, m] - EY[0, m]) * pm(m, 0) for m in (0, 1))
NIE = sum(EY[1, m] * (pm(m, 1) - pm(m, 0)) for m in (0, 1))
print(round(TE, 3), round(NDE, 3), round(NIE, 3)) # 0.34 0.18 0.16
# linear mediation with interaction: simulate the cross-world quantity Y(1, M(0))
rng = np.random.default_rng(1)
n, a, b, c, d = 10**6, 2.0, 1.0, 0.5, 0.5
eM, eY = rng.normal(size=n), rng.normal(size=n)
M = lambda t: 1 + a * t + eM
Yf = lambda t, m: c * t + b * m + d * t * m + eY
print(round(np.mean(Yf(1, M(0)) - Yf(0, M(0))), 3)) # 1.0 = c + d E[M(0)]
print(round(np.mean(Yf(1, M(1)) - Yf(1, M(0))), 3)) # 3.0 = a (b + d), not ab = 2
The simulation can compute only because we wrote the model and kept the noises. In real data this quantity is never observed; the mediation formula replaces it under assumptions 1–4.
6. Where it shows up #
- Epidemiology and medicine. Mediation analysis is standard: how much of the effect of education on heart disease goes through smoking or blood pressure; how much of a vaccine's effect goes through antibodies. VanderWeele's book (2015) is the main reference.
- Law. "But for" causation in toxic-tort cases uses the excess risk ratio and the rule ; the PN bounds show what the epidemiological data really support.
- Fairness in ML. Counterfactual fairness and path-specific fairness (Chiappa 2019) decide which causal paths from a protected attribute to a decision are allowed; for example, a path through a job-relevant skill may be allowed, a direct path may not.
- Explainability and recourse. Counterfactual explanations are implemented in many explainability libraries; recourse work adds the causal model and feasibility constraints (age cannot go down).
- Root-cause analysis. "Would the outage have happened without this deployment?" is a PN-type question; causal root-cause tools in operations and in manufacturing compute counterfactuals in fitted SCMs.
- ML for science. In climate science, probabilistic event attribution compares the probability of an extreme event with and without human forcing, and ; the reported "fraction of attributable risk" is the PN under monotonicity. In genetics, mediation analysis asks how much of a variant's effect on a disease goes through gene expression.
7. Common mistakes #
- Answering a rung-3 question with a rung-2 number. "The drug raised recovery from 20% to 40%, so it saved Ann with probability 20%" is wrong. Compute PN or its bounds; state monotonicity if you use it.
- Treating a counterfactual as identified by the graph. Counterfactuals depend on the functional form and the noise. Say which assumptions (additive noise, monotonicity) fix them, or report bounds.
- Keeping the descendants fixed. In the action step, only the non-descendants of the changed variable keep their factual values. Descendants change through their equations with the abducted noises (Joe's homework in section 4).
- Product of coefficients with an interaction or a nonlinear model. is the NIE only in linear models without a term. Fit the interaction and use the mediation formula; check by simulation.
- Mediation analysis that ignores mediator–outcome confounding. Randomizing does not randomize . Adjust for measured – confounders, never for ones affected by , and run a sensitivity analysis.
- Mixing up CDE and NDE. The CDE fixes the mediator at one value for everybody; the NDE keeps each unit's natural value. They are equal only without interaction.
- Calling a counterfactual explanation causal. It describes the model's decision boundary. Following it can fail when features cause each other; use recourse with a causal model of the features.
- "Fairness through unawareness". Removing the protected attribute does not remove its effect through descendants such as income or zip code.
8. Check yourself #
- In the model , , we observe , . Compute and
(with ).
Answer
Abduction: . Action . Prediction: . The interventional mean is . The unit has a negative noise, so its counterfactual is 1 below the population mean. - Why is only a lower bound without monotonicity?
Answer
The trial fixes and . If some units are "prevented" (), then for the same there are fewer "always" units and more "caused" ones: . So grows with . Monotonicity sets , the smallest value. - A linear SCM has , . Give TE, NDE, NIE and .
Answer
No interaction: for every , so ; ; . - Why can no randomized experiment, even one that randomizes both and , observe ?
Answer
It needs, for each unit, the mediator value under and the outcome under with that mediator value. A unit is either treated or not; we never see for a treated unit. Randomizing gives (CDEs), not the unit's own . This is why the cross-world assumption 4 is needed. - A lending model does not use race, but uses zip code and income, which race affects in the SCM. Is it counterfactually fair? What predictor would be?
Answer
Usually not: changing race in the counterfactual world changes zip code and income (descendants), so the prediction changes. A predictor that uses only non-descendants of race, or the abducted noise terms of the features (the parts not caused by race), is counterfactually fair (Kusner et al. 2017). - In the recourse figure with , the applicant is at . Verify that the explanation costs 2.30 and the recourse 1.64.
Answer
Score , gap . The explanation changes only: . Acting on also raises by , so the score rises by ; . Acting on alone gains per unit and would cost .
Name the three steps for computing a counterfactual in an SCM.
Abduction: update to . Action: replace the equation of by . Prediction: compute in the modified model with the updated noise.
Why does a counterfactual need more than the causal graph and ?
It depends on how the noise enters each equation, for one unit. Different SCMs with the same graph and the same experiments can give different counterfactuals.
In , , a unit has . Compute and .
, so ; .
What is a twin network?
A graph with a factual and a counterfactual copy of every endogenous node, sharing the exogenous noises; the counterfactual copy has the intervention applied. Counterfactual queries become conditional probabilities in it.
Define the probability of necessity.
: among exposed units with the outcome, the share that would not have had it without the exposure.
Give PN under exogeneity and monotonicity.
, the excess risk ratio. So gives .
Define the natural direct and natural indirect effects.
; .
Why is ?
Add and subtract inside .
When does the product of coefficients equal the NIE, and what is the NIE with an interaction ?
In a linear model without a interaction. With the interaction, .
Define counterfactual fairness.
A predictor is counterfactually fair if, for every individual, its prediction distribution would be the same had the protected attribute been different, with all descendants of the attribute changing accordingly.
9. Interview angle #
- "What is the difference between an interventional and a counterfactual question?" — Interventional: the effect of an action on a population, , identifiable from experiments. Counterfactual: what would have happened to observed units in another world, ; needs the functions and noise of an SCM or bounds.
- "A trial shows risk ratio 3. What is the probability that the drug caused this patient's side effect?" — Under monotonicity (the drug never prevents the side effect) and no confounding, . Without monotonicity, only .
- "How would you measure how much of a feature launch's effect on revenue goes through engagement?" — Randomize the launch (TE), define NDE/NIE, use the mediation formula with engagement as mediator; say that engagement is not randomized, so engagement–revenue confounders must be measured; run a sensitivity analysis.
- "Is the product of coefficients a good estimate of the indirect effect?" — Only in linear models without interaction and without unmeasured mediator–outcome confounding.
- "Is a counterfactual explanation the same as a causal counterfactual?" — No. It is the nearest input with another prediction, ignoring causal links between features. Recourse uses an SCM of the features.
10. Practice #
The notebook for this lesson has four exercises, each with a check cell and a folded solution:
- Write
counterfactual(scm, evidence, intervention)for additive-noise SCMs (abduction by solving for the noise); check the examples of this lesson and Joe's homework. - Build two binary SCMs with the same interventional distribution but different counterfactuals, and compute PN in both by enumerating the noise; compare with the Tian–Pearl bounds.
- Mediation in a linear SCM: estimate NDE and NIE by regression (product of coefficients and mediation formula) and by simulating from the true model; add an interaction and see the product rule fail.
- Counterfactual fairness on a simulated lending SCM: change the protected attribute, propagate to the descendants with each person's own noise, and compare a model that uses descendants with one that does not.
11. Watch and read #
- Pearl, Glymour and Jewell, Causal Inference in Statistics: A Primer (2016), chapter 4 (companion site): counterfactuals, the three steps, PN and mediation.
- Peters, Janzing and Schölkopf, Elements of Causal Inference (2017, open access), chapter 3 and section 6.4: counterfactuals in SCMs.
- Tian and Pearl (2000), Probabilities of causation: bounds and identification.
- Pearl (2001), Direct and indirect effects.
- Imai, Keele and Tingley (2010), "A general approach to causal mediation analysis", Psychological Methods.
- Kusner, Loftus, Russell and Silva (2017), Counterfactual fairness.
- Wachter, Mittelstadt and Russell (2017), Counterfactual explanations without opening the black box.
- Karimi, Schölkopf and Valera (2021), Algorithmic recourse: from counterfactual explanations to interventions.
- Brady Neal, Introduction to Causal Inference (free course notes), chapter 14.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.