Adjustment, matching, propensity scores and inverse probability weighting
Before this lesson: potential outcomes, the ATE and ATT, exchangeability and positivity (lesson 02); the backdoor criterion and the adjustment formula (lesson 04); linear regression (probability 13) and logistic regression. Importance sampling (probability 14) helps but is not required. Time: about 95 minutes, plus the notebook.
Why this matters #
Most causal questions in industry, medicine and policy are answered without an experiment: users opt in to a feature, doctors choose a drug, workers join a training program. Lesson 04 told us which variables to adjust for. This lesson is about how to adjust with data. The estimators here are the standard tools of epidemiology (Hernán and Robins), economics (Imbens and Rubin) and tech companies (observational studies next to A/B tests). They are also the base of causal machine learning: inverse propensity scoring (IPS) in recommender systems and learning to rank, off-policy evaluation in reinforcement learning (lesson 11), and double machine learning (lesson 08), which is AIPW with ML models.
1. Predict first #
2. The picture #
2.1 The problem: the groups differ before treatment #
A job-training program is open to everyone. People with low past earnings join more often. Past earnings also predict future earnings. So the people who joined would earn less even without the program, and the naive difference in mean earnings mixes the effect of the program with this difference between the groups. This is confounding by = past earnings (lesson 01 and lesson 04).
If blocks every backdoor path from to , the fix is to compare like with like: treated and control units with the same . There are three ways to do this, and this lesson treats all three:
| Idea | Method | What it models |
|---|---|---|
| predict the missing potential outcome | outcome regression (the g-formula) | |
| find a similar unit of the other group | matching | a distance between units |
| reweight the units so that the groups look alike | inverse probability weighting |
2.2 Weighting creates a pseudo-population #
Start with a population of 100 people and one binary confounder . Half have . In the group , 80% are treated: . In the group , 20% are treated: . The outcome is , so the true effect is for everyone.
The treated group is mostly (40 of 50 people), and adds 2 to . So the naive difference is 2.2, not 1:
Now give each treated unit the weight and each control unit the weight :
| Group | Treated: count → weighted | Control: count → weighted | ||
|---|---|---|---|---|
| 1.25 | 5 | 40 → 50 | 10 → 50 | |
| 5 | 1.25 | 10 → 50 | 40 → 50 |
After weighting, each group stands for the whole population: 50 people with and 50 with . A treated person in the group is rare (only 10 of 50), so this person counts 5 times. Together, the 10 treated people of that group now stand for all 50 people of the group, including the 40 who were not treated. Inside each group of the treatment was "as good as random", so these stand-ins are fair. In the pseudo-population no longer predicts , and the weighted difference in means is : the true effect.
Switch between the weights. "raw" shows the data: treated units sit at large , where is high anyway, so the naive difference is too large. "IPW (ATE)" gives each unit the weight or ; the dot area shows the weight. Notice the large control dots at large : rare controls stand for many people. The dashed lines are the weighted group means; their difference is the estimate. In the histograms below, both weighted groups now match the whole sample (dashed outline), and the SMD of drops to about 0. "weights for ATT" makes the controls look like the treated group; "IPW, trimmed" drops units with outside . The aqua curves are the true and , and the true effect changes with the target. Move the confounding slider to the right and watch the largest weight and the effective sample size.
A unit has an estimated propensity score . What is its IPW weight for the ATE if it is treated, and if it is a control?
A treated unit gets . A control unit gets . With , a control is rare among people like this unit, so each control must stand for about 10 people. Mixing up the two weights is a common mistake: the rare group gets the large weight.
2.3 Matching: find a twin in the other group #
Matching answers the causal question for each treated unit directly. For a treated unit we do not observe . We take the control unit with the closest covariates and use its outcome as a stand-in for . The average of over the treated units estimates the ATT, the effect for the treated. If the match were perfect (), exchangeability given would make a fair stand-in for .
With one or two covariates good matches are easy to find. With many covariates they are not: in high dimension every unit is far from every other unit (the curse of dimensionality). The propensity score solves this problem: section 3.4 shows that it is enough to match on the one number .
Compare the two kinds of matching. Each treated unit is joined to its nearest control (with replacement; faint controls are never used). "covariates X" uses the distance in the plane: pairs are close. "propensity score" uses the distance between values: a treated unit may take a control far away along a dashed line of equal . Both reduce the SMDs and move the matching estimate (black) from the naive difference toward the true ATT. Now make the caliper small: treated units with no close control are dropped (hollow), the estimate concerns the remaining treated units only, and its truth changes too. (The caliper is in standard deviations: of for covariate matching, of for propensity matching.)
You match every treated unit to its nearest control and average the differences . Which causal quantity does this estimate?
The average runs over the treated units, and each control only fills in the missing of a treated unit. So the target is . Many controls are never used, and some are used many times. To estimate the ATE, also match each control to its nearest treated unit and average over everyone.
3. Definitions and main results #
3.1 Assumptions and identification #
We observe independent copies of , where is a vector of pre-treatment covariates: measured before and not affected by . We write for the outcome regressions and for the propensity score. Three assumptions (lesson 02):
- Consistency. If , then . (This includes "no interference": the outcome of unit does not depend on the treatment of other units.)
- Conditional exchangeability (also called no unmeasured confounding, ignorability or unconfoundedness): . Within each level of , the treatment is as good as random. In graph language: satisfies the backdoor criterion of lesson 04.
- Positivity (also called overlap): for every with . Every kind of unit has some chance of being treated and some chance of being a control.
Which ones can the data check? Positivity can be checked, at least roughly: look at the estimated (section 3.6). Conditional exchangeability cannot be checked: it is a statement about of the treated units, and we never see it. It comes from knowledge of the problem (a causal graph), not from the data. Section 3.9 asks what happens if it fails.
Theorem (g-formula, or standardization). Under the three assumptions,
Proof (for ; the case is the same).
- By the law of total expectation, .
- By conditional exchangeability, is independent of given , so . Positivity () makes sure that this conditional expectation is defined for every .
- By consistency, when , so .
The right-hand side contains only observable quantities. So the ATE is identified: it is a property of the distribution of . This is the adjustment formula of lesson 04, written with expectations. For the treated, the same steps give . The ATT needs less: exchangeability only for , and positivity only in the form .
Every method below estimates the same estimand (or its ATT version). They differ in what they model and in how they fail.
3.2 Outcome regression (standardization) #
Estimator. Fit on the treated units and on the controls (any regression or ML model). Then predict both potential outcomes for every unit and average:
For the ATT, average only over the treated units. This is the plug-in version of the g-formula.
The usual regression is a special case. Fit one linear model and report . This equals when the model is right: and are linear and parallel (a constant effect). When the effect differs between units, the coefficient is not the ATE in general. For a discrete with one dummy per level, it is a weighted average of the effects with weights proportional to (Angrist 1998). Example: two equal groups with and effects . The ATE is and the ATT is , but the weights are and , so the coefficient is : neither the ATE nor the ATT.
Weak point: extrapolation. Where there are almost no controls (say, at large in the figure of section 2.2), is a guess made from other regions. A linear model extrapolates without a warning. Regression hides poor overlap; matching and weighting show it.
3.3 Matching #
- Exact matching. Pair units with exactly the same . Possible only with few discrete covariates. If each treated unit is compared with the mean of all controls with the same , the matching estimate equals the plug-in g-formula for the ATT.
- Nearest-neighbor matching (with replacement). For each treated unit , find the control that minimizes a distance : Euclidean on standardized covariates, Mahalanobis, or . Then
- matches. Average the outcomes of the nearest controls: lower variance, larger bias.
- Caliper. Drop a treated unit when its best match is farther than a caliper . A common choice is standard deviations of (Austin 2011). The dropped units change the estimand: we now estimate the effect for the treated units that have a match.
Matching estimates the ATT naturally. Its strength is transparency: you can look at the pairs. Its weakness is bias from imperfect matches. If , the stand-in has the wrong expected outcome: .
Matching bias and how to remove it (Abadie and Imbens)
With continuous covariates, the distance to the nearest control shrinks like , so the bias of nearest-neighbor matching also shrinks like (Abadie and Imbens 2006). The standard error shrinks like . For the bias shrinks more slowly than the noise, so in large samples it dominates and confidence intervals become wrong. The bias-corrected matching estimator (Abadie and Imbens 2011) fixes this. It fits a regression on the controls and replaces by : the regression moves the stand-in from to . A second warning: the standard bootstrap is not valid for nearest-neighbor matching with a fixed number of matches (Abadie and Imbens 2008); use their analytic variance formula or a weighting estimator instead.
3.4 The propensity score #
Definition. The propensity score is (Rosenbaum and Rubin 1983). It compresses a whole vector into one number between 0 and 1.
Theorem (balancing property). (a) : units with the same propensity score have the same distribution of in the treated and in the control group. (b) If , then .
So conditioning on the single number is as good as conditioning on all of . We can match, stratify or weight on instead of .
Proof of the balancing theorem
For a binary , independence of and given means .
(a)
- is a function of , so .
- By the tower rule, .
- Steps 1 and 2 give the same value, so : .
(b) Write .
- By the tower rule, .
- By exchangeability given , .
- So (the last step is step 2 of part (a)).
Estimating . In practice is unknown. Fit a probabilistic classifier of on : logistic regression, or a boosted model with calibrated probabilities. The probabilities must be calibrated, because IPW divides by them.
Judge the propensity model by balance, not by accuracy. The goal is not to predict well. The goal is that, after matching or weighting on , the covariates are balanced (section 3.7). A very accurate model is bad news: if predicts almost perfectly, then the treated and control units live in different regions of , and there is little overlap to compare. Also, do not add variables only because they predict : a variable that affects but not (an instrument, lesson 04) adds variance and can amplify bias.
Your propensity model has AUC 0.99 on held-out data. What does this tell you about the causal analysis?
AUC 0.99 means that for almost every treated unit, is near 1, and for almost every control, near 0. Then few units of one group look like units of the other group: positivity almost fails. IPW weights for controls with near 1 explode, and matching finds only poor matches. Calibration does not help: the problem is the data, not the model. In a randomized experiment the best possible AUC is 0.5.
3.5 Inverse probability weighting #
The Horvitz–Thompson IPW estimator of the ATE is
Theorem. Under the three assumptions, with the true : and . So with the true is unbiased for .
Proof (treated part).
- By consistency, (when both sides are 0).
- Condition on : . Positivity makes the division safe.
- By conditional exchangeability, and are independent given . So , and this is .
- The cancels: .
IPW is importance sampling. We want averages over the whole population, but the treated units are a sample from , not from . By Bayes' rule : the weight is the importance weight, up to a constant (probability 14).
The normalized (Hájek) estimator. The weights sum to only on average. Dividing by their actual sum gives a weighted difference in means:
It has a small bias but usually a much smaller variance, and it does not change when you add a constant to (the Horvitz–Thompson form does). Use it by default.
Weights for the ATT. Treated units get weight 1. Control units get , the odds of treatment. This reweights the controls to look like the treated group, so the weighted control mean estimates . (Check: .)
Estimated or true ? The proof uses the true . In practice we plug in . A surprising fact: with a good estimate (a correct parametric model, or a flexible model that grows with ), IPW with has a variance at least as small as IPW with the true , and with a flexible model it reaches the smallest possible variance (Hirano, Imbens and Ridder 2003). The estimated weights also correct the chance imbalance of in the sample.
3.6 Overlap and extreme weights #
If is close to 0 or 1 for some units, their weights are huge, and a few units decide the estimate. The variance of IPW grows without bound as or . Two numbers make this visible:
- the largest weight, and
- the effective sample size (Kish) of a group with weights : . Equal weights give ; one dominant weight gives about 1. Example: weights give , not 5.
Remedies, and their price.
- Trimming: keep only units with (often , Crump et al. 2009). The variance falls, but the estimand changes: it is now the effect for the units with good overlap, not the ATE. Say so when you report it.
- Truncating (or clipping) weights at a maximum value: keeps all units, adds bias.
- Overlap weights (Li, Morgan and Zaslavsky 2018): treated units get and controls get . They target the effect in the population with the most overlap, , and never explode.
Poor overlap is a property of the data, not of the estimator. Outcome regression hides it by extrapolating, and AIPW (section 3.8) also divides by : it reduces the damage but does not remove it. When overlap is poor, the honest answer is often an effect for a smaller population.
Increase the confounding strength and watch the histograms of : the treated units (above the axis) move to the right, the controls (below) to the left, and the overlap in the middle shrinks. The largest weight grows and the effective sample sizes fall. Press Run 200 samples to repeat the study 200 times: the estimates without trimming spread widely around the true ATE of 1. Now raise the trimming : the grey zones are removed, the spread falls, and the true target of the trimmed estimate moves below 1, because the units with the largest effects were trimmed away.
3.7 Diagnostics: balance and overlap #
Before you report an effect, check the two things the data can check.
Overlap. Plot the histograms of for the treated and the control group (as in the figure above). Look for regions where one group has no units. Report the largest weight and the ESS.
Balance. For each covariate, compute the standardized mean difference
where and are the mean and variance in group . For a binary covariate with shares , use . After weighting or matching, recompute the means with the weights (or in the matched sample) and keep the denominator from the raw data. A common rule is for every covariate (Austin 2011). Unlike a -test, the SMD does not depend on the sample size. Papers show the means before and after adjustment in a "Table 1" and the SMDs in a "Love plot".
What diagnostics cannot do. Good balance on the measured says nothing about an unmeasured confounder . Balance checks the estimation step (did the weights or matches do their job?), not the identification step (is enough?).
After weighting, all covariates have and the propensity histograms overlap well. Which statement is correct?
Balance and overlap are about the measured . Exchangeability given says that no confounder is missing from , and no statistic of can test that: it is a claim about of the treated, which is never observed. This is why section 3.9 adds a sensitivity analysis.
3.8 Doubly robust estimation (AIPW) #
Regression needs a correct outcome model. IPW needs a correct propensity model. The augmented inverse probability weighting (AIPW) estimator (Robins, Rotnitzky and Zhao 1994) uses both:
Read it as "regression estimate + a weighted average of the regression's mistakes". If the outcome model is right, the residuals average to zero and the correction does nothing on average. If the outcome model is wrong but the weights are right, the weighted residuals measure the mistake and remove it.
Theorem (double robustness). Let and be the limits of the fitted models. Under the three assumptions, AIPW is consistent for the ATE if either and , or . It does not need both.
Proof of double robustness
Take the treated part, ; the control part is the same with and .
- By consistency, , so .
- Condition on . By conditional exchangeability, , using (section 3.1).
- So .
- Subtract :
- The bias is an average of a product of two errors. It is zero if (first factor zero) or if (second factor zero). The sample average converges to this expectation by the law of large numbers.
Two more facts. When both models are correct, AIPW has the smallest possible asymptotic variance among regular estimators that use only these assumptions (it reaches the semiparametric efficiency bound). And the product form of the bias in step 4 is the key to lesson 08: with flexible ML models and cross-fitting (fit the models on one part of the data, evaluate the formula on the other part), two slowly converging models still give a fast-converging estimate. This is double machine learning.
Make one model wrong at a time. "wrong" models use instead of , so they miss the confounding through . Each run simulates 200 studies with 500 units. With a wrong propensity model, IPW moves away from the true ATE of 2, but AIPW stays centered on it. With a wrong outcome model, regression is off but AIPW is still centered. With both models wrong, AIPW fails too (the mean dot turns magenta). Notice also the spread: IPW with correct weights is unbiased but noisier than regression and AIPW.
In a study, the outcome model of AIPW is misspecified (it misses a nonlinear term), but the propensity model is correct. What happens as grows?
The bias of AIPW is (and the same for the controls), a product of the two errors. With a correct propensity model the second factor is 0. "Doubly robust" means two chances to be right: one correct model is enough. If both are wrong, AIPW is biased too, and it can even be worse than either method alone (Kang and Schafer 2007).
3.9 Sensitivity analysis: what if a confounder is missing? #
Every method above assumes conditional exchangeability. A sensitivity analysis asks: how strong would an unmeasured confounder have to be to change the conclusion? A result is credible only together with this statement.
Omitted-variable bias (linear case). Suppose the true model is , but we regress on and only. Then the estimate shifts by
where is the coefficient of in the full regression and is the coefficient of in the regression of on and (this is an exact identity of least squares). The bias is large only if is related to both the outcome () and the treatment ().
The same idea with partial (Cinelli and Hazlett 2020). Measure the strength of by two numbers between 0 and 1: , the share of the variance of (after ) that explains, and , the same for . Then
where is the residual degrees of freedom of the regression. The robustness value is the common value of the two partial that would bring the estimate to 0: with . To judge whether such a is plausible, compare it with the observed covariates: "a confounder as strong as past earnings".
The E-value (VanderWeele and Ding 2017) does the same on the risk-ratio scale, for a binary outcome. A confounder with risk ratio with the treatment and with the outcome can change an observed risk ratio by at most the bias factor (Ding and VanderWeele 2016)
The E-value is the smallest strength, equal on both sides, that could fully explain away an observed :
For , : only a confounder that raises both the chance of treatment and the risk of the outcome by a factor of 3.41 could explain the result away. For a protective effect (), use . Report the E-value of the confidence limit closest to 1, too.
Rosenbaum's (for matched pairs): assume that two units with the same can differ in their odds of treatment by at most a factor because of . Report the largest at which the result is still significant. is "no hidden bias".
Drag the black point to choose the strength of a hypothetical confounder ; the readout shows the estimate we would get if we could adjust for it. The study is the simulated job-training study of section 4 (estimate , standard error ). The grey lines are contours of the adjusted estimate; the magenta line is where it reaches 0, and the circle on the diagonal is the robustness value. The violet points are confounders exactly as strong as each observed covariate: a hidden confounder as strong as "earnings 1975" would almost remove the effect. Switch to "risk ratios" for the E-value version.
Answers to section 1. (1) Smaller. A treated person in that group gets and an untreated person gets : the untreated person's weight is 4 times larger, because untreated people are rare there. (2) Bad news. Near-perfect separation means poor overlap: extreme weights, poor matches, and an estimate that depends on extrapolation. (3) Yes. AIPW is doubly robust: a correct propensity model is enough for consistency.
4. Worked example #
(a) Twelve trainees, by hand #
Twelve people could join a training program. means "unemployed last year", means "joined", and is earnings next year in thousand dollars. Unemployed people join more often (4 of 6) than employed people (2 of 6).
| 1 | 1 | 6, 7, 8, 7 | 0 | 1 | 14, 16 | |
| 1 | 0 | 4, 6 | 0 | 0 | 10, 12, 11, 11 |
Step 1: cell means. , , , . The effect is for the unemployed and for the employed.
Step 2: naive difference. Treated mean ; control mean ; naive . It is far too small: the treated are mostly unemployed, who earn less anyway.
Step 3: g-formula. , so . For the ATT, average over the treated: 4 of them have and 2 have , so .
Step 4: exact matching (ATT). Match each treated unit with the mean of the controls in its cell (5 or 11). This gives the same 2.67 as step 3:
Step 5: propensity scores and IPW weights. and .
| Cell | (treated) | (control) | Weighted treated | Weighted control |
|---|---|---|---|---|
| 1.5 | 3 | |||
| 3 | 1.5 |
Both weighted groups now have 6 people of each kind, like the whole sample. Weighted means: treated , control . So . (Here the weights of each group sum to exactly , so the Horvitz–Thompson and Hájek forms agree.)
Step 6: ATT weights. Controls get : in the cell , in the cell . The weighted control mean is (the weights sum to ). So .
Step 7: balance. The share of is among the treated and among the controls. Both variances are , so : strong imbalance. After IPW, both weighted shares are , so the SMD is .
Step 8: effective sample size of the weighted treated group. Weights : out of 6.
Step 9: AIPW. With one mean per cell, the residuals add up to 0 in each cell, so the correction term is 0 and AIPW gives as well. With a saturated discrete , all the estimators agree; they differ when is continuous or high-dimensional and the models must smooth.
(b) A simulated job-training study #
In 1986 LaLonde compared observational estimates of a job-training program with the result of a randomized experiment, and many of them were far off; Dehejia and Wahba (1999) later showed that propensity-score methods on the right covariates came close. The study below is simulated in that spirit, so we know the truth. There are people with four covariates (age, years of education, earnings in 1975, unemployed in 1975). People with low past earnings join more often. The program raises earnings by 1 (thousand dollars) for people with a job in 1975 and by 2.5 for the unemployed, so the true ATE is about 1.45 and the true ATT, about 1.76, is larger (the unemployed join more often). The code is in section 5.
| Method | Target | Seed 0 | Mean of 200 | SD of 200 |
|---|---|---|---|---|
| naive difference | none | |||
| OLS coefficient of | ATE* | |||
| g-formula | ATE | |||
| NN matching | ATT | |||
| IPW (Hájek) | ATE | |||
| IPW, ATT weights | ATT | |||
| AIPW | ATE |
Truth: ATE (in seed 0 and on average); ATT in seed 0 and on average. "Seed 0" is one study; "mean" and "SD" are over 200 simulated studies. *The OLS coefficient is the ATE only if the effect were the same for everyone. The g-formula uses linear in each arm.
What to read from the table:
- The naive difference has the wrong sign. The participants are the people who would earn less anyway.
- All adjusted methods are close to their targets on average, but one study can be off by one or two standard deviations (IPW gives in this study). Always report a standard error, for example by the bootstrap (probability 12).
- IPW for the ATE has the largest spread: some controls with high past earnings are very unlikely to join ( as low as 0.007), and the few treated units that look like them get huge weights. The ATT weights do not have this problem: they give such controls a small weight .
- Matching is a little biased (1.67 vs 1.74): with four covariates the matches are not exact.
- AIPW is centered on the truth with about the spread of regression.
5. In code #
The code checks the hand computation of part (a) and runs the simulated study of part (b).
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.neighbors import NearestNeighbors
# (a) the twelve trainees of section 4: X = unemployed last year, T = joined, Y = earnings
X = np.array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
T = np.array([1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0])
Y = np.array([6, 7, 8, 7, 4, 6, 14, 16, 10, 12, 11, 11.])
e = np.array([T[X == x].mean() for x in X]) # ê(x) = share treated in the cell
mu = {(t, x): Y[(T == t) & (X == x)].mean() for t in (0, 1) for x in (0, 1)}
m1, m0 = np.array([mu[1, x] for x in X]), np.array([mu[0, x] for x in X])
print("naive", round(Y[T == 1].mean() - Y[T == 0].mean(), 2)) # 0.67
print("g-formula", np.mean(m1 - m0)) # 3.0
print("IPW (HT)", np.mean(T * Y / e - (1 - T) * Y / (1 - e))) # 3.0
w = (1 - T) * e / (1 - e) # ATT weights
print("IPW (ATT)", round(Y[T == 1].mean() - (w @ Y) / w.sum(), 2)) # 2.67
print("AIPW", np.mean(m1 - m0 + T * (Y - m1) / e - (1 - T) * (Y - m0) / (1 - e))) # 3.0
# (b) the simulated job-training study (earnings in 1000 $)
def simulate(n=2000, seed=0):
rng = np.random.default_rng(seed)
age, educ = rng.uniform(18, 55, n), rng.integers(8, 17, n).astype(float)
unemp = (rng.random(n) < 0.3).astype(float)
re75 = np.where(unemp == 1, 0.0, rng.gamma(2.0, 4.0, n)) # earnings in 1975
logit = -0.8 - 0.12 * (re75 - 8) + unemp - 0.03 * (age - 35) - 0.15 * (educ - 12)
T = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
tau = 1.0 + 1.5 * unemp # true effects
Y0 = (3 + 0.8 * re75 + 0.4 * (educ - 12) + 0.1 * (age - 35)
- 0.004 * (age - 35) ** 2 + rng.normal(0, 3, n))
return np.column_stack([age, educ, re75, unemp]), T, Y0 + tau * T, tau
X, T, Y, tau = simulate()
Z = (X - X.mean(0)) / X.std(0)
e = LogisticRegression(C=1e6).fit(Z, T).predict_proba(Z)[:, 1]
m1 = LinearRegression().fit(X[T == 1], Y[T == 1]).predict(X)
m0 = LinearRegression().fit(X[T == 0], Y[T == 0]).predict(X)
nn = NearestNeighbors(n_neighbors=1).fit(Z[T == 0])
match = Y[T == 0][nn.kneighbors(Z[T == 1])[1][:, 0]]
w1, w0, wa = T / e, (1 - T) / (1 - e), (1 - T) * e / (1 - e)
results = {
"naive": Y[T == 1].mean() - Y[T == 0].mean(),
"OLS coef": LinearRegression().fit(np.column_stack([T, X]), Y).coef_[0],
"g-formula": np.mean(m1 - m0),
"matching ATT": np.mean(Y[T == 1] - match),
"IPW ATE": w1 @ Y / w1.sum() - w0 @ Y / w0.sum(),
"IPW ATT": Y[T == 1].mean() - wa @ Y / wa.sum(),
"AIPW ATE": np.mean(m1 - m0 + T * (Y - m1) / e - (1 - T) * (Y - m0) / (1 - e)),
}
print(f"truth: ATE {tau.mean():.2f} ATT {tau[T == 1].mean():.2f}")
for k, v in results.items():
print(f"{k:13s} {v:6.2f}")
# truth: ATE 1.45 ATT 1.76
# naive -3.12
# OLS coef 1.32
# g-formula 1.30
# matching ATT 1.62
# IPW ATE 0.99
# IPW ATT 1.72
# AIPW ATE 1.28
LogisticRegression(C=1e6) turns off the default L2 penalty in practice: we want the propensity model
itself, not a shrunken one. The notebook builds every estimator step by step, adds cross-fitting to
AIPW and runs the 200-study experiment.
6. Where it shows up #
- Medicine and epidemiology. Observational drug-safety and effectiveness studies use propensity scores and IPW; target trial emulation (Hernán and Robins) designs the analysis as if it were a randomized trial and then adjusts with these tools. Marginal structural models extend IPW to treatments that change over time.
- Tech products. Users opt in to features, subscriptions and notifications. When an A/B test is not possible, analysts estimate the effect with matching or AIPW on logged covariates, and report a sensitivity analysis.
- Recommender systems and search. Users rate or click only what they were shown. Inverse propensity scoring (IPS) reweights the observed feedback by to get unbiased estimates of ranking quality and to train debiased models (Schnabel et al. 2016; Joachims et al. 2017).
- Off-policy evaluation. The value of a new policy from logs of an old policy is estimated with importance weights and with doubly robust estimators (lesson 11; reinforcement learning 03).
- Machine learning under covariate shift. Training points reweighted by , often estimated with a classifier that predicts "test or train": the same computation as a propensity score.
- Survey statistics. The Horvitz–Thompson estimator was invented (1952) to weight survey respondents by the inverse of their probability of being sampled.
- Science. Effects of policies, environmental exposures (air pollution and health) and land use are estimated from observational data with matching and weighting, together with sensitivity analysis.
7. Common mistakes #
- Adjusting for post-treatment variables. Covariates must be measured before the treatment. Adjusting for a mediator or a collider (lesson 04) creates bias, and no estimator can repair it. Check: draw the graph; for every covariate, ask "could the treatment change it?".
- Judging the propensity model by AUC or accuracy. The target is balance, not prediction. A very high AUC signals poor overlap. Check: SMDs after weighting, propensity histograms.
- Putting every predictor of into the propensity model. Instruments (causes of only) add variance and amplify any remaining bias. Include confounders and causes of .
- Ignoring extreme weights. One unit with weight 500 can decide the estimate. Check: largest weight, ESS, a plot of the weights; try Hájek, trimming or overlap weights, and say which estimand you now estimate.
- Mixing up the estimands. Matching treated units gives the ATT; IPW with gives the ATE; a caliper or trimming gives the effect in a subpopulation. Report the target with the number.
- Reading the OLS coefficient as the ATE. With heterogeneous effects, the coefficient of is a variance-weighted average of the effects, not the ATE. Use the g-formula with separate models for each arm.
- "Balanced, so causal." Balance on measured says nothing about unmeasured confounders. Check: a sensitivity analysis (robustness value, E-value).
- "Doubly robust means twice as safe." It means one of two models must be right. With both wrong, AIPW can be worse than either method alone.
- Plain bootstrap for nearest-neighbor matching. It is not valid for matching with a fixed number of matches (Abadie and Imbens 2008). Use the analytic variance or a weighting estimator with the bootstrap.
8. Check yourself #
- In a cell of 20 people, 5 are treated (). Give the IPW weights for the ATE and the
size of each weighted group.
Answer
Treated: ; controls: . Weighted treated: ; weighted controls: . Each group stands for all 20 people of the cell. - Compute the effective sample size of the weights and of .
Answer
: equal weights keep the full size. : one large weight makes five units worth only 2.5. - Why does trimming units with change what you estimate? Give an example where
it matters.
Answer
The estimate now averages the effect over the units that remain, not over the whole population. If the effect differs with and the trimmed units have different effects (in the figure of section 3.6, the units with large have the largest effects), the trimmed target is different from the ATE (there, below 1). - Write the AIPW estimator and show in one line why it is unbiased when (and the
weights are anything bounded).
Answer
. With : , so the correction terms have mean 0 and the estimator reduces to the g-formula. - Compute the E-value for an observed risk ratio of 3, and for a protective risk ratio of 0.5.
Answer
. For 0.5 use : . - A regression gives with standard error and . Compute the
robustness value.
Answer
, so . . A confounder that explains 17.4% of the residual variance of both and would bring the estimate to 0.
State conditional exchangeability in symbols and in words.
: within each level of , treatment is as good as random. It holds when satisfies the backdoor criterion.
What is positivity (overlap), and how much of it does the ATT need?
for every with . The ATT needs only : every kind of treated unit must have comparable controls.
Write the g-formula (standardization) for the ATE.
with .
What does the balancing theorem of the propensity score say?
, and if exchangeability holds given , it also holds given . So adjusting for the one number is enough.
Write the Horvitz–Thompson IPW estimator of the ATE.
.
Which weights make the control group look like the treated group (ATT)?
Treated units weight 1; control units weight , the odds of treatment.
Compute the effective sample size of the weights .
.
Define the standardized mean difference and the usual balance rule.
; a covariate counts as balanced if .
What does "doubly robust" mean for AIPW?
AIPW is consistent if either the outcome model or the propensity model is correct. If both are wrong, it is biased.
Compute the E-value for an observed risk ratio of 2.
.
9. Interview angle #
- "How would you estimate the effect of a feature that users opted into?" — Draw the graph: what drives opting in and the outcome (activity before the launch, tenure, platform)? Use only pre-treatment covariates. Fit a propensity model, check overlap and balance, estimate with AIPW (or IPW and matching as checks), report a confidence interval and a sensitivity analysis. Say that the result depends on "no unmeasured confounding" and suggest a holdout or an encouragement experiment if possible.
- "What is a propensity score and how do you check it?" — . It balances (Rosenbaum and Rubin). Check it by balance (SMDs after weighting below 0.1), overlap (histograms, largest weight, ESS) and calibration, not by AUC.
- "What does doubly robust mean?" — An estimator that combines an outcome model and a propensity model and is consistent if either one is right. AIPW: regression estimate plus inverse-weighted residuals. Its bias is a product of the two errors, which is why it works well with ML models and cross-fitting (double ML).
- "Matching or weighting?" — Matching is transparent and targets the ATT; it struggles with many covariates and its standard errors need care. Weighting targets the ATE or the ATT and uses all units, but is sensitive to extreme weights. AIPW is usually the best default.
- "Your IPW estimate jumps when you remove one user. Why?" — That user has an extreme weight (propensity near 0 or 1): poor overlap. Look at the ESS, use Hájek or overlap weights, or trim and report the new estimand.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution. Every exercise uses a simulation with a known true effect:
standardize(df): the g-formula with one linear model per arm; compare it with the naive difference and the OLS coefficient.nn_match_att(df, caliper): nearest-neighbor matching on standardized covariates withNearestNeighbors; a balance table of SMDs before and after.ipw(df, e_hat, kind): the Horvitz–Thompson, Hájek and ATT versions with aLogisticRegressionpropensity model; weighted SMDs and the effective sample size.aipw(df)with 2-fold cross-fitting; the experiment with right and wrong models.- Overlap: increase the confounding, compare the spread of IPW and AIPW, and see how trimming changes the estimand.
11. Watch and read #
- Miguel Hernán and James Robins, Causal Inference: What If (free): chapter 12 (IP weighting), chapter 13 (standardization and the g-formula), chapter 15 (outcome regression and propensity scores).
- Brady Neal, Introduction to Causal Inference (free PDF): chapter 7 (estimation: outcome models, propensity scores, IPW, doubly robust methods) and chapter 8 (sensitivity analysis).
- Matheus Facure, Causal Inference for the Brave and True: Matching, Propensity Score and Doubly Robust Estimation, with Python code.
- Peter Austin (2011), An Introduction to Propensity Score Methods for Reducing the Effects of Confounding in Observational Studies, Multivariate Behavioral Research: matching, weighting, balance diagnostics and the SMD.
- Elizabeth Stuart (2010), Matching Methods for Causal Inference: A Review and a Look Forward, Statistical Science.
- Joseph Kang and Joseph Schafer (2007), Demystifying Double Robustness, Statistical Science: when AIPW fails with two wrong models.
- Carlos Cinelli and Chad Hazlett (2020), Making Sense of Sensitivity: Extending Omitted Variable Bias, Journal of the Royal Statistical Society B: partial , the robustness value and benchmarks.
- Nick Huntington-Klein, The Effect, chapter 14: Matching (free online): matching and weighting with many examples.
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.