Algorithmadvanced
Augmented inverse probability weighting
Also called AIPW, doubly robust estimator.
Combines an outcome regression with inverse probability weighting of its residuals. It is consistent if either model is right and efficient if both are.
- Time
- Θ(n) worst · best
- Space
- Θ(1) extra
- Where
- n = the number of units
- Model
- Real RAM
- Properties
- deterministicdoubly robustneeds positivitysingle passnot stays in outcome rangeunbiased with one correct fixed model
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James M. Robins, Andrea Rotnitzky, Lue Ping Zhao, 1994
Augmented inverse probability weighting (AIPW) estimates the average treatment effect with two working models: a model of the propensity score and models and of the mean outcome in each arm. It predicts both potential outcomes for every unit with the outcome models, and then corrects the predictions with the inverse probability weighted residuals of the units that were actually observed in each arm. For fixed working models, the estimate has mean when either the propensity model or the outcome models are right; with fitted models it is consistent when either is right. This is why it is called doubly robust. When both are right, its asymptotic variance reaches the semiparametric efficiency bound, the smallest that any regular estimator of the ATE can have. With the working models fitted, the estimate takes one pass over the data.
In plain words
There are two common ways to adjust for differences between treated and untreated groups. One is to model how the outcome depends on the measured traits, and to predict for every person the outcome with and without treatment. The other is to weight people by one over their chance of getting the treatment they got. Each method fails if its model is wrong.
AIPW uses both. It starts from the predictions, then looks at how far off the predictions were for the people we actually saw in each group, and adds back those errors with the weights. If the predictions are good, the errors average out to nothing and the weights do not matter. If the weights are right, they fix whatever the predictions got wrong. Only when both are wrong does the estimate go wrong.
The problem
The two parts of the problem are kept apart: what the data can identify, and how to estimate it.
Identification. This is the same as for IPW. Each unit has potential outcomes and , a treatment and covariates measured before treatment, and the units are independent draws from one distribution. The estimand is . The assumptions are consistency with SUTVA (, no interference, no hidden versions of treatment), ignorability , and positivity . With and , there are two identification formulas,
the first by standardization (the g-formula) and the second by weighting. AIPW uses a third formula that combines them:
The added terms have mean 0 because a residual has mean 0 within each arm and stratum. Positivity can be checked in part from the estimated propensities. Ignorability and SUTVA cannot be checked from the observed data.
Estimation. The input is units with and three numbers from the working models: , and . A usual choice fits by logistic regression of on features of , and fits by least squares of on features of among the units with . The output is the estimate
its two parts and (estimates of and ), and a standard error. With the estimate is the Horvitz-Thompson form of IPW. Without the two residual terms it is the regression (standardization) estimate.
The algorithm
AIPW-ATE(T, Y, ẽ, m1, m0) ▷ n units; needs 0 < ẽ_i < 1- 1
s1 ← 0; s0 ← 0 - 2
for i ← 1 to n do - 3
if ẽ_i ≤ 0 or ẽ_i ≥ 1 then error "positivity fails" - 4
if T_i = 1 then s1 ← s1 + m1_i + (Y_i - m1_i) / ẽ_i; s0 ← s0 + m0_i - 5
else s1 ← s1 + m1_i; s0 ← s0 + m0_i + (Y_i - m0_i) / (1 - ẽ_i) - 6
μ1 ← s1 / n; μ0 ← s0 / n - 7
return (μ1 - μ0, μ1, μ0)
Every unit adds its predicted outcome under both treatments. Line L4 corrects the treated prediction with the weighted residual of a treated unit, and line L5 corrects the control prediction with the weighted residual of a control. A unit gives no residual for the arm it was not in; the weights make up for the missing residuals, as in IPW. Line L3 stops on a propensity of 0 or 1.
Fitting the working models. The reference code fits by Newton-Raphson on the logistic log-likelihood and stops when the largest coefficient step is below , and raises an error after 50 steps. If the treatment is perfectly separated by the features, the maximum likelihood estimate does not exist and the fitted propensities go to 0 or 1; this is a positivity failure in the model, and line L3 then stops the estimate. The outcome fits solve the normal equations, which is adequate for a few well scaled features; use a QR solve for an ill conditioned design.
Variance. If both working models are right, is asymptotically normal with variance , and fitting the models adds nothing to in the limit (Robins, Rotnitzky and Zhao 1994; Tsiatis 2006). The plug-in estimate is
with divisor , and is a normal confidence interval of approximate level . If one model is wrong, stays consistent but is not always right; a sandwich variance of the joint M-estimator that stacks the model fits and , or the bootstrap of the whole procedure, takes the model fits into account.
Example
The eight patients of the IPW page have a stratum (0 mild, 1 severe), and the design treated mild patients with probability and severe patients with probability .
| unit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | |
| 1 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | |
| 8 | 7 | 6 | 5 | 7 | 4 | 3 | 1 | |
| design | 1/4 | 1/4 | 1/4 | 1/4 | 1/4 | 3/4 | 3/4 | 3/4 |
Take a poor outcome model that ignores : (the treated mean) and (the control mean), with the design propensities. Line L4 gives the treated units the terms , , and in , and line L5 adds for each of the four controls, so and . In the same way and . So .
The table puts this next to the other choices of the working models. The stratified estimate, , is the reference.
| propensity | outcome models | |
|---|---|---|
| design | (pure IPW, Horvitz-Thompson) | |
| design | arm means, ignore | |
| design | cell means , | |
| for all, ignores | arm means, ignore | (the naive difference) |
| for all, ignores | cell means | |
| empirical and | arm means, ignore | |
| empirical and |
With the cell means, the residuals add to zero within each cell, and the propensities no longer matter. With the empirical propensities, the weights fix any outcome model. Only when both models ignore does the estimate fall back to the naive . The proofs show that both exact agreements with hold for every discrete covariate. The design propensities are the true ones, but the sample is small, so with a poor outcome model the estimate is , not : double robustness is a statement about the mean, not about each sample.
The same effect in the population. Let , , , , , and , so . With and the wrong propensity , the bias formula of the proofs gives , so . Make either model right and the bias is exactly 0.
Correctness
The proofs establish, in exact arithmetic:
- the loop computes the mean of the ;
- the bias identity: for fixed working models, , so the mean is if or (double robustness), and the bias is bounded by the product of the propensity error and the outcome error;
- consistency with estimated working models that converge uniformly to limits, if one of the limits is right;
- with a discrete , the empirical propensities or the cell means each give the stratified estimate exactly.
The asymptotic normality, the consistency of when both models are right, and the efficiency of AIPW are cited, not proved (Robins, Rotnitzky and Zhao 1994; Hahn 1998; Tsiatis 2006, Chapter 13). The simulation numbers below are measured.
Proof: The AIPW estimate has mean equal to the ATE if either the propensity model or the outcome model is rightfull
Unit has treatment , outcome , a propensity value with and two outcome predictions and . Write
All arithmetic is exact.
Lemma 1 (the loop). AIPW-ATE returns , and .
Proof. Line L1 sets , and the loop L2 visits each unit once. Line L3 changes nothing. For a treated unit, line L4 adds to and to ; these are the unit's terms of the two sums, because and . For a control, line L5 adds to and to , again the unit's terms. Line L6 divides by , and the difference of the two sums is term by term.
The double robustness identity
Here the units are independent copies of . Let be the true propensity and the true outcome regressions. Assume consistency , ignorability , positivity , and for . The working models are fixed functions , , that do not depend on the sample, with , and with , and integrable. Put and , and let be the score of a generic unit.
Theorem 2 (bias identity). With ,
Proof. By consistency . By ignorability , so , and . Since is a function of ,
In the same way and give . The integrability conditions make every term integrable (as in the identification proof of the IPW page, with absolute values first). So
with every function evaluated at . Subtract :
Take expectations. By the tower property of conditional expectation, , and .
Corollary 3 (double robustness). If , or if and , then . So with fixed working models of which at least one is right, , and almost surely by the strong law of large numbers.
Proof. If , then and for every . If , then . In both cases each product in Theorem 2 is 0 for every . By Lemma 1 and linearity of expectation, . The are independent and identically distributed with finite mean, so the strong law applies.
Corollary 4 (product bound). If for a constant , and , then
Proof. and , and both denominators are at least . Apply the Cauchy-Schwarz inequality to each term of Theorem 2.
The bias is a product of the two errors, so it is small when both errors are moderately small. This product form is the reason that double machine learning can use slowly converging learners for both nuisances.
Estimated working models
Theorem 5 (consistency). Let , , be estimated from the sample, and suppose there are fixed functions , , with for all and , such that in probability. If or , then in probability.
Proof. Write and for the estimate with the estimated and the limit functions. On the event , whose probability tends to 1, every lies in . For a treated unit,
and , so the absolute value is at most . The control term has the same bound with , and the two terms differ by at most . Hence
The average on the right converges to a finite constant by the law of large numbers, so the right side tends to 0 in probability. By Corollary 3, .
The uniform convergence holds, for example, for a logistic propensity model and linear outcome models fitted by maximum likelihood and least squares on a bounded covariate space with a nonsingular design: the coefficients converge to the minimizers of the population criteria (the limits and ), whether or not the models are right.
Exact identities with a discrete covariate
Let take finitely many values, let stratum have units, treated and controls, and let be the mean outcome of arm in stratum . The stratified estimate is .
Theorem 6. (a) If , then for all functions . (b) If , then for every function with values in .
Proof. Fix a stratum and look at its share of , which is . In case (a), , so the share is . In case (b), , so the share is again . The same steps with or give the share of . Sum over the strata and divide by .
Theorem 6 is the sample version of Corollary 3: the empirical propensity and the cell means are the saturated estimates of and , and either one alone gives the stratified estimate exactly.
What is not proved here
The asymptotic normality of with estimated working models, the fact that the plug-in variance is consistent when both models are right, and the fact that the variance with the true and equals the semiparametric efficiency bound are cited on the page (Robins, Rotnitzky and Zhao 1994; Hahn 1998; Tsiatis 2006, Chapter 13). The coverage figures on the page are measured by simulation.
Complexity
Given the working models, the loop does a constant number of arithmetic operations per unit, so the estimate takes time in the best and the worst case and extra space, and it can run on a stream. The scores for need a second pass, or running sums of and . The model fits usually cost more: with propensity features and outcome features, the Newton-Raphson fit costs per step and the two least squares fits .
Properties
- Doubly robust. For fixed working models, the mean of is if either the propensity model or both outcome models are right. A simulation shows it: uniform on , , with standard normal , true ATE 1.5, , 200 samples (seed 2026). The right outcome model uses in each arm, the wrong one a constant; the right propensity model is logistic in , the wrong one a constant.
| working models | mean of | SD | 95% coverage |
|---|---|---|---|
| both right | 1.506 | 0.073 | 0.955 |
| outcome wrong | 1.505 | 0.079 | 1.000 |
| propensity wrong | 1.507 | 0.073 | 0.920 |
| both wrong | 2.490 | 0.084 | 0.000 |
| IPW alone, right propensity | 1.511 | 0.087 |
With both models wrong, AIPW is the naive difference of means, 2.49. These numbers are measured, not proved.
- Product bias. The bias is at most a constant times the product of the propensity error and the outcome error. Two models that are each a little wrong give a bias of second order.
- Efficient when both are right. With the true and , the variance equals Hahn's (1998) bound , where . The function is the efficient influence function of the ATE. In the table, AIPW with both models right has a smaller SD than IPW with the right propensity.
- Not in range. Like the Horvitz-Thompson form, is not an average of the observed outcomes and can fall outside their range, for a binary outcome even outside . TMLE fixes this.
- Randomized experiments. If is the known assignment probability, is unbiased for every fixed outcome model, and a good outcome model only lowers the variance. This is regression adjustment for experiments, as in CUPED.
Variants and improvements
- Normalized weights. Dividing each residual sum by the sum of its weights (the Hájek form of the correction) keeps the estimate more stable when some weights are large.
- Regression on a clever covariate. Bang and Robins (2005) obtain a doubly robust estimate by adding and as covariates to the outcome regression and then standardizing. TMLE is a general form of this idea that keeps the estimate in the range of the outcome.
- Cross-fitting. Fit the working models on other folds of the data than the ones where is computed. This is double machine learning, and it allows flexible learners such as random forests and gradient boosting for the nuisances.
- Effect on the treated. The ATT version uses the score and needs only an outcome model for the controls.
- Missing data and policies. The same form estimates a mean from data missing at random (see missing-data mechanisms), which was the first use, and the value of a new policy from logged actions (off-policy evaluation). In Monte Carlo integration terms, the outcome model is a control variate for the weighted estimate.
When to use it
Use AIPW in an observational study when ignorability given the measured is credible and you can fit both a propensity model and an outcome model. It is a good default over IPW alone or regression alone, because one of the models may be wrong and you do not know which. In a randomized experiment it adds precision without risk to the bias. Check overlap first: if many estimated propensities are near 0 or 1, the residual weights are large, and trimming or the ATT is a better target. Pair it with a sensitivity analysis, since no method that uses only can fix an unmeasured confounder.
Pitfalls
- Both models a little wrong. Double robustness gives no guarantee when both models are wrong. Kang and Schafer (2007) built a simulation in which both models are only slightly wrong and some propensities are near 0, and AIPW was worse than the outcome regression alone. Check the weights and the balance of .
- Weights near the positivity limit. The residual terms carry the weights and . A unit with and a residual of 5 moves by .
- Overfitted working models on the same data. Flexible learners fitted and evaluated on the same units can make the residuals too small and bias the estimate. Use cross-fitting.
- Treating the plug-in variance as exact. With one wrong model, was conservative in one simulation case above (coverage 1.000) and too small in the other (0.920). Use a sandwich variance or the bootstrap when you doubt a model.
- A model of the wrong thing. The outcome models must be fitted separately in each arm, or with treatment interactions; a model with a common slope in for both arms is wrong when the effect varies with .
- Calling it unconfounded. Double robustness is about two models of observed data. It does not protect against an unmeasured confounder or against a covariate measured after treatment.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/augmented-inverse-probability-weighting/. The authors are listed in prov/T508RZ.jsonl.
"""Augmented inverse probability weighting (AIPW) estimate of the average treatment effect.
Unit i has a treatment t[i] in {0, 1}, an outcome y[i], a propensity e[i]
(the probability of treatment given the covariates) and two outcome
predictions m1[i] and m0[i] (the predicted outcome under treatment and under
control). The estimate is the mean of the AIPW scores
psi_i = m1_i - m0_i + t_i (y_i - m1_i) / e_i - (1 - t_i)(y_i - m0_i) / (1 - e_i).
The nuisance values e, m1, m0 are inputs. fit_aipw fits them with a logistic
regression for e and one least squares regression per arm for m1 and m0.
With Fraction or int inputs, aipw_ate and aipw_scores are exact.
"""
import math
from collections.abc import Sequence
from statistics import NormalDist
from typing import NamedTuple
class AIPWEstimate(NamedTuple):
tau: object # the AIPW estimate of E[Y(1) - Y(0)]
mu1: object # the AIPW estimate of E[Y(1)]
mu0: object # the AIPW estimate of E[Y(0)]
def aipw_scores(t: Sequence[int], y: Sequence, e: Sequence, m1: Sequence, m0: Sequence) -> list:
"""The scores psi_i, one per unit. Cost: Theta(n) time."""
n = len(t)
if not (n == len(y) == len(e) == len(m1) == len(m0)):
raise ValueError("t, y, e, m1 and m0 must have the same length")
if n == 0:
raise ValueError("no units")
out = []
for ti, yi, ei, a, b in zip(t, y, e, m1, m0):
if ti not in (0, 1):
raise ValueError("every treatment must be 0 or 1")
if not 0 < ei < 1:
raise ValueError("positivity fails: every propensity must be strictly between 0 and 1")
if ti == 1:
out.append(a - b + (yi - a) / ei)
else:
out.append(a - b - (yi - b) / (1 - ei))
return out
def aipw_ate(t: Sequence[int], y: Sequence, e: Sequence, m1: Sequence, m0: Sequence) -> AIPWEstimate:
"""AIPW estimate of the ATE and of the two arm means. Cost: Theta(n) time, O(1) extra space."""
n = len(t)
if not (n == len(y) == len(e) == len(m1) == len(m0)):
raise ValueError("t, y, e, m1 and m0 must have the same length")
if n == 0:
raise ValueError("no units")
s1 = s0 = 0 # @line L1
for ti, yi, ei, a, b in zip(t, y, e, m1, m0): # @line L2
if ti not in (0, 1):
raise ValueError("every treatment must be 0 or 1")
if not 0 < ei < 1: # @line L3
raise ValueError("positivity fails: every propensity must be strictly between 0 and 1")
if ti == 1: # @line L4
s1 += a + (yi - a) / ei
s0 += b
else: # @line L5
s1 += a
s0 += b + (yi - b) / (1 - ei)
mu1, mu0 = s1 / n, s0 / n # @line L6
return AIPWEstimate(mu1 - mu0, mu1, mu0) # @line L7
def aipw_variance(t, y, e, m1, m0):
"""Estimated variance of the AIPW estimate: S_psi^2 / n, with divisor n - 1 in S_psi^2."""
psi = aipw_scores(t, y, e, m1, m0)
n = len(psi)
if n < 2:
raise ValueError("need at least two units")
mean = sum(psi) / n
return sum((p - mean) ** 2 for p in psi) / (n - 1) / n
def aipw_interval(t, y, e, m1, m0, alpha: float = 0.05) -> tuple[float, float, float]:
"""(estimate, lower, upper) of the normal interval with nominal coverage 1 - alpha."""
tau = float(aipw_ate(t, y, e, m1, m0).tau)
se = math.sqrt(float(aipw_variance(t, y, e, m1, m0)))
z = NormalDist().inv_cdf(1 - alpha / 2)
return tau, tau - z * se, tau + z * se
# ----------------------------------------------------------------- nuisance fits
def solve(a: list[list], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting (exact for Fractions)."""
k = len(b)
m = [list(row) + [bi] for row, bi in zip(a, b)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular system")
m[c], m[p] = m[p], m[c]
for r in range(c + 1, k):
f = m[r][c] / m[c][c]
if f != 0:
for j in range(c, k + 1):
m[r][j] -= f * m[c][j]
x = [0] * k
for c in range(k - 1, -1, -1):
s = m[c][k] - sum(m[c][j] * x[j] for j in range(c + 1, k))
x[c] = s / m[c][c]
return x
def fit_least_squares(rows: Sequence[Sequence], y: Sequence) -> list:
"""Coefficients b that minimize sum (y_i - rows_i . b)^2, by the normal equations."""
p = len(rows[0])
xtx = [[sum(r[i] * r[j] for r in rows) for j in range(p)] for i in range(p)]
xty = [sum(r[i] * yi for r, yi in zip(rows, y)) for i in range(p)]
return solve(xtx, xty)
def _expit(z: float) -> float:
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
ez = math.exp(z)
return ez / (1.0 + ez)
def fit_logistic(rows: Sequence[Sequence[float]], t: Sequence[int], tol: float = 1e-10, max_iter: int = 50) -> list[float]:
"""Logistic regression coefficients by Newton-Raphson. Stops when the largest step is below tol."""
p = len(rows[0])
b = [0.0] * p
for _ in range(max_iter):
grad = [0.0] * p
hess = [[0.0] * p for _ in range(p)]
for r, ti in zip(rows, t):
q = _expit(sum(bj * rj for bj, rj in zip(b, r)))
w = q * (1.0 - q)
for i in range(p):
grad[i] += (ti - q) * r[i]
for j in range(i + 1):
hess[i][j] += w * r[i] * r[j]
for i in range(p):
for j in range(i + 1, p):
hess[i][j] = hess[j][i]
step = solve(hess, grad)
b = [bj + sj for bj, sj in zip(b, step)]
if max(abs(s) for s in step) < tol:
return b
raise ArithmeticError("Newton-Raphson did not converge; check for separation")
def fit_aipw(x: Sequence, t: Sequence[int], y: Sequence, outcome_features, propensity_features) -> tuple[list, list, list]:
"""Fit e by logistic regression on propensity_features(x) and m1, m0 by least squares on
outcome_features(x) within each arm. Returns the lists (e, m1, m0) evaluated at every unit."""
prow = [propensity_features(xi) for xi in x]
orow = [outcome_features(xi) for xi in x]
g = fit_logistic(prow, t)
e = [_expit(sum(gj * rj for gj, rj in zip(g, r))) for r in prow]
b1 = fit_least_squares([r for r, ti in zip(orow, t) if ti == 1], [yi for yi, ti in zip(y, t) if ti == 1])
b0 = fit_least_squares([r for r, ti in zip(orow, t) if ti == 0], [yi for yi, ti in zip(y, t) if ti == 0])
m1 = [sum(bj * rj for bj, rj in zip(b1, r)) for r in orow]
m0 = [sum(bj * rj for bj, rj in zip(b0, r)) for r in orow]
return e, m1, m0
test_augmented_inverse_probability_weighting.py 215 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/augmented-inverse-probability-weighting/. The authors are listed in prov/T508RZ.jsonl.
import math
import random
import statistics
from fractions import Fraction as Fr
import pytest
from augmented_inverse_probability_weighting import (
aipw_ate,
aipw_interval,
aipw_scores,
aipw_variance,
fit_aipw,
fit_least_squares,
fit_logistic,
)
# The worked example of the page (the eight units of the inverse probability weighting page).
EX_X = [0, 0, 0, 0, 0, 1, 1, 1]
EX_T = [1, 1, 0, 0, 0, 1, 1, 0]
EX_Y = [8, 7, 6, 5, 7, 4, 3, 1]
EX_E = [Fr(1, 4)] * 5 + [Fr(3, 4)] * 3
def stratified(x, t, y):
"""Oracle: sum over strata of (stratum share) times (difference of the arm means)."""
out = Fr(0)
for v in set(x):
idx = [i for i in range(len(x)) if x[i] == v]
tr = [y[i] for i in idx if t[i] == 1]
co = [y[i] for i in idx if t[i] == 0]
out += len(idx) * (Fr(sum(tr), len(tr)) - Fr(sum(co), len(co)))
return out / len(x)
def test_worked_example():
zero = [0] * 8
assert aipw_ate(EX_T, EX_Y, EX_E, zero, zero).tau == Fr(31, 6) # the Horvitz-Thompson IPW form
cells1 = [Fr(15, 2) if v == 0 else Fr(7, 2) for v in EX_X]
cells0 = [Fr(6) if v == 0 else Fr(1) for v in EX_X]
assert aipw_ate(EX_T, EX_Y, EX_E, cells1, cells0).tau == Fr(15, 8)
arm1, arm0 = [Fr(11, 2)] * 8, [Fr(19, 4)] * 8
assert aipw_ate(EX_T, EX_Y, EX_E, arm1, arm0).tau == Fr(10, 3)
half = [Fr(1, 2)] * 8
assert aipw_ate(EX_T, EX_Y, half, arm1, arm0).tau == Fr(3, 4) # both wrong: the naive difference
assert aipw_ate(EX_T, EX_Y, half, cells1, cells0).tau == Fr(15, 8)
emp = [Fr(2, 5)] * 5 + [Fr(2, 3)] * 3
assert aipw_ate(EX_T, EX_Y, emp, arm1, arm0).tau == Fr(15, 8)
assert aipw_ate(EX_T, EX_Y, emp, zero, zero).tau == Fr(15, 8)
def test_scores_average_to_estimate_and_variance():
rng = random.Random(5)
for _ in range(200):
n = rng.randint(2, 12)
t = [rng.randint(0, 1) for _ in range(n)]
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
e = [Fr(rng.randint(1, 9), 10) for _ in range(n)]
m1 = [Fr(rng.randint(-9, 9), 2) for _ in range(n)]
m0 = [Fr(rng.randint(-9, 9), 3) for _ in range(n)]
psi = aipw_scores(t, y, e, m1, m0)
est = aipw_ate(t, y, e, m1, m0)
assert sum(psi) / n == est.tau == est.mu1 - est.mu0
mean = sum(psi) / n
assert aipw_variance(t, y, e, m1, m0) == sum((p - mean) ** 2 for p in psi) / ((n - 1) * n)
def population_bias(px, e, et, mu1, mu0, m1, m0):
"""Exact E[psi] - tau over a discrete population, by direct expectation over X and T."""
mean_psi = Fr(0)
tau = Fr(0)
for x, p in px.items():
# E[psi | X = x] with E[T | X] = e(x) and E[Y | T = t, X] = mu_t(x)
treated = m1[x] - m0[x] + (mu1[x] - m1[x]) / et[x]
control = m1[x] - m0[x] - (mu0[x] - m0[x]) / (1 - et[x])
mean_psi += p * (e[x] * treated + (1 - e[x]) * control)
tau += p * (mu1[x] - mu0[x])
return mean_psi - tau
def test_double_robustness_identity_exact():
rng = random.Random(11)
for _ in range(300):
k = rng.randint(1, 4)
w = [rng.randint(1, 5) for _ in range(k)]
px = {x: Fr(w[x], sum(w)) for x in range(k)}
e = {x: Fr(rng.randint(1, 9), 10) for x in range(k)}
mu1 = {x: Fr(rng.randint(-9, 9)) for x in range(k)}
mu0 = {x: Fr(rng.randint(-9, 9)) for x in range(k)}
et = {x: Fr(rng.randint(1, 9), 10) for x in range(k)}
m1 = {x: Fr(rng.randint(-9, 9)) for x in range(k)}
m0 = {x: Fr(rng.randint(-9, 9)) for x in range(k)}
# correct propensity, wrong outcome model
assert population_bias(px, e, e, mu1, mu0, m1, m0) == 0
# correct outcome model, wrong propensity
assert population_bias(px, e, et, mu1, mu0, mu1, mu0) == 0
# both wrong: the bias is the product formula of the page
formula = sum(px[x] * ((e[x] / et[x] - 1) * (mu1[x] - m1[x]) - ((1 - e[x]) / (1 - et[x]) - 1) * (mu0[x] - m0[x])) for x in px)
assert population_bias(px, e, et, mu1, mu0, m1, m0) == formula
def test_population_example_of_the_page():
px = {0: Fr(1, 2), 1: Fr(1, 2)}
e = {0: Fr(1, 4), 1: Fr(3, 4)}
mu1 = {0: Fr(7), 1: Fr(4)}
mu0 = {0: Fr(6), 1: Fr(1)}
zero = {0: Fr(0), 1: Fr(0)}
half = {0: Fr(1, 2), 1: Fr(1, 2)}
assert population_bias(px, e, half, mu1, mu0, zero, zero) == -2
assert population_bias(px, e, e, mu1, mu0, zero, zero) == 0
assert population_bias(px, e, half, mu1, mu0, mu1, mu0) == 0
def test_discrete_covariate_sample_identities():
"""Empirical propensities give the stratified estimate for every outcome model that depends on x
only; cell-mean outcome models give it for every propensity that depends on x only."""
rng = random.Random(23)
for _ in range(300):
k = rng.randint(1, 3)
x, t, y = [], [], []
for v in range(k):
n1, n0 = rng.randint(1, 4), rng.randint(1, 4)
for _ in range(n1):
x.append(v), t.append(1), y.append(Fr(rng.randint(0, 20)))
for _ in range(n0):
x.append(v), t.append(0), y.append(Fr(rng.randint(0, 20)))
target = stratified(x, t, y)
share = {v: Fr(sum(1 for i in range(len(x)) if x[i] == v and t[i]), x.count(v)) for v in range(k)}
emp = [share[v] for v in x]
g1 = {v: Fr(rng.randint(-5, 25)) for v in range(k)}
g0 = {v: Fr(rng.randint(-5, 25)) for v in range(k)}
assert aipw_ate(t, y, emp, [g1[v] for v in x], [g0[v] for v in x]).tau == target
cm1 = {v: stratified_mean(x, t, y, v, 1) for v in range(k)}
cm0 = {v: stratified_mean(x, t, y, v, 0) for v in range(k)}
anyp = {v: Fr(rng.randint(1, 9), 10) for v in range(k)}
assert aipw_ate(t, y, [anyp[v] for v in x], [cm1[v] for v in x], [cm0[v] for v in x]).tau == target
def stratified_mean(x, t, y, v, arm):
vals = [y[i] for i in range(len(x)) if x[i] == v and t[i] == arm]
return Fr(sum(vals), len(vals))
def test_positivity_and_input_checks():
with pytest.raises(ValueError):
aipw_ate([1, 0], [1, 2], [1, Fr(1, 2)], [0, 0], [0, 0])
with pytest.raises(ValueError):
aipw_ate([1, 2], [1, 2], [Fr(1, 2)] * 2, [0, 0], [0, 0])
with pytest.raises(ValueError):
aipw_ate([1], [1, 2], [Fr(1, 2)], [0], [0])
with pytest.raises(ValueError):
aipw_ate([], [], [], [], [])
def test_least_squares_and_logistic_fits():
rows = [[Fr(1), Fr(v)] for v in range(5)]
y = [Fr(3 + 2 * v) for v in range(5)]
assert fit_least_squares(rows, y) == [3, 2]
# logistic: the score equations hold at the fitted coefficients
rng = random.Random(3)
xs = [rng.uniform(-2, 2) for _ in range(300)]
t = [1 if rng.random() < 1 / (1 + math.exp(-(0.5 + 1.5 * v))) else 0 for v in xs]
b = fit_logistic([[1.0, v] for v in xs], t)
q = [1 / (1 + math.exp(-(b[0] + b[1] * v))) for v in xs]
assert abs(sum(ti - qi for ti, qi in zip(t, q))) < 1e-8
assert abs(sum((ti - qi) * v for ti, qi, v in zip(t, q, xs))) < 1e-8
def expit(z):
return 1 / (1 + math.exp(-z))
def simulate(n, rng):
"""X uniform on [0, 1]; e(x) = expit(-2 + 4x); Y(t) = x + 2x^2 + t(1 + x) + N(0, 1). True ATE 1.5."""
x, t, y = [], [], []
for _ in range(n):
xi = rng.random()
ti = 1 if rng.random() < expit(-2 + 4 * xi) else 0
x.append(xi), t.append(ti), y.append(xi + 2 * xi * xi + ti * (1 + xi) + rng.gauss(0, 1))
return x, t, y
def test_monte_carlo_one_wrong_model():
"""With r = 40 samples of n = 1000 (seed 2026), the mean estimate stays within 4 standard errors
(plus 0.01 for the finite-n bias) of 1.5 when either model is right, and is far off when both are wrong."""
rng = random.Random(2026)
full_o = lambda v: [1.0, v, v * v]
const = lambda v: [1.0]
full_p = lambda v: [1.0, v]
runs = {"both": [], "outcome wrong": [], "propensity wrong": [], "both wrong": []}
configs = {"both": (full_o, full_p), "outcome wrong": (const, full_p), "propensity wrong": (full_o, const), "both wrong": (const, const)}
r = 40
for _ in range(r):
x, t, y = simulate(1000, rng)
for name, (of, pf) in configs.items():
e, m1, m0 = fit_aipw(x, t, y, of, pf)
runs[name].append(aipw_ate(t, y, e, m1, m0).tau)
for name in ("both", "outcome wrong", "propensity wrong"):
v = runs[name]
tol = 4 * statistics.stdev(v) / math.sqrt(r) + 0.01
assert abs(statistics.mean(v) - 1.5) < tol, name
assert statistics.mean(runs["both wrong"]) - 1.5 > 0.7
def test_interval_shape():
rng = random.Random(9)
x, t, y = simulate(400, rng)
e, m1, m0 = fit_aipw(x, t, y, lambda v: [1.0, v, v * v], lambda v: [1.0, v])
est, lo, hi = aipw_interval(t, y, e, m1, m0, alpha=0.05)
se = math.sqrt(aipw_variance(t, y, e, m1, m0))
assert lo < est < hi
assert abs((hi - lo) - 2 * 1.959963984540054 * se) < 1e-9
History
Robins, Rotnitzky and Zhao (1994) studied regression with covariates that are missing for some units, and showed that every regular estimator is, in the limit, an inverse probability weighted estimating equation plus an augmentation term; the best augmentation is the conditional mean of the missing part, which gives the form used here. Scharfstein, Rotnitzky and Robins (1999) pointed out that the augmented estimator stays consistent if either the missingness model or the outcome model is right, and the name "doubly robust" followed. Hahn (1998) derived the efficiency bound for the ATE. Bang and Robins (2005) wrote the doubly robust estimators for missing data and causal inference in a common form. Kang and Schafer (2007) showed by simulation that the property gives no protection when both models are wrong and the weights are large, which led to a long discussion and to the targeted and cross-fitted versions of the method. Tsiatis (2006) gives the theory in a textbook.
References
- James M. Robins, Andrea Rotnitzky and Lue Ping Zhao, Estimation of regression coefficients when some regressors are not always observed, Journal of the American Statistical Association 89(427), 1994, pp. 846 to 866 (augmented inverse probability weighted estimating equations and the efficient member of the class)
- Jinyong Hahn, On the role of the propensity score in efficient semiparametric estimation of average treatment effects, Econometrica 66(2), 1998, pp. 315 to 331 (the semiparametric efficiency bound for the ATE)
- Daniel O. Scharfstein, Andrea Rotnitzky and James M. Robins, Adjusting for nonignorable drop-out using semiparametric nonresponse models, Journal of the American Statistical Association 94(448), 1999, pp. 1096 to 1120, with the discussion and rejoinder in the same issue (the augmented estimator is consistent if either working model is right)
- Heejung Bang and James M. Robins, Doubly robust estimation in missing data and causal inference models, Biometrics 61(4), 2005, pp. 962 to 973 (doubly robust estimators, including the regression on a clever covariate)
- Joseph D. Y. Kang and Joseph L. Schafer, Demystifying double robustness, a comparison of alternative strategies for estimating a population mean from incomplete data, Statistical Science 22(4), 2007, pp. 523 to 539 (simulations in which both working models are slightly wrong and the propensities are near 0)
- Anastasios A. Tsiatis, Semiparametric Theory and Missing Data, Springer, 2006, Chapter 9 (augmented inverse probability weighted complete-case estimators) and Chapter 13 (the double-robust estimator of the average causal treatment effect, pp. 323 to 337)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag T508RZ Edit this page History Report an error Markdown