Algorithm Search⌘K

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
Properties
deterministicdoubly robustneeds positivitysingle passnot stays in outcome rangeunbiased with one correct fixed model
Origin
James M. Robins, Andrea Rotnitzky, Lue Ping Zhao, 1994

Augmented inverse probability weighting (AIPW) estimates the average treatment effect τ=E[Y(1)−Y(0)]\tau = \mathbb{E}[Y(1) - Y(0)] with two working models: a model e~(x)\tilde e(x) of the propensity score and models m1(x)m_1(x) and m0(x)m_0(x) 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 τ\tau 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 Y(1)Y(1) and Y(0)Y(0), a treatment T∈{0,1}T \in \{0, 1\} and covariates XX measured before treatment, and the units are independent draws from one distribution. The estimand is τ=E[Y(1)−Y(0)]\tau = \mathbb{E}[Y(1) - Y(0)]. The assumptions are consistency with SUTVA (Y=TY(1)+(1−T)Y(0)Y = TY(1) + (1 - T)Y(0), no interference, no hidden versions of treatment), ignorability (Y(0),Y(1))⊥T∣X(Y(0), Y(1)) \perp T \mid X, and positivity 0<e(X)<10 < e(X) < 1. With e(x)=Pr⁡[T=1∣X=x]e(x) = \Pr[T = 1 \mid X = x] and μt(x)=E[Y∣T=t,X=x]\mu_t(x) = \mathbb{E}[Y \mid T = t, X = x], there are two identification formulas,

τ=E[μ1(X)−μ0(X)]=E[TYe(X)−(1−T)Y1−e(X)],\tau = \mathbb{E}\big[\mu_1(X) - \mu_0(X)\big] = \mathbb{E}\left[\frac{TY}{e(X)} - \frac{(1 - T)Y}{1 - e(X)}\right],

the first by standardization (the g-formula) and the second by weighting. AIPW uses a third formula that combines them:

τ=E[μ1(X)−μ0(X)+T(Y−μ1(X))e(X)−(1−T)(Y−μ0(X))1−e(X)].\tau = \mathbb{E}\left[\mu_1(X) - \mu_0(X) + \frac{T(Y - \mu_1(X))}{e(X)} - \frac{(1 - T)(Y - \mu_0(X))}{1 - e(X)}\right].

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 nn units with (Ti,Yi)(T_i, Y_i) and three numbers from the working models: e~i=e~(Xi)∈(0,1)\tilde e_i = \tilde e(X_i) \in (0, 1), m1i=m1(Xi)m_{1i} = m_1(X_i) and m0i=m0(Xi)m_{0i} = m_0(X_i). A usual choice fits e~\tilde e by logistic regression of TT on features of XX, and fits mtm_t by least squares of YY on features of XX among the units with T=tT = t. The output is the estimate

τ^=1n∑i=1nψi,ψi=m1i−m0i+Ti(Yi−m1i)e~i−(1−Ti)(Yi−m0i)1−e~i,\hat\tau = \frac1n\sum_{i=1}^n \psi_i, \qquad \psi_i = m_{1i} - m_{0i} + \frac{T_i(Y_i - m_{1i})}{\tilde e_i} - \frac{(1 - T_i)(Y_i - m_{0i})}{1 - \tilde e_i},

its two parts μ^1\hat\mu_1 and μ^0\hat\mu_0 (estimates of E[Y(1)]\mathbb{E}[Y(1)] and E[Y(0)]\mathbb{E}[Y(0)]), and a standard error. With m1=m0=0m_1 = m_0 = 0 the estimate is the Horvitz-Thompson form of IPW. Without the two residual terms it is the regression (standardization) estimate.

