Causes Without Experiments
When you cannot randomize, what can still be learned, and at what cost in assumptions?
LaLonde takes a job-training experiment whose answer is known, about $1,794 a year, throws away its randomized controls, and asks whether survey men can stand in for them: the raw difference is -$635. The part asks what would have to be true for such a comparison to work. Unconfoundedness and overlap give the adjustment formula; causal diagrams and d-separation say which covariates to adjust for, and which (colliders, mediators) to leave alone; the front door identifies an effect with no adjustment set at all, and Simpson's paradox from Part 1 is resolved by the graph. Estimation follows on an observational version of the World's clinic, where the truth is known: g-computation models the outcome, propensity scores model the treatment, and the augmented estimator combines them so that either model being right is enough. Double machine learning adds cross-fitting so flexible learners can supply both. The part turns to what cannot be tested: with an unmeasured frailty every adjusted estimate is wrong, and Rosenbaum's Gamma, E-values and robustness values say how strong a hidden confounder would have to be, the argument Cornfield used for smoking. It ends back at LaLonde, where overlap, placebo outcomes and sensitivity decide how far the estimates can be trusted.
What you need. Potential outcomes from Part 35; logistic regression (Part 24) and the forests of Part 34 for the nuisance fits.
- Hook
- LaLonde's job training, 1986
- Mathematics
- DAGs, back-door and front-door, propensity scores, IPW, AIPW, DML, CATE, sensitivity, smoking
- Built
- statkit.causal
What you will be able to do
Bachelor's
- Read a causal diagram: tell a chain, a fork and a collider apart, and say which paths conditioning on a variable opens or blocks.
- Explain the argument that made the case for smoking as a cause of lung cancer without an experiment.
Master's
- Apply the back-door criterion to choose an adjustment set, and compute the adjustment and front-door formulas.
- Estimate an average effect by g-computation, matching, subclassification, IPW and AIPW, and check balance and effective sample size.
- Fit a marginal structural model with stabilized weights when a confounder is itself affected by earlier treatment.
PhD
- Show that the AIPW score is Neyman orthogonal, and state the product-rate condition under which cross-fitted DML is root-n normal.
- State the three rules of the do-calculus and what their completeness means.
Practice
- Inspect overlap before estimating anything, and report the largest weight, the effective sample size and a placebo outcome with the estimate.
- Report an E-value or a robustness value with an observational estimate, benchmarked against a measured covariate.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 17 min · Master's 51 min · PhD 58 min · Practice 25 min.
- 0LaLonde's testBachelor's4 min
- 1Unconfoundedness and overlapMaster's3 min
- 2Causal diagramsBachelor's4 min
- 3The back doorMaster's3 min
- 4The front door and do-calculusPhD3 min
- 5Simpson resolvedBachelor's2 min
- 6g-computationMaster's2 min
- 7Propensity scoresMaster's3 min
- 8WeightingMaster's3 min
- 9Double robustnessMaster's4 min
- 10Double machine learningPhD4 min
- 11Heterogeneous effectsMaster's5 min
- 12Sensitivity analysisPractice5 min
- 13Smoking and lung cancerBachelor's4 min
- 14Time-varying treatmentsMaster's3 min
- 15LaLonde revisitedPractice3 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
LaLonde's testBachelor's4 min
In 1986 the economist Robert LaLonde, fresh from his doctorate at Princeton, published one of the most influential tests in social science. The National Supported Work Demonstration of the mid-1970s had randomly assigned disadvantaged workers, many of them ex-offenders and former addicts, either to a programme of subsidized work experience or to a control group. LaLonde kept the programme's participants, threw away the randomized controls, and replaced them with men drawn from national surveys. Then he asked the econometric methods of the day to recover the experimental answer. If the methods targeted the same effect under valid assumptions, their estimates should be compatible with the experiment's sampling uncertainty. They did not. The estimates scattered widely, many far from the experimental benchmark and some with the wrong sign, and the specification tests of the time could not tell the good ones from the bad.
The data have been reanalysed ever since. In the subsample that Rajeev Dehejia and Sadek Wahba used in 1999, one hundred and eighty-five men took part in the programme and two hundred and sixty were randomized controls. The outcome is earnings in 1978, after the programme. The experiment says the programme raised earnings by about one thousand eight hundred dollars, with a wide interval. This noisy experimental estimate provides a valuable benchmark; it is not the exact treatment effect.
Following LaLonde's comparison strategy, replace the randomized controls with the four hundred and twenty-nine comparison men in the MatchIt teaching data from the Panel Study of Income Dynamics, a national household survey. The trainees and the randomized controls look alike, because a coin divided them. The survey men do not. They are older, far more likely to be married, much less likely to be black, and in 1974 earned more than twice as much. Nothing made them comparable.
The experiment: plus one thousand eight hundred dollars. Comparing the trainees with the survey men directly: minus six hundred and thirty-five. The programme appears to hurt. Adjusting by regression for age, education, race, marriage and past earnings brings the estimate to about fifteen hundred, much closer. But as we will see in chapter fifteen, other methods that sound equally reasonable give anything from four hundred to seventeen hundred dollars. Without the experiment, how would we know which to believe?
In 1999, Dehejia and Wahba showed that propensity-score methods, the subject of chapter seven, come close to the experimental answer on their subsample. In 2005, Jeffrey Smith and Petra Todd replied that they do so only on that particular subsample, and only with some specifications. The debate turned into a lesson that this part tries to teach: what decides whether observational causal inference works is not the cleverness of the method but the assumptions it rests on, and whether the data contain comparable people at all.
Most causal questions can never be put to a coin: whether smoking causes cancer, whether schooling raises earnings, whether a policy worked, why a war began. So what must we assume to learn about causes from observation? How do we adjust, and for what? And how wrong might we be?
Numbers: $1,794 vs −$635
1Unconfoundedness and overlapMaster's3 min
In a randomized trial, treatment is independent of the potential outcomes. Without randomization, the best we can hope for is independence given covariates X: among patients who look alike on X, treatment is as good as random. This is unconfoundedness, also called selection on observables. We also need overlap: at every value of X, there must be some chance of either treatment, so that every kind of treated patient has comparable untreated ones. Paul Rosenbaum and Donald Rubin called the pair strong ignorability in 1983.
Under these assumptions the average effect is identified, which means it can be written in terms of the distribution of observable things. Start with the average treated outcome, and average it over X. By unconfoundedness, within each X the treated outcome has the same average among the treated as among everyone. For the treated, the treated outcome is simply what we see. Overlap ensures that there are treated patients at every X, so the conditional mean exists. The average effect is the average over X of the difference in conditional means: the adjustment formula. Every method in this part is a way of estimating it.
The World gives us a test bed. Take three thousand eligible patients from the island and no trial at all: doctors prescribe the drug as they see fit, more often to patients with higher pressure, older patients and heavier ones. percent are treated. The World knows the truth: an average effect of minus , and minus among the treated, who are sicker and benefit more. The naive comparison says minus . Here, unlike in life, we know that the doctors used only the four recorded covariates, so unconfoundedness holds by construction.
Practical overlap can be diagnosed in the observed sample. Here is each patient's estimated probability of being treated, from a logistic regression on the four covariates, for the treated in red and the untreated in blue. The treated pile up near one and the untreated near zero, as they should when doctors choose. In between both groups are present. At the ends there are few comparable patients, and the methods ahead will have to extrapolate, or weight a handful of people very heavily.
Observed covariate support can reveal overlap problems, but finite data cannot establish positivity everywhere. Unconfoundedness cannot generally be verified from these observed outcomes alone. It is a claim about what we did not measure, and no amount of data on what we did measure can confirm it. It has to be argued from knowledge of how the treatment was actually chosen. The next chapters give that argument a precise language: causal diagrams.
Numbers: ATE −10.02; naive −1.38
2Causal diagramsBachelor's4 min
In 1921 the geneticist Sewall Wright drew diagrams of arrows to describe how coat colour was inherited in guinea pigs, and showed how to read correlations off them. Statisticians, Fisher among them, largely ignored the idea for half a century. In the 1990s the computer scientist Judea Pearl rebuilt it as a theory of directed acyclic graphs, with rules for reading off which variables are independent, and an operator for interventions. A causal graph is an assumption made explicit: which variables directly cause which. Its independence implications follow under the causal Markov assumptions; effect sizes still need data or further assumptions.
The World's observational study as a graph. The drug T and the twelve-week pressure Y. X, the baseline pressure, age and weight. An arrow from X to T, because the doctors use them to decide. An arrow from X to Y, because they also affect the outcome. And an arrow from T to Y: the effect we want. The absence of an arrow is the strong claim: no unrecorded variable points into both T and Y.
Every path in a graph is built from three kinds of junction. In a chain, A causes B causes C, and B is a mediator. The chain permits association, and conditioning on B blocks this path. In a fork, B causes both A and C: a confounder. Again the path permits association, and conditioning on B blocks it. In a collider, A and C both cause B. In this isolated collider graph the path is closed, so A and C are independent. Other open paths could change that. But conditioning on the collider opens it. That last rule is the surprising one, and the source of some famous paradoxes.
The rules combine into d-separation. A path is blocked by a set Z if it passes through a chain or fork node that is in Z, or through a collider that is not in Z and has no descendant in Z. Two variables are d-separated by Z if every path between them is blocked. And then, as Thomas Verma, Pearl and others proved, they are independent given Z in every probability distribution satisfying the graph's Markov property. Independence, a statistical property, is read off a picture of causes.
Apply the rules to the treatment and outcome. Association between T and Y can flow along the causal arrow, and along back-door paths, which start with an arrow into T. The path through X is a fork, blocked by adjusting for X. But suppose the doctors also judge an unrecorded frailty U, which also affects the outcome. That path stays open whatever we do with X. The graph shows exactly what unconfoundedness requires: no open back-door path once X is adjusted for.
The graph comes from knowledge of the subject, not from the data. Some of its implications can be tested, because it predicts particular independences. Its core cannot: the arrows it leaves out, especially to and from unmeasured variables. Next, how the graph tells us what to adjust for, and what to leave alone.
Numbers: three junctions; d-separation
3The back doorMaster's3 min
Pearl's back-door criterion says when a set of covariates Z is enough. First, nothing in Z may be a consequence of the treatment. Second, Z must block every back-door path from T to Y. If so, the distribution of the outcome under an intervention that sets T to t, written with Pearl's do-operator, is the conditional distribution given t and z, averaged over the population distribution of z. That is the adjustment formula of chapter one. The graph tells us when it is valid, and, as the next three examples show, when adjusting makes things worse.
In 1946 the Mayo Clinic statistician Joseph Berkson noticed that two diseases could appear related among hospital patients when they are unrelated in the population. Being admitted is a collider: either disease, if severe enough, puts you in hospital. Simulate two independent diseases: correlation zero. Among those admitted, the correlation is : a patient admitted without one disease must, almost surely, have the other. Conditioning on a collider, here by studying only hospital patients, manufactures an association out of nothing.
A subtler trap is M-bias, named for the shape of its graph. A pre-treatment variable M is caused by two unmeasured variables, one of which affects the treatment and the other the outcome. M comes before treatment and is correlated with both T and Y, so it looks exactly like a confounder. But the only path through it is closed, because M is a collider: the unadjusted estimate is already right. Adjusting for M opens the path, and the estimate falls from one to . Adjusting for A as well blocks the path again. The rule 'adjust for everything measured before treatment' is not safe.
And a mediator: the treatment works partly through an intermediate variable M, such as a lab value that the drug changes. The unadjusted comparison estimates the total effect, two. In this additive toy model with no mediator-outcome confounding, adjusting for M leaves one, the direct effect. Such a regression does not generally identify direct effects. Neither number is wrong, but they answer different questions, and adjusting for the consequences of treatment by habit answers the wrong one. Separating direct and indirect effects properly is mediation analysis, in Part 62.
So: adjust for confounders, the common causes of treatment and outcome. Do not adjust for colliders, nor for mediators or anything else the treatment affects. When the full graph is uncertain, Tyler VanderWeele and Ilya Shpitser's disjunctive cause criterion is sufficient when some subset of the measured pre-treatment variables already controls confounding. Adjust for every pre-treatment variable that is a cause of the treatment, the outcome, or both. Correlations alone do not determine which variables should be adjusted for. Conditional-independence evidence can help constrain graphs under further assumptions, but does not replace causal knowledge. Only knowledge of the causal structure can.
Numbers: Berkson −0.56; M-bias 0.16
4The front door and do-calculusPhD3 min
Sometimes no adjustment set exists, and the effect is still identified. Pearl's example is Fisher's objection to the smoking evidence, drawn as a graph. Suppose a genotype U causes both a craving for tobacco and cancer. Smoking T deposits tar M in the lungs, which causes cancer Y. U is unmeasured, so the back door from smoking to cancer through it cannot be closed. But if smoking affects cancer only through tar, and the genotype has no direct effect on tar, there is another way in: through the front door.
The argument has two steps. The effect of smoking on tar has no back door, since the only path from T to M through U is blocked by the collider at Y: so it is just the conditional distribution. The effect of tar on cancer has a back door, M from T from U to Y, but conditioning on smoking blocks it: adjust for T. Chain the two, and the effect of smoking on cancer is identified, though the confounder was never measured. The price is two strong assumptions about the mediator, which real tar rarely satisfies; the front door is rare in practice, but it showed that adjustment is not the only route to identification.
A simulated population of four hundred thousand, thirty percent of whom carry the genotype. The naive comparison of smokers with non-smokers gives a difference in cancer risk of , nearly double the truth, because carriers both smoke more and get more cancer. The true causal difference is . The front-door formula, using only smoking, tar and cancer, gives .
Both the back-door and front-door formulas are special cases of Pearl's do-calculus, three rules for rewriting expressions with interventions. The first deletes or adds an observation when the graph makes it irrelevant. The second exchanges an intervention for a mere observation when no back door is open. The third deletes an intervention that cannot affect the outcome. In 2006 Ilya Shpitser and Pearl, and independently Yimin Huang and Marco Valtorta, proved the rules complete for identifying causal intervention distributions from an observational distribution in the assumed nonparametric causal graph model. If that effect is not identifiable there, new assumptions or data are needed. This does not mean every causal question is identified or that the graph itself is known.
The graphical language and the potential-outcomes language of Part 35 are two notations for one theory. Thomas Richardson and James Robins's single-world intervention graphs make the bridge explicit: they split the treatment node into the value we set and the value it would naturally take, so that statements like unconfoundedness, the independence of Y of t from T given X, can be read straight off the picture. Next, an old paradox, resolved by drawing it.
Numbers: 0.235 vs 0.129 (truth 0.128)
5Simpson resolvedBachelor's2 min
Part 1 ended with a puzzle from the World's clinic. Among patients with mild illness, the treated recover more often, by about eight points; among the severely ill, also by about eight points; but over everyone, the treated recover less often, by eleven points. The reason is that doctors treat the severely ill three times as often, and the severely ill recover less. Part 1 said that statistics alone cannot say which comparison is right. Now we can.
Draw the clinic. Severity is determined before treatment. It causes treatment, through the doctors' choices, and it causes recovery. So it is a confounder, and the back-door path from treatment through severity to recovery must be closed by adjusting for it.
The back-door formula: average the within-severity recovery rates over the population's mix of severity. About sixty-five percent mild and thirty-five percent severe. The causal effect of treatment is a gain of points in recovery. That is what the World built in: the treatment raises everyone's chance of recovery by seven or eight points. The aggregate comparison mixed the effect of treatment with the effect of being sick.
Pearl's point is that the same table can call for the opposite answer. Suppose the third variable were not severity at admission but blood pressure measured after treatment, which the treatment affects. Then it is a mediator, part of the path by which treatment acts. Adjusting for it would remove part of the effect, and the aggregate comparison is the right one. The numbers are identical; the causal story decides.
So Simpson's paradox is not a paradox of probability; the arithmetic is fine. It is a reminder that causal questions need causal assumptions. With the graph, choosing the right comparison is a calculation. Next, carrying out that calculation when the covariates are many and continuous.
Numbers: −11.2 → +7.8 points
6g-computationMaster's2 min
The most direct way to compute the adjustment formula is to model the outcome. Fit a regression of the outcome on the covariates, separately among the treated and the untreated. Use the two models to predict every patient's outcome under both treatments: conditional mean outcomes, rather than each individual's missing potential outcome. Average the predicted differences. James Robins introduced this in 1986, for treatments that change over time, as the g-formula, g for generalized; with one time point it is also called standardization, or the T-learner. It is valid if the identifying assumptions hold and the outcome models are right. The last condition is the catch.
In one dimension it is a picture. Twelve-week pressure against baseline pressure, treated in red and untreated in blue. Fit a line to each arm. We fit both arms using all four recorded covariates, and standardize the other three over the same patients. The gap is the model's standardized effect at each baseline; averaging over baseline gives its g-computation estimate. Notice where the data are: few untreated patients at high pressure, few treated at low. There, each line is an extrapolation.
With all four covariates and a linear model in each arm, g-computation estimates minus , against the true minus ; the naive comparison said minus . It works here because the World's outcomes really are close to linear in the covariates. When the outcome model is wrong, so is the answer, and nothing in the procedure warns us.
The weakness is that the outcome model is trusted most exactly where there are fewest data of the other arm to check it. Flexible models such as forests reduce the risk of the wrong functional form, but they bring regularization bias and no simple standard error, a problem chapter ten will solve. The alternative strategy models how the treatment was chosen, not how the outcome is produced.
Numbers: −10.35
7Propensity scoresMaster's3 min
Rosenbaum and Rubin's 1983 idea was to model the treatment instead. The propensity score is each patient's probability of being treated given their covariates. It is a balancing score: among patients with the same propensity, the covariates have the same distribution in the two arms, whatever their values. So if treatment is unconfounded given X, it is unconfounded given the propensity score alone. Instead of matching patients on many covariates, we can compare patients with equal propensity: a one-dimensional problem.
The simplest use is matching. For each treated patient, find the untreated patient whose estimated propensity is closest. The average difference between the pairs estimates the effect on the treated, because every pair's treated member is one of the treated. Allowing controls to be reused permits closer matches, but creates dependent pair differences. Standard errors must account for that reuse. A caliper drops treated patients with no close match, which enforces overlap but quietly changes the population the estimate is about.
An older idea, from William Cochran in 1968, cuts the score into five strata. Compare treated and untreated within each stratum, then average the five differences. Cochran showed that five strata remove about ninety percent of the bias due to a covariate, under conditions he worked out. The other ten percent remains, because within a broad stratum the treated still have somewhat higher scores than the untreated.
On the World's observational study. The naive comparison, minus . Matching each treated patient to its nearest untreated neighbour on the propensity score: minus , close to the true effect on the treated, minus . Five strata: minus , which removes percent of the naive bias, much as Cochran predicted, but not all of it.
A real virtue of propensity methods is that the score is built without looking at the outcomes. The analyst can refine the score, the matches and the strata until the covariates balance, as with rerandomization, which reduces direct outcome-driven selection. The analyst must still document the design choices and account for the final design. Rubin put it in a title in 2008: for objective causal inference, design trumps analysis. Next, using the score as a weight.
Numbers: ATT −12.43; strata −8.59
8WeightingMaster's3 min
Weighting uses the propensity score differently. A treated patient whose propensity is point two is, in effect, one of five similar patients, four of whom were not treated. Let that patient stand for all five, with a weight of one over e, which is five. An untreated patient with the same propensity stands for one point two five. Then each weighted arm resembles the whole population in its covariates, as if a coin had assigned treatment: a pseudo-randomized trial built from observational data. It is Part 18's Horvitz–Thompson estimator, with treatment in place of being sampled.
The inverse probability weighted estimator averages treated outcomes divided by the propensity, minus untreated outcomes divided by one minus it. Why it works: the expected treated term, given X, is the probability of treatment times the average treated outcome, divided by the probability of treatment, by unconfoundedness. The propensities cancel, leaving the mean treated outcome. In practice one normalizes the weights to sum to n in each arm, Hajek's version, which is more stable. For the effect on the treated, the treated get weight one, and the untreated are reweighted by the odds e over one minus e, to look like the treated.
Check balance, the way a trial would. For each covariate, the standardized difference in means between the arms. Before weighting, the treated have baseline pressures over a standard deviation higher, and are much older. After weighting, the differences shrink towards zero, though baseline pressure is still above the conventional threshold of a tenth. The propensity model here is exactly the right one; what remains is the work of a few enormous weights at the edges of overlap.
The weighted estimate is minus , against the true minus : much better than the naive comparison, but in this sample its interval misses the truth. The largest weight is , and the weights are so uneven that each arm's fifteen hundred patients count as about seven hundred. A few patients at the edges of overlap carry much of the answer, which is IPW's characteristic weakness.
There are standard remedies for extreme weights. Trim the sample to the region of good overlap, as Richard Crump and colleagues proposed in 2009, accepting that the estimate then describes that region only. Truncate the largest weights, trading variance for some bias. Or target the overlap population, whose density is tilted by e times one minus e. The actual observation weights are one minus e for treated patients and e for controls. With a converged unpenalized logistic fit, its score equations give exact balance for the included covariate means.
Numbers: −8.48; max weight 36
9Double robustnessMaster's4 min
Combine the two strategies. For each patient, take g-computation's predicted effect, and add inverse-probability-weighted corrections from the residuals of the outcome models. Average these scores. Their spread gives the usual influence-function standard error when nuisance estimation satisfies the inference conditions; one correct nuisance alone does not automatically validate that standard error. This augmented inverse probability weighted estimator was introduced by James Robins, Andrea Rotnitzky and Lue Ping Zhao in 1994. One reading is g-computation, corrected by weighting its own mistakes. The other is IPW, with the outcome model removing most of the noise that the weights would amplify.
Its key property: if the outcome models are right, the residual corrections average to zero whatever the weights, so the estimate is consistent. If instead the propensity model is right, the weighted residuals exactly cancel the outcome models' bias, whatever it is. So the estimator is consistent if either model is right: doubly robust. And when both are right, its variance is the smallest that any regular estimator can achieve under these assumptions, because the true score minus the target effect is the efficient influence function, which Part 49 derives.
On the World's study, the doubly robust estimate is minus , very close to the truth, with an interval that covers it. And its standard error is about two thirds of IPW's: the outcome models absorb most of the noise.
But what if both models are wrong? In 2007 Joseph Kang and Joseph Schafer published a simulation that became famous. Four standard normal variables determine an outcome linearly, and whether it is observed, logistically: the task is to estimate its mean, two hundred and ten, from the observed cases, a missing-data version of the causal problem. The analyst sees only smooth transformations of the four variables, so both a linear outcome model and a logistic observation model fitted to them are slightly wrong, though the working models can look plausible in routine diagnostics.
A thousand samples of a thousand. The wrong outcome model alone is only slightly biased, by less than one. IPW with the wrong propensity model is worse, biased by five with a large error. With either model right, the simulated estimates have small bias and around ninety percent coverage here. Double robustness is a consistency result; it does not promise finite-sample unbiasedness or automatically doubly robust confidence intervals. With both wrong, it is a disaster: a bias of minus twenty-one and a root mean squared error of about two hundred, far worse than the simple outcome model, because a few observations with near-zero estimated propensity receive weights in the tens of thousands, and the doubly robust correction multiplies their residuals by those weights.
So double robustness is insurance against one mistake, not against two. The replies to Kang and Schafer proposed bounded weights, propensity models fitted for balance, and targeted maximum likelihood estimators, Mark van der Laan's TMLE, which keep estimates inside the range of the data. The modern answer is to fit both models flexibly, with machine learning, so that neither is badly wrong, and to do it carefully, which is the next chapter.
Numbers: −9.91; Kang–Schafer bias −21.5
10Double machine learningPhD4 min
Real confounding is rarely linear: doctors use thresholds, effects interact, risks curve. So it is natural to fit the outcome regressions and the propensity score with the flexible learners of Part 34. But machine learning methods deliberately accept bias to reduce variance, and a regularized nuisance fit leaks its bias into the causal estimate. And they overfit: their residuals on the data they were trained on are too small, which makes any standard error built from them too small.
The resolution has two parts. Expand the estimation error: the average of the centered score at the true nuisances, which is the good part, plus terms from the errors in the fitted nuisances. The doubly robust score has a special property, Neyman orthogonality: its derivative with respect to the nuisances is zero, so small errors in them have no first-order effect. What remains is roughly the product of the outcome model's error and the propensity model's error. If each converges faster than n to the minus a quarter, much slower than a parametric model's n to the minus a half, their product is negligible, and, with overlap, suitable moments and the other regularity conditions, the estimate has the same first-order behavior as if the nuisances were known. Part 49 proves this.
The second part is cross-fitting. Split the data in two. Fit the outcome regressions and the propensity score on the second half, and evaluate each patient's score on the first half. Then swap the halves, and average all the scores. No patient's score uses a nuisance model trained on that patient. This removes direct reuse of its outcome in nuisance fitting; finite-sample bias and nuisance approximation error can still remain. Victor Chernozhukov and six colleagues set out this double, or debiased, machine learning in 2018; it works with any learner fast enough.
A test with nonlinear confounding. Five uniform covariates and a thousand patients. The chance of treatment depends on a sine of a product and a parabola. The untreated outcome is Friedman's function from Part 34, sharing those shapes. The effect varies, with an average of three.
A hundred and fifty simulated studies. Linear regression adjustment is biased by over one, and its intervals never cover the truth. The doubly robust estimator with random forests fitted to all the data is biased by more than half a point, and its standard errors are too small: it never covers either. The same estimator with cross-fitting has a small bias, standard errors that match its estimated sampling variability, and covers percent of the time.
When the effect is assumed constant, the same ideas give the partially linear model. Peter Robinson showed in 1988 that one can regress the outcome's residual from its prediction given X on the treatment's residual from its prediction given X. It is Part 12's Frisch–Waugh–Lovell theorem with machine-learned residuals, cross-fitted. Next, effects that are allowed to differ from one person to the next.
Numbers: 88.0% vs 0%
11Heterogeneous effectsMaster's5 min
An average effect may hide large differences between people. The conditional average effect asks for the average effect among patients with covariates x. In a randomized trial, or under unconfoundedness, it is the difference of two regression functions. It is still an average: individual effects, and the share of people harmed, remain out of reach, as Part 35 showed. In the World's trial we know the systematic part of each patient's effect: it grows with their true pressure and their age. We grade predictions against that latent systematic effect. The learners observe noisy recorded pressure, so this benchmark is not exactly the conditional average effect given their recorded covariates.
The meta-learners build effect estimates from any regression method. The T-learner fits one model per arm and subtracts. The S-learner fits a single model with treatment as a feature, which a regularized learner may simply ignore. The X-learner of Sören Künzel and colleagues imputes each patient's effect using the other arm's model, then regresses those imputed effects on x. Edward Kennedy's DR-learner regresses the doubly robust scores of chapter nine on x.
The causal forest of Stefan Wager and Susan Athey is built for the purpose. First centre the outcome and the treatment by their predicted values from ordinary forests. Then grow trees that split, not where the outcome changes, but where the effect changes: each split maximizes the difference between the children's effect estimates, each a residual-on-residual slope. The trees are honest: one half of each subsample chooses the splits and the other half estimates the leaves, which separates split selection from leaf estimation in the ideal honest design. Our teaching implementation also uses globally fitted out-of-bag centering models, so this does not establish the full theoretical honesty conditions. Average many such trees, Wager and Athey proved asymptotic normality for forests satisfying their subsampling, regularity and honesty conditions. We illustrate point predictions here, rather than certify those confidence-interval conditions.
Train each method on the trial's two thousand patients, and grade its predictions on two thousand other eligible islanders, against the World's latent systematic effect on patients excluded from training. This includes noise from observing recorded rather than true pressure. Giving everyone the trial's average effect has an error of millimetres, partly because the islanders are older than the trial. The T-learner does a little better, and the DR-learner, whose pseudo-outcomes are very noisy at this sample size, does worse. The X-learner and the causal forest cut the error of the constant by about two fifths. And a linear model with treatment interactions does best of all, because the latent systematic effect is linear in true pressure and age. Recorded pressure is noisy, so this is only an approximate observed-covariate model. Flexible methods pay for their flexibility in variance.
A more useful check for decisions: sort the islanders into ten groups by predicted effect, and compare each group's average prediction with its true average effect. The causal forest, the T-learner, and the linear model. Their decile averages show useful ranking in this example. But the causal forest is too timid, predicting too little benefit for those who gain most, the averaging bias of Part 34; the T-learner is too bold, mistaking the noise of two separate fits for heterogeneity; the linear model tracks the diagonal more closely.
Some cautions. Heterogeneity discovered by searching is Part 33's multiplicity problem in new clothes. It should be tested, for instance by checking whether the predicted effects predict differences in actual outcomes, as Chernozhukov and colleagues' best-linear-predictor tests do. When used for decisions, the target is a treatment rule: treat when the predicted benefit exceeds the cost, as in Athey and Wager's policy learning. And recall the subgroup chapter of Part 35: most claimed differences between subgroups are noise. Part 62 returns to all this.
Numbers: latent-effect RMSE 4.35 → 2.76 (forest), 1.20 (linear)
12Sensitivity analysisPractice5 min
Return to the World's study, but now let the doctors also judge each patient's frailty, which no data set records. Frail patients are treated more often, and their pressure would be higher anyway. Adjusting for the four recorded covariates gives minus , with a small standard error. The truth is minus ; had frailty been measured, adjusting for it would have given minus . The observed data alone do not generally identify this hidden-confounding bias. What we can do is ask how strong an unmeasured confounder would have to be to change the conclusion.
Paul Rosenbaum's approach starts from matched pairs. If there is no hidden bias, the two members of a pair, alike on the measured covariates, were equally likely to be the treated one: a coin within each pair. Hidden bias of size gamma allows their odds of treatment to differ by up to a factor gamma, because of something unmeasured. For each gamma, compute a worst-case one-sided signed-rank tail probability under the sharp null and the matched-pair assignment model. We compute the signed-rank tail by exact dynamic programming over independent pair signs, including average-rank ties. The smallest gamma that makes the effect insignificant summarizes how robust the finding is.
In the World's frailty study, we form disjoint pairs without reusing controls, using a caliper on the estimated logit propensity score. Unmatched treated patients are omitted. the matched estimate is minus . The displayed gamma threshold describes loss of significance for this matched sample under the sensitivity model. Approximate matching also leaves some measured-covariate imbalance. The simulator tells us that the average effect is negative despite substantial bias in its estimated size. The sensitivity threshold alone does not establish the actual confounder's strength, identify the causal sign, or bound all estimation bias.
For risk ratios, Tyler VanderWeele and Peng Ding proposed in 2017 a number that is easy to report. Given an observed risk ratio, the E-value is the risk ratio plus the square root of the risk ratio times the risk ratio minus one. The E-value is an equal-strength threshold: if both sensitivity associations are below E, this confounding bound cannot explain the association. One association can be smaller than E if the other is sufficiently larger. Their trade-off is the product divided by the sum minus one, under the specified risk-ratio sensitivity model. For a risk ratio of two, the equal-strength threshold is three point four one. An association of ten on one side and three on the other can also exceed the required bias factor.
For regression estimates, Carlos Cinelli and Chad Hazlett described a confounder by two partial R-squared values: how much of the treatment's variation it explains, and how much of the outcome's, beyond what is measured. The omitted-variable bias is then bounded exactly by a formula in the standard error, the degrees of freedom and those two numbers. Their robustness value is the common partial R-squared a confounder would need with both to erase the estimate entirely, computable from the t statistic alone. And it can be benchmarked: compare it with how much the strongest measured covariate explains.
In the frailty study, the adjusted estimate has a t statistic of about minus twenty. Its robustness value is : a confounder explaining thirty percent of the residual variation in both treatment and outcome would be needed to erase it. The actual frailty explains about nine percent of each. That is far below thirty, so this particular measured-in-the-simulator frailty does not erase the adjusted regression coefficient; but it is large enough to bias the estimate by over a quarter, and a full sensitivity analysis would plot the bias for every pair of R-squared values, not just report one number.
The lesson is to report an observational estimate with its sensitivity analysis, never alone. An early formal sensitivity analysis was Jerome Cornfield's, in 1959, in the case where it mattered most.
Numbers: Γ* ≈ 2.8; RV 0.30
13Smoking and lung cancerBachelor's4 min
In 1950 Richard Doll and Austin Bradford Hill interviewed patients in London hospitals, comparing those with lung cancer with patients admitted for other diseases. Of six hundred and forty-nine men with lung cancer, six hundred and forty-seven were smokers. Of six hundred and forty-nine men with other diseases, six hundred and twenty-two. Almost everyone smoked, but the difference was decisive: an odds ratio of about fourteen, and the risk climbed steadily with the amount smoked. Ernst Wynder and Evarts Graham published similar findings in America the same year.
A comparison of hospital patients could be biased by who is admitted, who is asked, and how they remember their habits; Berkson's warning from chapter three applies. So in 1951 Doll and Hill wrote to every doctor in Britain, asking about their smoking. About forty thousand doctors initially responded. The landmark fifty-year analysis followed thirty-four thousand four hundred and thirty-nine male British doctors. Deaths from lung cancer rose with the number of cigarettes smoked, and doctors who stopped had lower risks than those who continued.
The most famous dissent came from Fisher. Correlation, he wrote in 1957 and 1958, is not causation; perhaps an inherited constitution makes some people both crave tobacco and develop cancer. He cited twin studies showing that identical twins are more alike in their smoking than fraternal twins, so smoking is partly heritable. Fisher was right that such a confounder was possible; no observational study can rule it out. The question was whether it was plausible, and that is a question sensitivity analysis can answer. Fisher, it should be said, was also a smoker and a consultant to the tobacco industry.
Jerome Cornfield and five colleagues answered in 1959. Smokers' risk of dying of lung cancer was about nine times that of non-smokers. If a hidden factor explained all of it, they showed that a binary confounder fully explaining that association would have to be at least nine times as prevalent among smokers under their model. For heavy smokers, whose risks were higher still, it would have to be more lopsided still. No known inherited trait is distributed so unevenly between smokers and non-smokers. In modern terms, the E-value of a risk ratio of nine is about . Cornfield's inequality was an early formal sensitivity analysis and one part of a much broader accumulation of causal evidence.
In 1965 Bradford Hill listed the considerations that had persuaded him. Strength of association; consistency across studies; specificity; temporality, the cause preceding the effect; a biological gradient, more exposure, more disease; plausibility; coherence with other knowledge; experimental evidence, such as the fall in risk after stopping; and analogy. He called them viewpoints, not criteria, and wrote that none of them could bring indisputable evidence on its own. Strength is Cornfield's argument; the gradient and the effect of stopping are the closest an observational study comes to an experiment.
Assigning people to prolonged harmful smoking exposure is not an ethical way to establish this causal effect. Smoking-cessation interventions can, and do, use randomized trials. The case was made by triangulation: case-control and cohort studies in many countries, a dose-response gradient, the benefit of stopping, and Cornfield's argument that no plausible confounder could explain it. In 1964 the United States Surgeon General's report concluded that cigarette smoking causes lung cancer. Next, treatments that are not a single decision but a sequence of them.
Numbers: 647/649 vs 622/649; E = 17.5
14Time-varying treatmentsMaster's3 min
Many treatments are not one decision but a sequence: HIV drugs adjusted to the latest viral load, insulin to the latest blood sugar. Here is the smallest example. A treatment at time zero. A health measure at time one, which the first treatment improves. A second treatment, chosen by doctors according to that health measure. And an unmeasured patient characteristic that affects both the health measure and the final outcome. We want the effect of always treating against never treating.
Here is the dilemma that Robins identified in 1986. The health measure confounds the second treatment: it causes both the treatment and the outcome, so we must adjust for it. But it is also a mediator of the first treatment, part of the way the first dose works, so we must not. Worse, it is a collider on the path from the first treatment through the health measure, back through the unmeasured characteristic, to the outcome; adjusting opens that path. Neither naive treatment-only regression nor interpreting coefficients after ordinary adjustment for the health measure identifies the total regime effect here. Outcome regression remains useful inside the longitudinal g-formula.
Robins's solutions model the potential outcomes directly. A marginal structural model says how the average outcome under each treatment sequence depends on the sequence. Weight each patient by the inverse probability of the second treatment they received, given their health measure, stabilized by its probability without that information. With sequential exchangeability, positivity and a correct treatment model, weighting removes the health measure's influence on the second treatment in the target pseudo-population. In this simulation the numerator uses the marginal second-treatment probability. Then regress the outcome on the two treatments alone, with those weights, without adjusting for the health measure. Or use the g-formula: model the outcome given the whole history, and average over how the health measure would evolve under each sequence.
Two hundred thousand simulated patients. The truth, always against never treating, is minus seven. Regressing the outcome on the two treatments gives minus , because the second treatment goes to the sicker patients. Adding the health measure makes it worse, minus , for the reasons just given. The weighted marginal structural model gives minus , and the g-formula minus . The stabilized weights average one, as they should.
These tools are now organized by a discipline Miguel Hernán and Robins called target-trial emulation, in 2016. First write the protocol of the randomized trial you would run if you could: who is eligible, which treatment strategies are compared, when follow-up starts, what outcome is counted. Then emulate that trial with observational data, making sure that eligibility, treatment assignment and the start of follow-up line up, as they would in a trial. Many famous failures of observational studies came from misaligning them, such as counting time before treatment started as treated time. Aligning treatment initiation and follow-up helped explain important differences between observational and randomized hormone-therapy findings.
Numbers: −2.57 vs −7.04 (truth −7)
15LaLonde revisitedPractice3 min
Return to LaLonde's trainees and the survey men, with a teaching propensity model inspired by Dehejia and Wahba: age, education and their squares, race, marriage, degree, and earnings in 1974 and 1975 with indicators for zero earnings. Two thirds of the survey men have a propensity below a tenth: nothing like the trainees. Three quarters of the trainees have a propensity above a half. The comparison rests on a minority of the survey men, and, within the overlap, on a few who resemble the trainees closely.
The experiment says about eighteen hundred dollars. Against the survey men, the raw difference is negative. Regression with the covariates, and regression used to predict what the trainees would have earned, give fifteen to sixteen hundred. Propensity-score matching with one neighbour gives about four hundred; weighting, about thirteen hundred, or fifteen hundred when restricted to the overlap; five strata on the overlap, about five hundred. Every one of these is a textbook method, applied as the textbooks say, and they span more than a thousand dollars, a substantial fraction of the experimental confidence interval's width. The methods also differ in extrapolation and, after trimming, their target populations.
As a picture, with the experiment's ninety-five percent interval as the green band. All but one of the adjusted estimates land inside it, which is better than LaLonde's original methods managed, and matching falls just below; but they still differ materially, and a researcher with only the survey data would have no way of knowing which to trust.
Guido Imbens and Yiqing Xu, revisiting the data in 2024, stressed a check that needs no experiment: a placebo test. Treat earnings in 1975, before the programme, as if they were the outcome, using only earlier information. The programme cannot have affected them, so a valid method should find nothing. In the experiment the difference is a couple of hundred dollars, noise; matched against the survey men, minus a hundred and forty. These small point contrasts are diagnostic rather than formal pass results; no placebo interval has been computed. A reassuring placebo does not establish exchangeability for later earnings: the selection into the programme happened after 1975, when the men chose to enrol, and no pre-programme check can see that.
The lessons that forty years of re-analysis drew. First, check overlap before estimating anything: most of the survey men should never have been in the comparison. Second, outcomes measured before treatment, here earlier earnings, are the most important covariates of all; without them, the methods fail badly. Third, overlap improves the basis for comparisons, but does not guarantee estimator agreement or remove hidden confounding. Poor overlap makes estimates particularly dependent on extrapolation. And fourth, unconfoundedness is a claim about the world: test what can be tested, with placebos, and bound the rest, with sensitivity analysis.
Numbers: $428 to $1,648
Recap, problems, and the road aheadAll tracks3 min
Part thirty-six in twelve lines. LaLonde showed that non-experimental methods could miss an experimental answer, and forty years later the lesson is that overlap and pre-treatment outcomes decide more than methods do. Without a coin we need unconfoundedness and overlap. Causal diagrams make the assumptions explicit, and chains, forks and colliders say which paths carry association. The back-door criterion says what to adjust for, and Berkson's bias, M-bias and mediators what not to. The front door and the do-calculus identify effects beyond adjustment. Simpson's paradox is resolved by the graph, not the numbers. g-computation models the outcome, propensity scores model the treatment, and weighting builds a pseudo-trial at the price of extreme weights. Doubly robust estimation gives two chances to be right, but not with both models wrong. Double machine learning makes flexible models honest by orthogonality and cross-fitting. Meta-learners and causal forests estimate effects that vary. And sensitivity analysis, from Cornfield's smoking argument to E-values, with marginal structural models and target trials for treatments over time, completes the toolkit.
A promise for later. This part identified causal effects from observational data under unconfoundedness and overlap. It assumed that every confounder was measured, which can never be tested. Part 37 looks for natural experiments, situations where nature, a lottery or a rule assigns treatment as if at random: instrumental variables, regression discontinuities, differences-in-differences and synthetic controls.
Where it comes back. Part 37 finds natural experiments. Part 40 asks causal questions about survival. Part 41 applies the same weighting and doubly robust ideas to missing data. Part 49 derives the efficient influence functions behind AIPW and DML. Part 52 handles thousands of confounders. Part 60 treats distribution shift as a transport problem. Part 62 covers mediation, heterogeneous effects and discovering causal graphs from data. And Part 63 asks what counterfactual fairness means.
Six problems, with full solutions in the README. The balancing property of the propensity score; unconfoundedness given the score; the unbiasedness of weighting; double robustness; the M-graph; and the E-value formula. Pause here if you want to try them.
The books this part follows: Hernán and Robins's Causal Inference: What If; Pearl's Causality and his primer with Glymour and Jewell; Imbens and Rubin, and Rosenbaum's Observational Studies; and Stefan Wager's statistical learning approach; with the papers from Cornfield to Imbens and Xu.
Thirty-six parts of sixty-five. We can estimate causes without experiments, if we measure enough, and say how wrong we might be if we did not. But sometimes we can do better: nature, a lottery or an arbitrary rule may have flipped the coin for us. Part 37: natural experiments.
Where it goes next. Natural experiments (instruments, discontinuities, difference-in-differences, synthetic control) follow in Part 37; the same weighting and doubly robust tools handle missing data in Part 41; efficient influence functions, the theory behind AIPW and DML, are in Part 49; mediation, heterogeneity and causal discovery in Part 62.
Key results
The part's results in one place, for revision.
Try it
Lab 36 · Double robustness: two chances to be right
Simulate an observational study in which treatment and outcome both depend on x squared, and estimate the average effect (truth 2) by outcome regression, by weighting and by AIPW, with each nuisance model either right (it uses x squared) or wrong (linear in x), three hundred times each.
python -m videos.stats.labs 36
needs numpy, scipy, matplotlib · download lab36.py ·
source on GitHubdifference in means, no adjustment: bias +2.95 (truth 2.0)
both right: bias outcome model +0.00 IPW +0.00 AIPW -0.00 (AIPW 90% interval covers 91%)
outcome right, propensity wrong: bias outcome model +0.00 IPW +2.95 AIPW +0.00 (AIPW 90% interval covers 89%)
outcome wrong, propensity right: bias outcome model +2.95 IPW +0.00 AIPW +0.00 (AIPW 90% interval covers 100%)
both wrong: bias outcome model +2.95 IPW +2.95 AIPW +2.95 (AIPW 90% interval covers 0%)
AIPW's error is a product of the two models' errors: it vanishes if either the outcome model or the propensity model is right, and with both wrong it is as biased as the comparison nobody adjusted.
The code (90 lines; it asserts its own result)
"""Lab 36: give the doubly robust estimator one wrong model, then two, and watch where its two chances run out."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import causal
TITLE = "Double robustness: two chances to be right"
GOAL = ("Simulate an observational study in which treatment and outcome both depend on x squared, and estimate the "
"average effect (truth 2) by outcome regression, by weighting and by AIPW, with each nuisance model either "
"right (it uses x squared) or wrong (linear in x), three hundred times each.")
TASKS = [
"Raise the confounding from 0.8 to 2 so some propensities approach 1. What happens to IPW's largest weight and RMSE, and to AIPW's?",
"Use causal.dml_ate with a flexible learner of your own (for example a k-nearest-neighbour mean) for both nuisances, cross-fitted.",
"Add an unmeasured confounder u to both the treatment and the outcome models. Which of the twelve cells stays unbiased?",
]
TAU, N, CONF = 2.0, 1000, 0.8
def study(rng):
x = rng.uniform(-2, 2, N)
e = 1 / (1 + np.exp(-CONF * (x ** 2 - 1.3))) # doctors treat the extremes more often
t = rng.random(N) < e
y = TAU * t + 3 * x ** 2 + rng.standard_normal(N)
return x, t, y
def estimates(x, t, y, out_right, ps_right):
feats = lambda ok: np.column_stack([x, x ** 2]) if ok else x[:, None] # noqa: E731
D = np.column_stack([np.ones(N), feats(out_right)])
mu1 = D @ np.linalg.lstsq(D[t], y[t], rcond=None)[0]
mu0 = D @ np.linalg.lstsq(D[~t], y[~t], rcond=None)[0]
ps = causal.propensity(feats(ps_right), t.astype(float))
a = causal.aipw(y, t, mu0, mu1, ps)
return float(np.mean(mu1 - mu0)), causal.ipw(y, t, ps)["est"], a["est"], a["lo"] <= TAU <= a["hi"]
def run(seed=0):
rng = np.random.default_rng(seed)
reps = 300
lab = labs.Lab()
cases = [(True, True), (True, False), (False, True), (False, False)]
names = {(True, True): "both right", (True, False): "outcome right, propensity wrong",
(False, True): "outcome wrong, propensity right", (False, False): "both wrong"}
res = {c: [] for c in cases}
naive = []
for _ in range(reps):
x, t, y = study(rng)
naive.append(y[t].mean() - y[~t].mean())
for c in cases:
res[c].append(estimates(x, t, y, *c))
res = {c: np.array(v) for c, v in res.items()}
bias = {c: res[c][:, :3].mean(0) - TAU for c in cases}
lab.row("difference in means, no adjustment: bias", f"{np.mean(naive) - TAU:+.2f} (truth {TAU})")
for c in cases:
b = bias[c]
lab.row(f"{names[c]}: bias", f"outcome model {b[0]:+.2f} IPW {b[1]:+.2f} AIPW {b[2]:+.2f} "
f"(AIPW 90% interval covers {res[c][:, 3].mean():.0%})")
se = {c: res[c][:, 2].std(ddof=1) / np.sqrt(reps) for c in cases}
for c in cases[:3]:
assert abs(bias[c][2]) < max(0.03, 4 * se[c]), f"AIPW is consistent with {names[c]}"
assert abs(bias[(True, False)][1]) > 0.5 and abs(bias[(False, True)][0]) > 0.5, "each single method fails with its model wrong"
assert abs(bias[(False, False)][2]) > 0.5, "with both models wrong nothing is left"
assert 0.84 < res[(True, True)][:, 3].mean() < 0.96, "influence-function interval with both models right"
assert abs(np.mean(naive) - TAU) > 0.5
lab.note = ("AIPW's error is a product of the two models' errors: it vanishes if either the outcome model or the "
"propensity model is right, and with both wrong it is as biased as the comparison nobody adjusted.")
fig, ax = labs.figure(2, size=(11, 4.2))
x, t, y = study(np.random.default_rng(seed + 1))
ax[0].scatter(x[~t], y[~t], s=6, color=labs.BLUE, alpha=0.5, label="untreated")
ax[0].scatter(x[t], y[t], s=6, color=labs.GOLD, alpha=0.5, label="treated")
g = np.linspace(-2, 2, 100)
ax[0].plot(g, 3 * g ** 2, color=labs.BLUE)
ax[0].plot(g, 3 * g ** 2 + TAU, color=labs.GOLD)
ax[0].set(title="One study: the treated sit at the extremes of x", xlabel="x", ylabel="outcome y")
ax[0].legend(loc="upper center")
w = 0.25
pos = np.arange(4)
for j, (lbl, col) in enumerate((("outcome model", labs.BLUE), ("IPW", labs.ORANGE), ("AIPW", labs.GREEN))):
ax[1].bar(pos + (j - 1) * w, [bias[c][j] for c in cases], w, color=col, label=lbl)
ax[1].axhline(np.mean(naive) - TAU, color=labs.RED, ls="--", label="no adjustment")
ax[1].axhline(0, color=labs.MUTED, lw=1)
ax[1].set_xticks(pos)
ax[1].set_xticklabels(["both right", "outcome right,\npropensity\nwrong", "outcome wrong,\npropensity\nright", "both wrong"])
ax[1].set(title="Bias of each estimator over 300 studies (truth 2)", ylabel="mean estimate minus truth", ylim=(-0.3, 4.4))
ax[1].legend(loc="upper left", ncol=2)
lab.fig = fig
return lab
Now change it
- Raise the confounding from 0.8 to 2 so some propensities approach 1. What happens to IPW's largest weight and RMSE, and to AIPW's?
- Use causal.dml_ate with a flexible learner of your own (for example a k-nearest-neighbour mean) for both nuisances, cross-fitted.
- Add an unmeasured confounder u to both the treatment and the outcome models. Which of the twelve cells stays unbiased?
Problems, with solutions
Try each problem before opening its solution.
-
Balancing. Prove that \(e(X)\) is a balancing score: \(X \perp\!\!\!\perp T \mid e(X)\).
Solution
P(T = 1 | X, e(X)) = P(T = 1 | X) = e(X), which depends on X only through e(X).
- So P(T = 1 | X, e(X)) = P(T = 1 | e(X)), i.e. T ⊥ X | e(X).
-
Unconfoundedness given the score. Show that unconfoundedness given \(X\) implies unconfoundedness given \(e(X)\).
Solution
P(T = 1 | Y(0), Y(1), e(X)) = E[P(T = 1 | Y(0), Y(1), X) | Y(0), Y(1), e(X)].
- By unconfoundedness the inner probability is e(X), so this is E[e(X) | Y(0), Y(1), e(X)] = e(X), free of the potential outcomes.
-
IPW. Show that \(E[TY/e(X)] = E[Y(1)]\) under unconfoundedness and overlap.
Solution
E[TY/e(X)] = E[E[T Y(1) | X]/e(X)] = E[E[T | X] E[Y(1) | X]/e(X)] = E[Y(1)].
- The middle step uses consistency and unconfoundedness, and the division needs overlap.
-
Double robustness. Show that the AIPW estimator is consistent if either \(\mu_t\) or \(e\) is correct.
Solution
Write the AIPW term for Y(1) as μ₁(X) + T(Y − μ₁(X))/e(X), and take its expectation given X: μ₁ + e₀(X)(m₁(X) − μ₁(X))/e(X), where m₁ = E[Y(1) | X] and e₀ is the true propensity.
- If μ₁ = m₁, the correction is zero, so the mean is m₁ for any e.
- If e = e₀, the result is μ₁ + m₁ − μ₁ = m₁ for any μ₁.
- Averaging over X gives E[Y(1)] either way for fixed limiting nuisance functions satisfying overlap and integrability. Plug-in estimated nuisances need convergence and inference conditions; this is not a finite-sample unbiasedness proof.
-
M-bias. In the M-graph \(T \leftarrow A \to M \leftarrow B \to Y\), \(T \to Y\), show adjusting for \(M\) alone violates the back-door criterion.
Solution
- With Z = {M}, the path T ← A → M ← B → Y has the collider M in Z, so it is open.
- It begins with an arrow into T, so it is an open back-door path, and the criterion fails.
- Adding A blocks it, since A is a non-collider in Z.
-
E-value. Derive the E-value: show \(RR + \sqrt{RR(RR - 1)}\) solves \(\frac{E^2}{2E - 1} = RR\).
Solution
- VanderWeele & Ding's bound: a confounder with risk ratios RR_UT and RR_UY can shift an observed RR by at most B = RR_UT RR_UY/(RR_UT + RR_UY − 1).
- Set both equal to E and require B = RR: E²/(2E − 1) = RR, so E² − 2RR·E + RR = 0, and E = RR + √(RR² − RR).
- This is the equal-strength threshold. For RR = 2, E ≈ 3.414, but associations 10 and 3 give B = 2.5: one association may be below E if the other is larger.
Notes and sources
Where it comes back
- Part 37: natural experiments: instruments, regression discontinuity, difference-in-differences, synthetic control.
- Part 40: causal survival analysis.
- Part 41: missing data with the same weighting and doubly robust tools.
- Part 49: efficient influence functions; the theory behind AIPW and DML.
- Part 52: high-dimensional confounding.
- Part 60: distribution shift as transport.
- Part 62: mediation, heterogeneity, causal discovery.
- Part 63: counterfactual fairness.
Glossary
- Unconfoundedness (ignorability): (Y(0), Y(1)) ⊥ T | X. Overlap (positivity): 0 < e(x) < 1.
- DAG; d-separation: a causal graph; the graphical test for conditional independence.
- Back-door / front-door criterion: graphical conditions under which adjustment or the front-door formula identifies an effect.
- Collider; Berkson's bias; M-bias: a node with two arrows in; the association created by conditioning on one.
- do-calculus: Pearl's three rules for rewriting interventional quantities.
- g-computation (g-formula): estimating E[Y(t)] by averaging fitted outcome models.
- Propensity score: e(x) = P(T = 1 | X = x); a balancing score.
- IPW: weighting by 1/e or 1/(1 − e); Hajek normalizes the weights.
- AIPW / doubly robust: consistent if either nuisance model is right, under overlap and regularity; valid efficient inference requires additional conditions.
- DML: cross-fitted machine-learned nuisances in an orthogonal score.
- CATE; meta-learners; causal forest: E[Y(1)−Y(0) | X]; generic recipes; effect-splitting forests. The latent World benchmark is distinguished from recorded-covariate CATE.
- Rosenbaum's Γ; E-value; robustness value: three scales for how strong hidden confounding must be to change a conclusion.
- MSM; stabilized weights; target trial: models for potential outcomes under treatment sequences; their weights; the protocol an observational analysis emulates.
Sources
- LaLonde.
- R. LaLonde, AER 76 (1986); R. Dehejia & S. Wahba, JASA 94 (1999); J. Smith & P. Todd, J. Econometrics 125 (2005).
- G. Imbens & Y. Xu, LaLonde (1986) after nearly four decades (2024).
- Identification.
- P. Rosenbaum & D. Rubin, Biometrika 70 (1983); S. Wright, J. Agric. Res. 20 (1921).
- J. Pearl, Biometrika 82 (1995), Causality (2000; 2009).
- T. Verma & J. Pearl (1988); D. Geiger, T. Verma & J. Pearl, Networks 20 (1990).
- J. Berkson, Biometrics Bull. 2 (1946); T. VanderWeele & I. Shpitser, Biometrics 67 (2011).
- I. Shpitser & J. Pearl, AAAI (2006); Y. Huang & M. Valtorta, UAI (2006); T. Richardson & J. Robins (2013).
- Estimation.
- J. Robins, Math. Modelling 7 (1986); W. Cochran, Biometrics 24 (1968); D. Rubin, Ann. Appl. Stat. 2 (2008).
- D. Horvitz & D. Thompson, JASA 47 (1952); R. Crump, V. J. Hotz, G. Imbens & O. Mitnik, Biometrika 96 (2009); F. Li, K. Morgan & A. Zaslavsky, JASA 113 (2018).
- J. Robins, A. Rotnitzky & L. P. Zhao, JASA 89 (1994); J. Kang & J. Schafer, Stat. Sci. 22 (2007); M. van der Laan & D. Rubin (2006).
- V. Chernozhukov, D. Chetverikov, M. Demirer, E. Duflo, C. Hansen, W. Newey & J. Robins, Econometrics J. 21 (2018); P. Robinson, Econometrica 56 (1988).
- Heterogeneity.
- S. Künzel, J. Sekhon, P. Bickel & B. Yu, PNAS 116 (2019); E. Kennedy, EJS 17 (2023).
- S. Athey & G. Imbens, PNAS 113 (2016); S. Wager & S. Athey, JASA 113 (2018); S. Athey, J. Tibshirani & S. Wager, Ann. Stat. 47 (2019); S. Athey & S. Wager, Econometrica 89 (2021).
- Sensitivity.
- J. Cornfield, W. Haenszel, E. Hammond, A. Lilienfeld, M. Shimkin & E. Wynder, JNCI 22 (1959).
- P. Rosenbaum, Biometrika 74 (1987), Observational Studies (2002).
- T. VanderWeele & P. Ding, Ann. Intern. Med. 167 (2017); C. Cinelli & C. Hazlett, JRSS B 82 (2020).
- Smoking.
- R. Doll & A. B. Hill, BMJ (1950, 1954); E. Wynder & E. Graham, JAMA 143 (1950).
- R. A. Fisher, BMJ (1957), Nature 182 (1958); A. B. Hill, Proc. R. Soc. Med. 58 (1965); US Surgeon General (1964).
- Time-varying.
- J. Robins, M. Hernán & B. Brumback, Epidemiology 11 (2000); M. Hernán & J. Robins, Am. J. Epidemiol. 183 (2016).
- M. Hernán et al., Epidemiology 19 (2008).
- Data. NSW via R's Matching (Sekhon) and MatchIt (Ho, Imai, King & Stuart).
About this partfrom its README
Part 36 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the sixteenth part of Stage III, Master's. Part 35 showed why randomization identifies causal effects. This part asks what can be learned without it, and at what cost in assumptions:
- identification: unconfoundedness and overlap, causal diagrams, the back door, the front door and the do-calculus;
- estimation: g-computation, propensity scores, weighting, double robustness, double machine learning;
- heterogeneous effects;
- sensitivity analysis;
- smoking and lung cancer;
- time-varying treatments.
The part builds statkit.causal (II) and an instrument, the causal graph (CausalGraph): nodes, arrows, highlighted
paths and conditioning boxes, backed by the kit's DAG with d-separation and the back-door criterion. Its real data are
the NSW job-training data (LaLonde 1986; Dehejia & Wahba 1999), from R's Matching (GPL-3) and MatchIt (GPL ≥ 2)
packages. Its test bed is an observational version of the World's clinic, in which doctors choose who is treated and
the World knows both potential outcomes.
It opens with a teaching comparison following LaLonde's (1986) strategy. The 429 MatchIt comparison men are not the original paper's complete PSID sample or specification; the experimental estimate has its own sampling uncertainty. In Dehejia & Wahba's subsample (185 trainees, 260 randomized controls):
- the experiment estimates $1,794 (95% CI $479 to $3,109);
- against 429 PSID men, the raw difference is −$635, and OLS with covariates gives $1,548;
- the PSID men are older (28.0 vs 25.8), more often married (0.51 vs 0.19), less often black (0.20 vs 0.84), and earned $5,619 vs $2,096 in 1974.
From there the part covers:
-
Unconfoundedness and overlap.
- Strong ignorability (Rosenbaum & Rubin 1983) and the adjustment formula.
- The World's observational study: 3,000 eligible patients, 47% treated by doctors on baseline pressure, age and BMI. The ATE is −10.02 and the ATT −12.26; the naive estimate is −1.38. The propensity histograms diagnose practical support; finite samples cannot establish positivity everywhere.
-
Causal diagrams.
- Wright (1921); Pearl.
- Chains, forks and colliders; d-separation (Verma & Pearl; Geiger et al.).
- Back-door paths with an unmeasured frailty.
-
The back door.
- The back-door criterion and adjustment.
- Berkson's bias: the correlation of two independent diseases is 0.00 overall and −0.56 among the admitted.
- M-bias: the truth is 1.00; the unadjusted estimate is 0.99, adjusting for M gives 0.16, and for M and A 1.00.
- A mediator: the total effect is 2.00; adjusting for the mediator gives the direct 1.01.
- The disjunctive cause criterion (VanderWeele & Shpitser 2011), assuming some subset of measured pre-treatment variables suffices to control confounding.
-
The front door and do-calculus.
- Fisher's genotype as a graph. Naive 0.235, truth 0.1275, front door 0.129.
- The three rules and their completeness for identifying intervention distributions in the assumed nonparametric causal graph model (Shpitser & Pearl; Huang & Valtorta 2006); SWIGs (Richardson & Robins 2013).
-
Simpson resolved.
- The World's clinic: +7.7 (mild) and +8.1 (severe) points within strata, −11.2 overall. Back-door adjustment gives +7.8.
- With a mediator instead, the same numbers call for no adjustment.
-
g-computation (Robins 1986). −10.35 vs truth −10.02; extrapolation where overlap is thin.
-
Propensity scores.
- The balancing property.
- Nearest-neighbour matching with replacement (ATT −12.43 vs −12.26). Reused controls make pair differences dependent; uncertainty must account for reuse.
- Cochran's (1968) five strata: −8.59, removing 83% of the naive bias.
- Design trumps analysis (Rubin 2008).
-
Weighting.
- Horvitz–Thompson and Hajek IPW, and the ATT weights.
- Balance: the baseline-pressure SMD goes from 1.37 to 0.18 and age from 0.85 to 0.08.
- IPW gives −8.48 [−9.5, −7.5]. The largest weight is 36, and the effective sample sizes are 742 and 662.
- Trimming (Crump et al. 2009), truncation, overlap weights (Li, Morgan & Zaslavsky 2018): treated weight 1−e, control weight e, targeting the density tilt e(1−e). Exact included-covariate mean balance requires a converged unpenalized logistic fit.
-
Double robustness (Robins, Rotnitzky & Zhao 1994). AIPW gives −9.91 [−10.6, −9.2], with SE 0.44 against IPW's 0.63. Kang & Schafer (2007), 1,000 samples of 1,000:
Estimator Bias RMSE 90% coverage outcome model, wrong −0.85 1.73 IPW, wrong 4.88 12.5 AIPW, propensity right 0.04 1.66 91.9% AIPW, outcome right 0.03 2.24 90.8% AIPW, both wrong −21.5 202 55.9% The largest single weight is 39,667. These are seeded adaptations of the Kang–Schafer design. Double robustness gives consistency under nuisance-model conditions, not finite-sample unbiasedness or automatically valid confidence intervals when just one nuisance is correct.
-
Double machine learning (Chernozhukov et al. 2018).
-
Neyman orthogonality; the product-rate condition; cross-fitting. The efficient influence function is the true AIPW score minus the target. Overlap, moment and nuisance-rate regularity are also required. Cross-fitting removes direct own-outcome reuse, not all finite-sample bias.
-
Nonlinear confounding with n = 1,000 and ATE 3, 150 studies:
Estimator Bias Mean SE 90% coverage linear OLS 1.12 0% forest AIPW, no cross-fitting 0.58 0.087 0% DML, cross-fitted 0.08 0.187 88.0% -
The partially linear model (Robinson 1988).
-
-
Heterogeneous effects.
-
T-, S-, X- (Künzel et al. 2019) and DR-learners (Kennedy 2023); the causal forest (Wager & Athey 2018; Athey, Tibshirani & Wager 2019) with local centring and separate splitting/estimation halves. This teaching forest does not certify the full honest-forest inference theorem; shared nuisance fitting can still couple the halves.
-
The World's trial, graded on 2,000 islanders excluded from training, against the latent systematic effect τ = −(9 + 0.3(true sbp − 150) + 0.08(age − 60)). Learners observe noisy recorded pressure, so this benchmark is not exactly E[τ | recorded X]. RMSE:
Estimator RMSE constant ATE 4.35 T-learner 3.50 DR-learner 4.57 X-learner 2.62 causal forest 2.76 linear, interacted 1.20 -
Decile calibration: the forest is too timid, the T-learner too bold.
-
-
Sensitivity analysis. The World with an unmeasured frailty:
- adjusted −7.25 (SE 0.37), truth −9.93, −9.05 with frailty measured;
- Rosenbaum's Γ: 288 disjoint propensity-score matched pairs under a 0.2 SD logit-score caliper, with an exact dynamic-programming one-sided signed-rank worst-case tail. Significance persists to Γ ≈ 2.8 on the displayed grid. The selected matched sample differs from the full ATT target; the result does not bound actual hidden bias or prove a causal sign;
- E-values (VanderWeele & Ding 2017): an equal-strength threshold. Unequal confounder associations can trade off; both do not have to exceed E;
- Cinelli & Hazlett (2020): RV = 0.30 (0.28 for significance), against the frailty's actual partial R² of 0.087 and 0.085. These values describe a specified regression, not proof that its coefficient has a causal interpretation.
-
Smoking and lung cancer.
- Doll & Hill (1950): 647 of 649 cases and 622 of 649 controls smoked (OR ≈ 14); the British Doctors Study followed 34,439 male doctors for fifty years (1951–2001).
- Fisher's constitutional hypothesis (1957–58).
- Cornfield et al. (1959): under the stated binary-confounder explanation, RR ≈ 9 needs a confounder at least 9 times as prevalent (the equal-strength E-value is 17.5).
- Hill's nine viewpoints (1965).
-
Time-varying treatments.
- Treatment–confounder feedback with an unmeasured U; the truth is −7. Naive −2.57; adjusted for L₁ −2.10; IPW-MSM −7.04; g-formula −6.99. Identification requires sequential exchangeability, consistency and positivity, with appropriate nuisance models; regression within a valid g-formula is possible even though an ordinary treatment coefficient is not the regime effect.
- Target-trial emulation (Hernán & Robins 2016).
-
LaLonde revisited.
- 67% of PSID men have ê < 0.1, 74% of trainees have ê > 0.5, and 313 of 429 controls lie in range.
- Estimates: OLS $1,548, regression ATT $1,648, matching $428, IPW-ATT $1,348 ($1,539 on the overlap), strata $510.
- Placebo (1975 earnings): experiment $265, PSID −$144 (Imbens & Xu 2024).
- Lessons: overlap, pre-treatment outcomes, placebos, sensitivity.
Data:
- NSW is the Museum's;
- the observational study, the clinic and the trial are the World's;
- the colliders, front door, Kang–Schafer, DML and MSM examples are seeded simulations.
Built in this part:
statkit.causal(II) (explainer/stats/kit/causal.py), checked intests/test_stats_kit_causal.py:- Graphs:
DAGwith d-separation (moral ancestral graph), path enumeration, open/blocked paths and the back-door criterion. - Propensity methods: logistic propensity scores, SMD balance, g-computation, propensity matching, subclassification.
- Weighting and double robustness: Horvitz–Thompson/Hajek IPW for the ATE and ATT; AIPW with influence-function SEs; cross-fitted DML for the ATE and the partially linear model.
- Heterogeneous effects: T-, S-, X- and DR-learners; a locally centred teaching causal forest with separate split/estimation halves; this does not certify full honest-forest inference.
- Sensitivity and time: E-values, robustness values, partial R², Rosenbaum normal approximations in the kit; the chapter uses local exact signed-rank dynamic programming for disjoint matched pairs, Cornfield's ratio; stabilized MSM weights.
- Graphs:
- The Museum gains
nsw(). - The causal graph (
CausalGraphinexplainer/stats/viz.py).
The Coverage Board gains nine rows (90% intervals):
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| naive difference in means | World: doctors choose, n = 2,000 | 0.0% | broken |
| IPW, logistic propensity | same | 78.4% | broken |
| AIPW, both models fitted | same | 90.0% | kept |
| regression adjustment, unmeasured frailty | World: doctors also see frailty | 0.0% | broken |
| AIPW, PS right, outcome wrong | Kang & Schafer (2007), n = 1,000 | 91.9% | kept |
| AIPW, both models wrong | same | 55.9% | broken |
| OLS adjustment, linear | nonlinear confounding, n = 1,000 | 0.0% | broken |
| AIPW with forests, no cross-fitting | same | 0.0% | broken |
| DML: forests, cross-fitted | same | 88.0% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | LaLonde's test | $1,794 vs −$635 |
| 1 | Unconfoundedness and overlap | ATE −10.02; naive −1.38 |
| 2 | Causal diagrams | three junctions; d-separation |
| 3 | The back door | Berkson −0.56; M-bias 0.16 |
| 4 | The front door and do-calculus | 0.235 vs 0.129 (truth 0.128) |
| 5 | Simpson resolved | −11.2 → +7.8 points |
| 6 | g-computation | −10.35 |
| 7 | Propensity scores | ATT −12.43; strata −8.59 |
| 8 | Weighting | −8.48; max weight 36 |
| 9 | Double robustness | −9.91; Kang–Schafer bias −21.5 |
| 10 | Double machine learning | 88.0% vs 0% |
| 11 | Heterogeneous effects | latent-effect RMSE 4.35 → 2.76 (forest), 1.20 (linear) |
| 12 | Sensitivity analysis | Γ* ≈ 2.8; RV 0.30 |
| 13 | Smoking and lung cancer | 647/649 vs 622/649; E = 17.5 |
| 14 | Time-varying treatments | −2.57 vs −7.04 (truth −7) |
| 15 | LaLonde revisited | $428 to $1,648 |
| 16 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: LaLonde (1986); Dehejia & Wahba (1999); Smith & Todd (2005).
- Unconfoundedness and overlap.
- DAGs (Wright 1921; Pearl 1995). d-separation (
CausalGraph). - Back door. The adjustment formula; colliders (Berkson 1946), mediators, M-bias.
- Front door and do-calculus. Pearl's rules; SWIGs.
- Simpson resolved (Part 1).
- g-computation (Robins 1986).
- Propensity scores (Rosenbaum & Rubin 1983). Matching; subclassification (Cochran 1968); balance.
- IPW (Board).
- AIPW and double robustness (Robins, Rotnitzky & Zhao 1994); Kang–Schafer (Board).
- DML (Chernozhukov et al. 2018). Orthogonality and cross-fitting (theory in Part 49) (Board).
- CATE. Meta-learners; causal forests (Wager & Athey 2018), graded against the World's truth.
- Sensitivity. Cornfield (1959); Rosenbaum's Γ; E-values; Cinelli & Hazlett (2020).
- Smoking and lung cancer. Doll & Hill; Fisher (1958); Cornfield; Hill (1965).
- Time-varying treatments. MSMs; target-trial emulation (Hernán & Robins 2016).
- LaLonde revisited, with the role of overlap (recent re-analyses (verify)).
- Outro.
Built: statkit.causal (II). Data: NSW (license checked).
Build the film
python -m videos.stats.stats36.compute # the part's numbers, into .cache/stats36
python tools/build.py stats36 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats36 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats36. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
OMP_NUM_THREADS=1 python -m videos.stats.stats36.compute # once (about twenty minutes)
python tools/build.py stats36 -q l # fast 480p preview
python tools/build.py stats36 # 1080p30 -> renders/stats36.mp4
python tools/qa_scene.py stats36 AIPW
python tools/lecture_length.py stats36 --floor 50