The algorithm

  1. AIPW-ATE(T, Y, ẽ, m1, m0) ▷ n units; needs 0 < ẽ_i < 1
  2. 1s1 ← 0; s0 ← 0
  3. 2for i ← 1 to n do
  4. 3if ẽ_i ≤ 0 or ẽ_i ≥ 1 then error "positivity fails"
  5. 4if T_i = 1 then s1 ← s1 + m1_i + (Y_i - m1_i) / ẽ_i; s0 ← s0 + m0_i
  6. 5else s1 ← s1 + m1_i; s0 ← s0 + m0_i + (Y_i - m0_i) / (1 - ẽ_i)
  7. 6μ1 ← s1 / n; μ0 ← s0 / n
  8. 7return (μ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 e~\tilde e by Newton-Raphson on the logistic log-likelihood and stops when the largest coefficient step is below 10−1010^{-10}, 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, n(τ^−τ)\sqrt n(\hat\tau - \tau) is asymptotically normal with variance V=E[(ψ−τ)2]V = \mathbb{E}[(\psi - \tau)^2], and fitting the models adds nothing to VV in the limit (Robins, Rotnitzky and Zhao 1994; Tsiatis 2006). The plug-in estimate is

v=Sψ2n,Sψ2=1n−1∑i=1n(ψi−τ^)2,v = \frac{S_\psi^2}{n}, \qquad S_\psi^2 = \frac{1}{n - 1}\sum_{i=1}^n (\psi_i - \hat\tau)^2,

with divisor n−1n - 1, and τ^±z1−α/2v\hat\tau \pm z_{1 - \alpha/2}\sqrt v is a normal confidence interval of approximate level 1−α1 - \alpha. If one model is wrong, τ^\hat\tau stays consistent but vv is not always right; a sandwich variance of the joint M-estimator that stacks the model fits and ψ\psi, or the bootstrap of the whole procedure, takes the model fits into account.

Example

The eight patients of the IPW page have a stratum xx (0 mild, 1 severe), and the design treated mild patients with probability 1/41/4 and severe patients with probability 3/43/4.

unit 1 2 3 4 5 6 7 8
xx 0 0 0 0 0 1 1 1
TT 1 1 0 0 0 1 1 0
YY 8 7 6 5 7 4 3 1
design ee 1/4 1/4 1/4 1/4 1/4 3/4 3/4 3/4

Take a poor outcome model that ignores xx: m1=11/2m_1 = 11/2 (the treated mean) and m0=19/4m_0 = 19/4 (the control mean), with the design propensities. Line L4 gives the treated units the terms 112+4(8−112)=312\tfrac{11}2 + 4(8 - \tfrac{11}2) = \tfrac{31}2, 112+4(7−112)=232\tfrac{11}2 + 4(7 - \tfrac{11}2) = \tfrac{23}2, 112+43(4−112)=72\tfrac{11}2 + \tfrac43(4 - \tfrac{11}2) = \tfrac72 and 112+43(3−112)=136\tfrac{11}2 + \tfrac43(3 - \tfrac{11}2) = \tfrac{13}6 in s1s_1, and line L5 adds 11/211/2 for each of the four controls, so s1=164/3s_1 = 164/3 and μ^1=41/6\hat\mu_1 = 41/6. In the same way s0=4⋅194+(194+53)+(194+13)+(194+3)+(194−15)=28s_0 = 4 \cdot \tfrac{19}4 + (\tfrac{19}4 + \tfrac53) + (\tfrac{19}4 + \tfrac13) + (\tfrac{19}4 + 3) + (\tfrac{19}4 - 15) = 28 and μ^0=7/2\hat\mu_0 = 7/2. So τ^=41/6−7/2=10/3\hat\tau = 41/6 - 7/2 = 10/3.

The table puts this next to the other choices of the working models. The stratified estimate, 58(7.5−6)+38(3.5−1)=15/8\tfrac58(7.5 - 6) + \tfrac38(3.5 - 1) = 15/8, is the reference.

propensity outcome models τ^\hat\tau
design ee m=0m = 0 (pure IPW, Horvitz-Thompson) 31/631/6
design ee arm means, ignore xx 10/310/3
design ee cell means m1=(7.5,3.5)m_1 = (7.5, 3.5), m0=(6,1)m_0 = (6, 1) 15/815/8
1/21/2 for all, ignores xx arm means, ignore xx 3/43/4 (the naive difference)
1/21/2 for all, ignores xx cell means 15/815/8
empirical 2/52/5 and 2/32/3 arm means, ignore xx 15/815/8
empirical 2/52/5 and 2/32/3 m=0m = 0 15/815/8

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 xx does the estimate fall back to the naive 3/43/4. The proofs show that both exact agreements with 15/815/8 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 10/310/3, not 15/815/8: double robustness is a statement about the mean, not about each sample.

The same effect in the population. Let Pr⁡[X=1]=1/2\Pr[X = 1] = 1/2, e(0)=1/4e(0) = 1/4, e(1)=3/4e(1) = 3/4, μ1(0)=7\mu_1(0) = 7, μ0(0)=6\mu_0(0) = 6, μ1(1)=4\mu_1(1) = 4 and μ0(1)=1\mu_0(1) = 1, so τ=12⋅1+12⋅3=2\tau = \tfrac12 \cdot 1 + \tfrac12 \cdot 3 = 2. With m=0m = 0 and the wrong propensity e~=1/2\tilde e = 1/2, the bias formula of the proofs gives E[ψ]−τ=−34−54=−2\mathbb{E}[\psi] - \tau = -\tfrac34 - \tfrac54 = -2, so E[ψ]=0\mathbb{E}[\psi] = 0. Make either model right and the bias is exactly 0.

Correctness

The proofs establish, in exact arithmetic:

  • the loop computes the mean of the ψi\psi_i;
  • the bias identity: for fixed working models, E[ψ]−τ=E[(e/e~−1)(μ1−m1)]−E[((1−e)/(1−e~)−1)(μ0−m0)]\mathbb{E}[\psi] - \tau = \mathbb{E}[(e/\tilde e - 1)(\mu_1 - m_1)] - \mathbb{E}[((1 - e)/(1 - \tilde e) - 1)(\mu_0 - m_0)], so the mean is τ\tau if e~=e\tilde e = e or mt=μtm_t = \mu_t (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 XX, the empirical propensities or the cell means each give the stratified estimate exactly.

The asymptotic normality, the consistency of vv 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 ii has treatment Ti∈{0,1}T_i \in \{0, 1\}, outcome YiY_i, a propensity value e~i\tilde e_i with 0<e~i<10 < \tilde e_i < 1 and two outcome predictions m1im_{1i} and m0im_{0i}. Write

ψi=m1i−m0i+Ti(Yi−m1i)e~i−(1−Ti)(Yi−m0i)1−e~i.\psi_i = m_{1i} - m_{0i} + \frac{T_i(Y_i - m_{1i})}{\tilde e_i} - \frac{(1 - T_i)(Y_i - m_{0i})}{1 - \tilde e_i}.

All arithmetic is exact.

Lemma 1 (the loop). AIPW-ATE returns μ^1=1n∑i(m1i+Ti(Yi−m1i)/e~i)\hat\mu_1 = \frac1n\sum_i \big(m_{1i} + T_i(Y_i - m_{1i})/\tilde e_i\big), μ^0=1n∑i(m0i+(1−Ti)(Yi−m0i)/(1−e~i))\hat\mu_0 = \frac1n\sum_i\big(m_{0i} + (1 - T_i)(Y_i - m_{0i})/(1 - \tilde e_i)\big) and τ^=μ^1−μ^0=1n∑iψi\hat\tau = \hat\mu_1 - \hat\mu_0 = \frac1n\sum_i\psi_i.

Proof. Line L1 sets s1=s0=0s_1 = s_0 = 0, and the loop L2 visits each unit once. Line L3 changes nothing. For a treated unit, line L4 adds m1i+(Yi−m1i)/e~im_{1i} + (Y_i - m_{1i})/\tilde e_i to s1s_1 and m0im_{0i} to s0s_0; these are the unit's terms of the two sums, because Ti=1T_i = 1 and 1−Ti=01 - T_i = 0. For a control, line L5 adds m1im_{1i} to s1s_1 and m0i+(Yi−m0i)/(1−e~i)m_{0i} + (Y_i - m_{0i})/(1 - \tilde e_i) to s0s_0, again the unit's terms. Line L6 divides by nn, and the difference of the two sums is ∑iψi\sum_i \psi_i term by term. □\square

The double robustness identity

Here the units (Xi,Ti,Yi(0),Yi(1))(X_i, T_i, Y_i(0), Y_i(1)) are independent copies of (X,T,Y(0),Y(1))(X, T, Y(0), Y(1)). Let e(x)=Pr⁡[T=1∣X=x]e(x) = \Pr[T = 1 \mid X = x] be the true propensity and μt(x)=E[Y(t)∣X=x]\mu_t(x) = \mathbb{E}[Y(t) \mid X = x] the true outcome regressions. Assume consistency Y=TY(1)+(1−T)Y(0)Y = TY(1) + (1 - T)Y(0), ignorability (Y(0),Y(1))⊥T∣X(Y(0), Y(1)) \perp T \mid X, positivity 0<e(X)<10 < e(X) < 1, and E∣Y(t)∣<∞\mathbb{E}|Y(t)| < \infty for t=0,1t = 0, 1. The working models are fixed functions e~(x)\tilde e(x), m1(x)m_1(x), m0(x)m_0(x) that do not depend on the sample, with 0<e~(X)<10 < \tilde e(X) < 1, and with mt(X)m_t(X), mt(X)/e~(X)m_t(X)/\tilde e(X) and mt(X)/(1−e~(X))m_t(X)/(1 - \tilde e(X)) integrable. Put e~i=e~(Xi)\tilde e_i = \tilde e(X_i) and mti=mt(Xi)m_{ti} = m_t(X_i), and let ψ\psi be the score of a generic unit.

Theorem 2 (bias identity). With τ=E[Y(1)−Y(0)]\tau = \mathbb{E}[Y(1) - Y(0)],

E[ψ]−τ=E[(e(X)e~(X)−1)(μ1(X)−m1(X))]−E[(1−e(X)1−e~(X)−1)(μ0(X)−m0(X))].\mathbb{E}[\psi] - \tau = \mathbb{E}\left[\left(\frac{e(X)}{\tilde e(X)} - 1\right)\big(\mu_1(X) - m_1(X)\big)\right] - \mathbb{E}\left[\left(\frac{1 - e(X)}{1 - \tilde e(X)} - 1\right)\big(\mu_0(X) - m_0(X)\big)\right].

Proof. By consistency TY=TY(1)T Y = T Y(1). By ignorability T⊥Y(1)∣XT \perp Y(1) \mid X, so E[TY∣X]=e(X)μ1(X)\mathbb{E}[TY \mid X] = e(X)\mu_1(X), and E[Tm1(X)∣X]=e(X)m1(X)\mathbb{E}[T m_1(X) \mid X] = e(X)m_1(X). Since e~(X)\tilde e(X) is a function of XX,

E[T(Y−m1(X))e~(X) | X]=e(X)e~(X)(μ1(X)−m1(X)).\mathbb{E}\left[\frac{T(Y - m_1(X))}{\tilde e(X)} \,\middle|\, X\right] = \frac{e(X)}{\tilde e(X)}\big(\mu_1(X) - m_1(X)\big).

In the same way (1−T)Y=(1−T)Y(0)(1 - T)Y = (1 - T)Y(0) and T⊥Y(0)∣XT \perp Y(0) \mid X give E[(1−T)(Y−m0(X))/(1−e~(X))∣X]=1−e(X)1−e~(X)(μ0(X)−m0(X))\mathbb{E}[(1 - T)(Y - m_0(X))/(1 - \tilde e(X)) \mid X] = \frac{1 - e(X)}{1 - \tilde e(X)}(\mu_0(X) - m_0(X)). The integrability conditions make every term integrable (as in the identification proof of the IPW page, with absolute values first). So

E[ψ∣X]=m1−m0+ee~(μ1−m1)−1−e1−e~(μ0−m0),\mathbb{E}[\psi \mid X] = m_1 - m_0 + \frac{e}{\tilde e}(\mu_1 - m_1) - \frac{1 - e}{1 - \tilde e}(\mu_0 - m_0),

with every function evaluated at XX. Subtract μ1−μ0=(μ1−m1)−(μ0−m0)+(m1−m0)\mu_1 - \mu_0 = (\mu_1 - m_1) - (\mu_0 - m_0) + (m_1 - m_0):

E[ψ∣X]−(μ1−μ0)=(ee~−1)(μ1−m1)−(1−e1−e~−1)(μ0−m0).\mathbb{E}[\psi \mid X] - (\mu_1 - \mu_0) = \left(\frac{e}{\tilde e} - 1\right)(\mu_1 - m_1) - \left(\frac{1 - e}{1 - \tilde e} - 1\right)(\mu_0 - m_0).

Take expectations. By the tower property of conditional expectation, E[E[ψ∣X]]=E[ψ]\mathbb{E}[\mathbb{E}[\psi \mid X]] = \mathbb{E}[\psi], and E[μ1(X)−μ0(X)]=τ\mathbb{E}[\mu_1(X) - \mu_0(X)] = \tau. □\square

Corollary 3 (double robustness). If e~=e\tilde e = e, or if m1=μ1m_1 = \mu_1 and m0=μ0m_0 = \mu_0, then E[ψ]=τ\mathbb{E}[\psi] = \tau. So with fixed working models of which at least one is right, E[τ^]=τ\mathbb{E}[\hat\tau] = \tau, and τ^→τ\hat\tau \to \tau almost surely by the strong law of large numbers.

Proof. If e~=e\tilde e = e, then e/e~−1=0e/\tilde e - 1 = 0 and (1−e)/(1−e~)−1=0(1 - e)/(1 - \tilde e) - 1 = 0 for every xx. If mt=μtm_t = \mu_t, then μt−mt=0\mu_t - m_t = 0. In both cases each product in Theorem 2 is 0 for every xx. By Lemma 1 and linearity of expectation, E[τ^]=E[ψ]=τ\mathbb{E}[\hat\tau] = \mathbb{E}[\psi] = \tau. The ψi\psi_i are independent and identically distributed with finite mean, so the strong law applies. □\square

Corollary 4 (product bound). If e~(X)∈[c,1−c]\tilde e(X) \in [c, 1 - c] for a constant c>0c > 0, and ∥f∥=(E[f(X)2])1/2\|f\| = (\mathbb{E}[f(X)^2])^{1/2}, then

∣E[ψ]−τ∣≤1c ∥e−e~∥ (∥μ1−m1∥+∥μ0−m0∥).|\mathbb{E}[\psi] - \tau| \le \frac1c\,\|e - \tilde e\|\,\big(\|\mu_1 - m_1\| + \|\mu_0 - m_0\|\big).

Proof. e/e~−1=(e−e~)/e~e/\tilde e - 1 = (e - \tilde e)/\tilde e and (1−e)/(1−e~)−1=(e~−e)/(1−e~)(1 - e)/(1 - \tilde e) - 1 = (\tilde e - e)/(1 - \tilde e), and both denominators are at least cc. Apply the Cauchy-Schwarz inequality to each term of Theorem 2. □\square

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 e^\hat e, m^1\hat m_1, m^0\hat m_0 be estimated from the sample, and suppose there are fixed functions eˉ\bar e, mˉ1\bar m_1, mˉ0\bar m_0 with eˉ(x)∈[c,1−c]\bar e(x) \in [c, 1 - c] for all xx and E∣mˉt(X)∣<∞\mathbb{E}|\bar m_t(X)| < \infty, such that δn=sup⁡x∣e^(x)−eˉ(x)∣+∑tsup⁡x∣m^t(x)−mˉt(x)∣→0\delta_n = \sup_x |\hat e(x) - \bar e(x)| + \sum_t \sup_x |\hat m_t(x) - \bar m_t(x)| \to 0 in probability. If eˉ=e\bar e = e or (mˉ1,mˉ0)=(μ1,μ0)(\bar m_1, \bar m_0) = (\mu_1, \mu_0), then τ^→τ\hat\tau \to \tau in probability.

Proof. Write τ^(e^,m^)\hat\tau(\hat e, \hat m) and τ^(eˉ,mˉ)\hat\tau(\bar e, \bar m) for the estimate with the estimated and the limit functions. On the event δn<c/2\delta_n < c/2, whose probability tends to 1, every e^(Xi)\hat e(X_i) lies in [c/2,1−c/2][c/2, 1 - c/2]. For a treated unit,

Yi−m^1ie^i−Yi−mˉ1ieˉi=(Yi−mˉ1i)(1e^i−1eˉi)−m^1i−mˉ1ie^i,\frac{Y_i - \hat m_{1i}}{\hat e_i} - \frac{Y_i - \bar m_{1i}}{\bar e_i} = (Y_i - \bar m_{1i})\left(\frac{1}{\hat e_i} - \frac{1}{\bar e_i}\right) - \frac{\hat m_{1i} - \bar m_{1i}}{\hat e_i},

and ∣1/e^i−1/eˉi∣=∣eˉi−e^i∣/(e^ieˉi)≤2δn/c2|1/\hat e_i - 1/\bar e_i| = |\bar e_i - \hat e_i|/(\hat e_i\bar e_i) \le 2\delta_n/c^2, so the absolute value is at most (2/c2) δn∣Yi−mˉ1i∣+(2/c) δn(2/c^2)\,\delta_n|Y_i - \bar m_{1i}| + (2/c)\,\delta_n. The control term has the same bound with mˉ0\bar m_0, and the two mm terms differ by at most 2δn2\delta_n. Hence

∣τ^(e^,m^)−τ^(eˉ,mˉ)∣≤δn(2+4c+2c2⋅1n∑i(∣Yi−mˉ1i∣+∣Yi−mˉ0i∣)).|\hat\tau(\hat e, \hat m) - \hat\tau(\bar e, \bar m)| \le \delta_n\left(2 + \frac{4}{c} + \frac{2}{c^2}\cdot\frac1n\sum_i \big(|Y_i - \bar m_{1i}| + |Y_i - \bar m_{0i}|\big)\right).

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, τ^(eˉ,mˉ)→τ\hat\tau(\bar e, \bar m) \to \tau. □\square

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 eˉ\bar e and mˉ\bar m), whether or not the models are right.

Exact identities with a discrete covariate

Let XX take finitely many values, let stratum xx have nxn_x units, n1x≥1n_{1x} \ge 1 treated and n0x≥1n_{0x} \ge 1 controls, and let Yˉtx\bar Y_{tx} be the mean outcome of arm tt in stratum xx. The stratified estimate is τ^S=∑xnxn(Yˉ1x−Yˉ0x)\hat\tau_S = \sum_x \frac{n_x}{n}(\bar Y_{1x} - \bar Y_{0x}).

Theorem 6. (a) If e~(x)=n1x/nx\tilde e(x) = n_{1x}/n_x, then τ^=τ^S\hat\tau = \hat\tau_S for all functions m1(x),m0(x)m_1(x), m_0(x). (b) If mt(x)=Yˉtxm_t(x) = \bar Y_{tx}, then τ^=τ^S\hat\tau = \hat\tau_S for every function e~(x)\tilde e(x) with values in (0,1)(0, 1).

Proof. Fix a stratum xx and look at its share of nμ^1n\hat\mu_1, which is nxm1(x)+∑i: Xi=x, Ti=1(Yi−m1(x))/e~(x)=nxm1(x)+n1x(Yˉ1x−m1(x))/e~(x)n_x m_1(x) + \sum_{i:\,X_i = x,\,T_i = 1}(Y_i - m_1(x))/\tilde e(x) = n_x m_1(x) + n_{1x}(\bar Y_{1x} - m_1(x))/\tilde e(x). In case (a), n1x/e~(x)=nxn_{1x}/\tilde e(x) = n_x, so the share is nxYˉ1xn_x\bar Y_{1x}. In case (b), Yˉ1x−m1(x)=0\bar Y_{1x} - m_1(x) = 0, so the share is again nxYˉ1xn_x\bar Y_{1x}. The same steps with 1−e~(x)=n0x/nx1 - \tilde e(x) = n_{0x}/n_x or m0(x)=Yˉ0xm_0(x) = \bar Y_{0x} give the share nxYˉ0xn_x\bar Y_{0x} of nμ^0n\hat\mu_0. Sum over the strata and divide by nn. □\square

Theorem 6 is the sample version of Corollary 3: the empirical propensity and the cell means are the saturated estimates of ee and μt\mu_t, and either one alone gives the stratified estimate exactly.

What is not proved here

The asymptotic normality of n(τ^−τ)\sqrt n(\hat\tau - \tau) with estimated working models, the fact that the plug-in variance Sψ2/nS_\psi^2/n is consistent when both models are right, and the fact that the variance E[(ψ−τ)2]\mathbb{E}[(\psi - \tau)^2] with the true ee and μt\mu_t 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 Θ(n)\Theta(n) time in the best and the worst case and Θ(1)\Theta(1) extra space, and it can run on a stream. The scores ψi\psi_i for vv need a second pass, or running sums of ψi\psi_i and ψi2\psi_i^2. The model fits usually cost more: with pp propensity features and qq outcome features, the Newton-Raphson fit costs O(np2+p3)O(n p^2 + p^3) per step and the two least squares fits O(nq2+q3)O(n q^2 + q^3).

Properties

  • Doubly robust. For fixed working models, the mean of ψ\psi is τ\tau if either the propensity model or both outcome models are right. A simulation shows it: XX uniform on [0,1][0, 1], e(x)=expit⁡(−2+4x)e(x) = \operatorname{expit}(-2 + 4x), Y=x+2x2+T(1+x)+εY = x + 2x^2 + T(1 + x) + \varepsilon with standard normal ε\varepsilon, true ATE 1.5, n=1000n = 1000, 200 samples (seed 2026). The right outcome model uses 1,x,x21, x, x^2 in each arm, the wrong one a constant; the right propensity model is logistic in 1,x1, x, the wrong one a constant.
working models mean of τ^\hat\tau 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 ee and μt\mu_t, the variance E[(ψ−τ)2]\mathbb{E}[(\psi - \tau)^2] equals Hahn's (1998) bound E[σ12(X)/e(X)+σ02(X)/(1−e(X))+(μ1(X)−μ0(X)−τ)2]\mathbb{E}\big[\sigma_1^2(X)/e(X) + \sigma_0^2(X)/(1 - e(X)) + (\mu_1(X) - \mu_0(X) - \tau)^2\big], where σt2(x)=Var⁡[Y(t)∣X=x]\sigma_t^2(x) = \operatorname{Var}[Y(t) \mid X = x]. The function ψ−τ\psi - \tau 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, μ^1\hat\mu_1 is not an average of the observed outcomes and can fall outside their range, for a binary outcome even outside [0,1][0, 1]. TMLE fixes this.
  • Randomized experiments. If e~\tilde e is the known assignment probability, τ^\hat\tau 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 T/e~(X)T/\tilde e(X) and (1−T)/(1−e~(X))(1 - T)/(1 - \tilde e(X)) 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 ψi\psi_i 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 (T(Y−m0(X))−(1−T) e~(X)(Y−m0(X))/(1−e~(X)))/Pr⁡[T=1]\big(T(Y - m_0(X)) - (1 - T)\,\tilde e(X)(Y - m_0(X))/(1 - \tilde e(X))\big)/\Pr[T = 1] 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 XX 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 XX 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 XX.
  • Weights near the positivity limit. The residual terms carry the weights 1/e~1/\tilde e and 1/(1−e~)1/(1 - \tilde e). A unit with e~=0.01\tilde e = 0.01 and a residual of 5 moves μ^1\hat\mu_1 by 500/n500/n.
  • 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, vv 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 XX for both arms is wrong when the effect varies with XX.
  • 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.

augmented_inverse_probability_weighting.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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)
  6. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example