Module contents
Lesson 15 of 28Advanced 115 min

Doubly robust estimation, influence functions and semiparametric efficiency

Combine outcome and treatment models through AIPW, derive double robustness and efficient influence functions, examine Hahn’s bound, and compare one-step estimation with TMLE under explicit assumptions.

After this lesson you can

  • Derive AIPW and prove double robustness using the product-error decomposition.
  • Calculate efficient influence functions for ATE and a missing-outcome mean.
  • Construct standard errors and intervals from empirical influence variance under suitable conditions.
  • Implement AIPW and TMLE and compare them with IPW and g-computation under correct and incorrect specifications.
  • Explain a one-step estimator as first-order bias correction of a plug-in.

Before you start

Two ways to be wrong

You want to evaluate a training program using historical records. In the previous lesson you estimated its effect by modeling the outcome or weighting by the probability of receiving training. An outcome model may extrapolate badly; a poorly estimated propensity may weight toward the wrong population. Can we combine both pieces so an error in one does not necessarily ruin the answer?

Yes, under conditional ignorability, consistency, absence of interference, positivity, and appropriate statistical conditions. But “doubly robust” does not mean it tolerates unmeasured confounding, lack of support, or two incorrect models. Nor does it guarantee a reliable interval when weights are extreme.

InteractiveSpecification grid

Each column changes the propensity model and each row the outcome model. The dashed line marks the true effect; the three distributions share a height scale within each cell.

  • g-computation
  • IPW
  • AIPW
  • True effect

Model: X is Bernoulli(0.5), T is Bernoulli with probability 0.2 if X = 0 and 0.8 if X = 1, and Y = T + 1.2X + 0.8ε, with ε standard normal. In each replicate, correct models estimate Y means by treatment and X, and treatment probabilities by X; incorrect ones omit X and use only treatment-specific means or frequencies. IPW is Horvitz-Thompson. Models are fitted and evaluated on the same sample, suitable here for these simple parametric fits but not a guarantee of validity with flexible learners.

In this saturated binary simulation, fitting equations make AIPW exactly equal to g when the outcome model is correct and to IPW when propensity is correct. This sample-by-sample equality does not hold for arbitrary models. Each histogram uses bins of 0.1; values outside 0 to 2.5 accumulate in the end bars. Histograms fluctuate across replicates: double robustness is an asymptotic property, does not guarantee accuracy for each sample, and does not protect against both models failing.

Mean g0.999
Mean IPW0.999
Mean AIPW0.999
True effect1.000
Compare estimator distributions when each model is correct or a covariate is omitted.

AIPW: prediction plus weighted residuals

Let O=(X,T,Y)O=(X,T,Y) with T∈{0,1}T\in\{0,1\}, e(x)=P(T=1∣X=x)e(x)=P(T=1\mid X=x) and μt(x)=E[Y∣T=t,X=x]\mu_t(x)=E[Y\mid T=t,X=x]. With pretreatment covariates and the earlier causal assumptions, ATE is τ=E[μ1(X)−μ0(X)]\tau=E[\mu_1(X)-\mu_0(X)]. The augmented inverse probability weighting or AIPW estimator replaces unknown functions with models and adds residuals:

τ^AIPW=Pn[μ^1(X)−μ^0(X)+T{Y−μ^1(X)}e^(X)−(1−T){Y−μ^0(X)}1−e^(X)].\widehat\tau_{\rm AIPW} =\mathbb P_n\left[ \widehat\mu_1(X)-\widehat\mu_0(X) +\frac{T\{Y-\widehat\mu_1(X)\}}{\widehat e(X)} -\frac{(1-T)\{Y-\widehat\mu_0(X)\}}{1-\widehat e(X)} \right].

Here Pn\mathbb P_n is the sample average. The first difference is g-computation; the other terms correct its observed residuals, weighted as in IPW. A person’s outcome under the unobserved alternative remains unobserved: the correction uses conditional independence and assignment probabilities.

To understand double robustness, first consider fixed functions e~,μ~0,μ~1\widetilde e,\widetilde\mu_0,\widetilde\mu_1 with positive denominators and integrable contributions. Conditioning on XX and subtracting τ\tau, the expectation of the uncentered expression is

E[(e~−e){μ~1−μ1e~+μ~0−μ01−e~}].E\left[ (\widetilde e-e) \left\{\frac{\widetilde\mu_1-\mu_1}{\widetilde e} +\frac{\widetilde\mu_0-\mu_0}{1-\widetilde e}\right\} \right].

Check arm by arm: E[T(Y−μ~1)/e~∣X]=e(μ1−μ~1)/e~E[T(Y-\widetilde\mu_1)/\widetilde e\mid X]=e(\mu_1-\widetilde\mu_1)/\widetilde e, and the control term is analogous with a negative sign. The expression vanishes if e~=e\widetilde e=e or if both conditional means are correct. If both models fail, their product need not vanish. For estimated functions convergence and control of dependence between fitting and evaluation are also needed: this population identity alone proves neither sample consistency nor normality.

A product of errors and a rate that matters

If e~\widetilde e is bounded away from zero and one, Cauchy–Schwarz bounds absolute bias by a constant times

∥e~−e∥2(∥μ~1−μ1∥2+∥μ~0−μ0∥2).\|\widetilde e-e\|_2 \left(\|\widetilde\mu_1-\mu_1\|_2+\|\widetilde\mu_0-\mu_0\|_2\right).

Therefore the expression is orthogonal to small first-order errors in either piece when the other is true. For an interval centered at scale n\sqrt n, the product is usually required to be op(n−1/2)o_p(n^{-1/2}), alongside other inference conditions. Two errors of order Op(n−1/4)O_p(n^{-1/4}) only ensure product Op(n−1/2)O_p(n^{-1/2}): it may remain as large as the standard error. Two errors op(n−1/4)o_p(n^{-1/4}) suffice for the product, as do unequal rates with a sufficiently small product. Chernozhukov and colleagues state product conditions and use cross-fitting to control overfitting.

InteractiveProduct bias

Height is the exact population bias of AIPW. The point marks selected errors; the grid includes errors of both signs. α increases toward the lower right and γ toward the lower left. Sample size n only determines the path of these errors; it does not generate samples.

α: outcome errorγ: propensity errorα ∈ [−0.08; 0.08]γ ∈ [−0.10; 0.10]
  • Positive bias
  • Negative bias
  • Selected state

Now n ≈ 10,000, α = 0.02530 and γ = 0.03162. Along this particular path, |bias|√n approaches a positive constant as n grows. With a=b=0.25, the product is of order n⁻¹ᐟ² and the ratio does not vanish.

Model: P(X=1)=0.4; e(X)=(0.25; 0.75), μ₀(X)=(0.10; 0.50) and μ₁(X)=(0.55; 0.85). Perturbations are ẽ=e+γ(1,−1), m̃₀=μ₀+α(1,−1) and m̃₁=μ₁+α(1,1). Errors follow α=0.08(n/100)⁻ᵃ and γ=0.10(n/100)⁻ᵇ.

Bias is calculated using E[(ẽ−e)·((m̃₁−μ₁)/ẽ+(m̃₀−μ₀)/(1−ẽ))]. Double robustness eliminates bias if either error is zero; for centered inference a common sufficient condition, along with other assumptions, is that the product of their norms is o(n⁻¹ᐟ²). Particular cancellations can occur. The surface does not calculate coverage or errors of fitted models.

0.25
0.25
4.0
Population AIPW bias0.00306340
Scale 1/√n0.01000
|Bias| × √n0.3063
Both rates and sample size determine bias relative to the n⁻¹ᐟ² scale.

The surface uses a fully specified population model and calculates exact bias, not fabricated experimental results. Change both rates and observe bias multiplied by n\sqrt n. Failure of this ratio to approach zero does not imply inconsistency: bias may matter for a centered first-order approximation.

The influence function as a derivative

A functional Ψ(P)\Psi(P) assigns a parameter to a distribution. Let PεP_\varepsilon be a regular submodel with P0=PP_0=P and score s(O)=∂εlog⁡pε(O)∣ε=0s(O)=\partial_\varepsilon\log p_\varepsilon(O)|_{\varepsilon=0} of mean zero and finite second moment. An efficient influence function ϕP\phi_P represents the derivative via

ddεΨ(Pε)∣ε=0=EP[ϕP(O)s(O)],EP[ϕP(O)]=0.\left.\frac{d}{d\varepsilon}\Psi(P_\varepsilon)\right|_{\varepsilon=0} =E_P[\phi_P(O)s(O)],\qquad E_P[\phi_P(O)]=0.

In the model’s closed tangent space, the canonical representative has minimum norm; other representatives may differ in a direction orthogonal to the tangent space. For the mean Ψ(P)=EP[Y]\Psi(P)=E_P[Y], differentiating the integral gives E[(Y−Ψ)s]E[(Y-\Psi)s], hence ϕP(Y)=Y−Ψ\phi_P(Y)=Y-\Psi if E[Y2]<∞E[Y^2]<\infty. For variance the influence is (Y−EY)2−Var⁡(Y)(Y-EY)^2-\operatorname{Var}(Y) if, for example, E[Y4]<∞E[Y^4]<\infty. These conditions ensure representatives belong to L2(P)L^2(P). The lab checks derivatives by contaminating finite distributions, but numerical checking does not replace proof for all regular submodels.

InteractiveThe one-step correction

The curve shows Bernoulli variance. The starting point uses q; the tangent adds the mean correction calculated under p. This is a population example, not a random sample.

0.000.230.450.00.51.0Success probabilityVariance
  • True functional
  • Plug-in q
  • Linear correction
Comparison

For Y Bernoulli(p), V(p)=p(1−p). The influence function for variance at q is (Y−q)²−q(1−q), whose mean under p is (p−q)(1−2q). The difference between the one-step value and V(p) is exactly (p−q)². The correction removes the first-order term, but the quadratic remainder remains and the line can leave the possible variance range.

0.70
0.25
True variance0.2100
Plug-in0.1875
Mean correction0.2250
One step0.4125
Remaining error0.2025
The tangent removes linear plug-in error; observe the quadratic remainder.

In that figure, for Y∼Bernoulli⁡(p)Y\sim\operatorname{Bernoulli}(p) and plug-in qq, the functional is V(p)=p(1−p)V(p)=p(1-p). The mean under PpP_p of influence evaluated at PqP_q is (p−q)(1−2q)(p-q)(1-2q); adding it to V(q)V(q) leaves exact error (p−q)2(p-q)^2. With data, replace that expectation by an empirical average and there is additional noise. The one-step idea removes linear error, not a promise that the result respects parameter bounds.

Deriving the influence of the average effect

For θ1(P)=EX[μ1(X)]\theta_1(P)=E_X[\mu_1(X)], factor the density as p(x)p(t∣x)p(y∣t,x)p(x)p(t\mid x)p(y\mid t,x) and decompose the score into sX+sT+sYs_X+s_T+s_Y, each component conditionally centered. Differentiating the distribution of XX gives E[(μ1(X)−θ1)sX]E[(\mu_1(X)-\theta_1)s_X]. Differentiating the conditional mean of YY in the treated arm gives

E[Te(X){Y−μ1(X)}sY(O)].E\left[\frac{T}{e(X)}\{Y-\mu_1(X)\}s_Y(O)\right].

The factor T/eT/e cancels the probability of observing the treated arm. The functional does not directly depend on the assignment mechanism; its product with sTs_T has expectation zero. Thus,

ϕ1(O)=Te(X){Y−μ1(X)}+μ1(X)−θ1.\phi_1(O)=\frac{T}{e(X)}\{Y-\mu_1(X)\}+\mu_1(X)-\theta_1.

The same reasoning for arm zero followed by subtraction gives

ϕτ(O)=μ1(X)−μ0(X)−τ+Te(X){Y−μ1(X)}−1−T1−e(X){Y−μ0(X)}.\phi_{\tau}(O)=\mu_1(X)-\mu_0(X)-\tau +\frac{T}{e(X)}\{Y-\mu_1(X)\} -\frac{1-T}{1-e(X)}\{Y-\mu_0(X)\}.

In the observed nonparametric model this representative belongs to the tangent space and is efficient when it has finite second moment. A sufficient condition is uniform positivity and E[Y2]<∞E[Y^2]<\infty; strict positivity alone does not guarantee the weighted variance exists. If TT indicates observation of a missing-at-random outcome, ϕ1\phi_1 is also the influence for its population mean, with ee equal to observation probability. This analogy requires missing-at-random and support assumptions; it does not make every missingness mechanism random.

The Hahn bound

Residuals from both arms never occur simultaneously, have conditional mean zero, and are orthogonal to the term depending only on XX. Therefore

Var⁡(ϕτ)=E[Var⁡(Y∣T=1,X)e(X)+Var⁡(Y∣T=0,X)1−e(X)+{μ1(X)−μ0(X)−τ}2].\operatorname{Var}(\phi_{\tau})= E\left[ \frac{\operatorname{Var}(Y\mid T=1,X)}{e(X)} +\frac{\operatorname{Var}(Y\mid T=0,X)}{1-e(X)} +\{\mu_1(X)-\mu_0(X)-\tau\}^2 \right].

The semiparametric efficiency bound of Hahn is this variance for n(τ^−τ)\sqrt n(\widehat\tau-\tau), or that quantity divided by nn on the estimator’s asymptotic variance scale. It is a lower bound for regular estimators in the model considered, not a promise for small samples or irregular estimators.

Knowing ee removes assignment tangent directions, but the previous influence is already orthogonal to them: conditional on X,TX,T its residuals have zero mean and the remaining term depends only on XX. Thus knowing ee does not reduce this bound for ATE. ATT also depends on the treated covariate distribution and its bound can change when the mechanism is known; do not transfer the conclusion without recalculating the estimand.

One step and inference

A one-step estimator combines Ψ(P^)\Psi(\widehat P) with the average of ϕP^\phi_{\widehat P}. For ATE this gives exactly the AIPW expression above. Under suitable conditions, if both nuisance functions converge to truth, their product error is op(n−1/2)o_p(n^{-1/2}), necessary moments are finite, and the empirical process is controlled, we obtain

n(τ^−τ)=1n∑i=1nϕτ(Oi)+op(1).\sqrt n(\widehat\tau-\tau) =\frac1{\sqrt n}\sum_{i=1}^n\phi_\tau(O_i)+o_p(1).

With i.i.d. observations and positive variance, estimate standard error using the sample standard deviation of centered AIPW contributions divided by n\sqrt n, and construct an approximate normal interval. Cross-fitting trains functions on other folds before evaluating each observation and facilitates conditions with flexible learners; it does not remove rate, support, or moment requirements. The next lesson develops that partition.

If one nuisance converges to an incorrect limit, AIPW can still be consistent by double robustness, but influence calculated as if both were true does not automatically give a valid interval: nuisance estimation may contribute a first-order term. A variance appropriate to the procedure must be justified. The efficiency bound is not reached merely because one model is correct.

TMLE: update the model toward the question

Targeted maximum likelihood estimation updates the initial outcome model to satisfy an influence equation. For binary outcomes, with initial predictions q0,q1q_0,q_1 in (0,1)(0,1) and estimated propensity in (0,1)(0,1), define the clever covariate

H(T,X)=Te^(X)−1−T1−e^(X),logit⁡qε(T,X)=logit⁡qT(X)+εH(T,X).H(T,X)=\frac{T}{\widehat e(X)}-\frac{1-T}{1-\widehat e(X)},\qquad \operatorname{logit}q_\varepsilon(T,X) =\operatorname{logit}q_T(X)+\varepsilon H(T,X).

Fit ε\varepsilon by binomial likelihood using the initial logit as an offset and no additional intercept. If a finite interior solution exists, its first-order condition is Pn[H(Y−qε(T,X))]=0\mathbb P_n[H(Y-q_\varepsilon(T,X))]=0. Then predict both outcomes for each XiX_i using H(1,Xi)=1/e^iH(1,X_i)=1/\widehat e_i and H(0,Xi)=−1/(1−e^i)H(0,X_i)=-1/(1-\widehat e_i); the average difference is TMLE.

Since updated residual correction averages zero, TMLE equals AIPW algebraically when evaluated at updated predictions, not necessarily the initial AIPW. For binary outcomes its predictions lie in [0,1][0,1] and resulting ATE in [−1,1][-1,1]; a one-step estimator can fall outside. This does not guarantee less bias, lower variance, or coverage with poor support. Logistic separation or extreme scores may prevent a finite fluctuation and require diagnosis.

For a continuous outcome with known population bounds L<UL<U, transform YY to [0,1][0,1], use logistic quasi-likelihood fluctuation for the mean, and rescale by U−LU-L. For an unbounded outcome observed extremes are not known bounds; use an appropriate fluctuation and do not claim a nonexistent range guarantee. Van der Laan and Rubin develop targeting and the influence equation.

Lab: AIPW and TMLE from scratch

The following SCM has three strata and twelve observable atoms. The code fits logistic models by maximum likelihood, calculates four estimators, and solves targeting. If separation or a singular matrix appears, it reports this instead of producing a fictitious number.

[ ]aipw tmle setupBrowser
import numpy as np

# SCM con tres estratos; Y(a)|X es Bernoulli con media mu_a(X).
# Las variables exógenas de asignación y resultados son independientes dado X.
p_x = np.array([.35, .4, .25])
levels = np.arange(3.)
def expit(v):
    return 1 / (1 + np.exp(-np.clip(v, -35, 35)))
e_true = expit(-.8+.8*levels)
mu0_true = expit(-1.5+.7*levels)
mu1_true = expit(-.5+.5*levels)
truth = p_x @ (mu1_true - mu0_true)
atoms = np.array([(x,t,y) for x in (0,1,2) for t in (0,1) for y in (0,1)])
ax, at, ay = atoms.T
mu_atom = np.where(at == 1, mu1_true[ax], mu0_true[ax])
probs = p_x[ax] * np.where(at == 1, e_true[ax], 1-e_true[ax]) * np.where(ay == 1, mu_atom, 1-mu_atom)
assert np.isclose(probs.sum(), 1)

def logistic_fit(total,success,correct):
    """MV binomial agrupada: intercepto solo o intercepto y pendiente en X."""
    if np.any(total.sum(axis=1)<=0):
        raise ValueError('Brazo vacío')
    beta0=np.zeros(len(total)); beta1=np.zeros(len(total))
    for _ in range(60):
        pred=expit(beta0[:,None]+beta1[:,None]*levels)
        residual=success-total*pred
        weight=total*pred*(1-pred)
        s0=residual.sum(axis=1); w0=weight.sum(axis=1)
        if np.any(w0<=1e-14): raise ValueError('Logística degenerada')
        if correct:
            s1=(residual*levels).sum(axis=1)
            w1=(weight*levels).sum(axis=1); w2=(weight*levels**2).sum(axis=1)
            det=w0*w2-w1*w1
            if np.any(det<=1e-14): raise ValueError('Información sin rango')
            d0=(s0*w2-s1*w1)/det; d1=(s1*w0-s0*w1)/det
            beta1+=np.clip(d1,-2,2)
        else:
            d0=s0/w0; d1=0
        beta0+=np.clip(d0,-2,2)
        if max(np.max(np.abs(d0)),np.max(np.abs(d1)))<1e-10: break
    else: raise ValueError('Logística sin convergencia o separación')
    return expit(beta0[:,None]+beta1[:,None]*levels)

def estimates(p, correct_e, correct_y):
    """Cuatro estimadores sobre distribuciones empíricas de doce átomos.

    p es una matriz de distribuciones. Los modelos correctos usan X lineal;
    los incorrectos solo tienen intercepto. Todos se ajustan a los mismos datos.
    """
    p = np.atleast_2d(np.asarray(p, float))
    px = np.column_stack([p[:, ax == x].sum(axis=1) for x in (0,1,2)])
    n1 = np.column_stack([p[:, (ax == x) & (at == 1)].sum(axis=1) for x in (0,1,2)])
    ey = np.column_stack([p[:, (ax == x) & (at == 1) & (ay == 1)].sum(axis=1) for x in (0,1,2)])
    cy = np.column_stack([p[:, (ax == x) & (at == 0) & (ay == 1)].sum(axis=1) for x in (0,1,2)])
    if np.any(px <= 0) or np.any(n1 <= 0) or np.any(px-n1 <= 0):
        raise ValueError('Algún estrato o brazo carece de observaciones')
    e=logistic_fit(px,n1,correct_e)
    q1=logistic_fit(n1,ey,correct_y)
    q0=logistic_fit(px-n1,cy,correct_y)
    if np.any((e <= 0)|(e >= 1)|(q0 <= 0)|(q0 >= 1)|(q1 <= 0)|(q1 >= 1)):
        raise ValueError('Nuisance en el borde: TMLE requiere offset finito')
    ee, q0a, q1a = e[:,ax], q0[:,ax], q1[:,ax]
    h = at/ee-(1-at)/(1-ee)
    qa = np.where(at == 1,q1a,q0a)
    g = np.sum(px*(q1-q0),axis=1)
    ipw = np.sum(p*(at*ay/ee-(1-at)*ay/(1-ee)),axis=1)
    aipw = np.sum(p*(q1a-q0a+h*(ay-qa)),axis=1)
    # Submodelo logístico con offset logit(q_T), sin intercepto añadido.
    offset = np.log(qa/(1-qa))
    eps = np.zeros(len(p))
    for _ in range(60):
        updated = expit(offset+eps[:,None]*h)
        score = np.sum(p*h*(ay-updated),axis=1)
        info = np.sum(p*h*h*updated*(1-updated),axis=1)
        if np.any(info <= 1e-14):
            raise ValueError('Fluctuación degenerada')
        step = np.clip(score/info,-2,2)
        eps += step
        if np.max(np.abs(score)) < 1e-11:
            break
    else:
        raise ValueError('Fluctuación TMLE no convergió')
    q1star = expit(np.log(q1/(1-q1))+eps[:,None]/e)
    q0star = expit(np.log(q0/(1-q0))-eps[:,None]/(1-e))
    tmle = np.sum(px*(q1star-q0star),axis=1)
    updated_score = np.sum(p*h*(ay-np.where(at==1,q1star[:,ax],q0star[:,ax])),axis=1)
    assert np.max(np.abs(updated_score)) < 1e-10
    return np.column_stack((g,ipw,aipw,tmle))

def mc_scenario(correct_e, correct_y, seed, repetitions=1000, n=500):
    # La multinomial equivale a repetir la muestra i.i.d. de los doce átomos.
    p = np.random.default_rng(seed).multinomial(n,probs,size=repetitions)/n
    point = estimates(p,correct_e,correct_y)
    # Delta numérico de la función completa del estimador, incluido el ajuste
    # de las nuisances y el targeting. Un paso de contaminación por átomo.
    # Esto es distinto de tratar nuisances estimadas como si fueran fijas.
    delta = 1e-5
    eye = np.eye(12)
    perturbed = ((1-delta)*p[:,None,:]+delta*eye[None,:,:]).reshape(-1,12)
    changed = estimates(perturbed,correct_e,correct_y).reshape(repetitions,12,4)
    influence = (changed-point[:,None,:])/delta
    se = np.sqrt(np.sum(p[:,:,None]*influence**2,axis=1)/n)
    diff = point-truth
    bias = diff.mean(axis=0)
    mse = (diff**2).mean(axis=0)
    coverage = (np.abs(diff)<=1.96*se).mean(axis=0)
    for j,name in enumerate(('G-computación','IPW HT','AIPW','TMLE')):
        mcse = np.sqrt(coverage[j]*(1-coverage[j])/repetitions)
        print(f'{name:14} sesgo={bias[j]:+.4f}, ECM={mse[j]:.5f}, cobertura={coverage[j]:.3f} (EE Monte Carlo={mcse:.3f})')
    return point,se

print(f'ATE poblacional del SCM: {truth:.6f}')
print('Modelos logísticos estimados: intercepto y X lineal o intercepto solo; n=500, 1000 réplicas i.i.d.')

The explicit influence standard error implementation requires the conditions above; this example fits both nuisances with correct specification.

[ ]aipw eif demoBrowser
def aipw_from_scratch(y,t,mu0,mu1,e):
    """AIPW y EE EIF con nuisances dadas; la validez exige condiciones adicionales."""
    y,t,mu0,mu1,e=(np.asarray(v,float) for v in (y,t,mu0,mu1,e))
    if any(v.ndim!=1 or len(v)!=len(y) or not np.isfinite(v).all() for v in (y,t,mu0,mu1,e)):
        raise ValueError('Vectores incompatibles o no finitos')
    if set(np.unique(t))!={0.,1.} or np.any((e<=0)|(e>=1)):
        raise ValueError('Tratamiento o propensity inválido')
    scores=mu1-mu0+t*(y-mu1)/e-(1-t)*(y-mu0)/(1-e)
    return float(scores.mean()),float(np.std(scores,ddof=1)/np.sqrt(len(y)))

rng_demo=np.random.default_rng(151506)
n_demo=800
x_demo=rng_demo.choice(3,n_demo,p=p_x)
t_demo=rng_demo.binomial(1,e_true[x_demo])
y_demo=rng_demo.binomial(1,np.where(t_demo==1,mu1_true[x_demo],mu0_true[x_demo]))
counts=np.array([[np.sum(x_demo==x) for x in (0,1,2)]],float)
treated=np.array([[np.sum((x_demo==x)&(t_demo==1)) for x in (0,1,2)]],float)
success1=np.array([[np.sum((x_demo==x)&(t_demo==1)&(y_demo==1)) for x in (0,1,2)]],float)
success0=np.array([[np.sum((x_demo==x)&(t_demo==0)&(y_demo==1)) for x in (0,1,2)]],float)
e_demo=logistic_fit(counts,treated,True)[0,x_demo]
mu1_demo=logistic_fit(treated,success1,True)[0,x_demo]
mu0_demo=logistic_fit(counts-treated,success0,True)[0,x_demo]
value_demo,se_demo=aipw_from_scratch(y_demo,t_demo,mu0_demo,mu1_demo,e_demo)
print('AIPW con ambas nuisances bien especificadas:',round(value_demo,4),
      'EE EIF:',round(se_demo,4),'ATE verdadero:',round(truth,4))
print('IC normal aproximado al 95%:',np.round([value_demo-1.96*se_demo,value_demo+1.96*se_demo],4))
print('El EE EIF requiere hipótesis de convergencia y regularidad; no lo garantiza solo la doble robustez.')

The following grid generates 1,000 i.i.d. samples of 500 observations per scenario. The multinomial over atoms is equivalent to generating each sample individually. For coverage it numerically differentiates the entire estimator, including nuisance fitting and targeting, against each atom. Thus it does not automatically treat efficient influence as valid variance in misspecified scenarios. Coverage is a Monte Carlo frequency with uncertainty, not a general guarantee.

[ ]aipw tmle grid1Browser
print('Propensión correcta, resultado correcto')
result_cc = mc_scenario(True,True,151501)
[ ]aipw tmle grid2Browser
print('Propensión correcta, resultado incorrecto')
result_ci = mc_scenario(True,False,151502)
[ ]aipw tmle grid3Browser
print('Propensión incorrecta, resultado correcto')
result_ic = mc_scenario(False,True,151503)
[ ]aipw tmle grid4Browser
print('Propensión incorrecta, resultado incorrecto')
result_ii = mc_scenario(False,False,151504)

This cell’s continuous outcome has known population bounds; the binary example uses the same routine on [0,1]. The printed influence standard errors require inference conditions even when the point estimator is doubly robust.

[ ]aipw tmle continuousBrowser
def tmle_bounded(y,t,q0,q1,e,lower,upper):
    """TMLE con fluctuación logística para un resultado de límites conocidos.

    q0 y q1 son predicciones de la media en la escala original, no resultados
    simulados; los límites deben ser poblacionales y fijarse de antemano.
    """
    y,t,q0,q1,e=map(lambda a: np.asarray(a,float),(y,t,q0,q1,e))
    if not all(a.ndim==1 and len(a)==len(y) and np.isfinite(a).all() for a in (y,t,q0,q1,e)):
        raise ValueError('Vectores incompatibles o no finitos')
    if not np.isfinite([lower,upper]).all() or not lower<upper or np.any((y<lower)|(y>upper)):
        raise ValueError('Límites poblacionales inválidos')
    if set(np.unique(t))!={0.,1.} or np.any((e<=0)|(e>=1)):
        raise ValueError('Tratamiento o propensiones inválidas')
    z=(y-lower)/(upper-lower)
    m0=(q0-lower)/(upper-lower);m1=(q1-lower)/(upper-lower)
    if np.any((m0<=0)|(m0>=1)|(m1<=0)|(m1>=1)):
        raise ValueError('Offset infinito: las predicciones deben ser interiores')
    h=t/e-(1-t)/(1-e)
    observed=t*m1+(1-t)*m0
    offset=np.log(observed/(1-observed))
    epsilon=0.
    for _ in range(60):
        updated=expit(offset+epsilon*h)
        score=np.mean(h*(z-updated))
        info=np.mean(h*h*updated*(1-updated))
        if info<=1e-14:
            raise ValueError('Fluctuación degenerada')
        epsilon+=np.clip(score/info,-2,2)
        if abs(score)<1e-11:
            break
    else:
        raise ValueError('Fluctuación sin convergencia')
    m1s=expit(np.log(m1/(1-m1))+epsilon/e)
    m0s=expit(np.log(m0/(1-m0))-epsilon/(1-e))
    estimate=(upper-lower)*np.mean(m1s-m0s)
    score=(upper-lower)*(m1s-m0s+h*(z-(t*m1s+(1-t)*m0s)))-estimate
    assert abs(score.mean())<1e-9
    return estimate,np.std(score,ddof=1)/np.sqrt(len(y)),epsilon

# Resultado continuo entre 0 y 10 por construcción, con medias condicionales
# 10*mu_t(X). El targeting usa la pérdida logística como cuasi-verosimilitud.
rng_cont=np.random.default_rng(151505)
n_cont=800
x_cont=rng_cont.choice(3,n_cont,p=p_x)
t_cont=rng_cont.binomial(1,e_true[x_cont])
m_cont=np.where(t_cont==1,mu1_true[x_cont],mu0_true[x_cont])
y_cont=10*rng_cont.beta(12*m_cont,12*(1-m_cont))
count_cont=np.array([[np.sum(x_cont==x) for x in (0,1,2)]],float)
treated_cont=np.array([[np.sum((x_cont==x)&(t_cont==1)) for x in (0,1,2)]],float)
e_cont=logistic_fit(count_cont,treated_cont,True)[0,x_cont]
q0_cont=np.full(n_cont,y_cont[t_cont==0].mean())
q1_cont=np.full(n_cont,y_cont[t_cont==1].mean())
estimate_cont,se_cont,eps_cont=tmle_bounded(y_cont,t_cont,q0_cont,q1_cont,e_cont,0,10)
assert -10<=estimate_cont<=10
print('Continuo acotado: ATE verdadero',round(10*truth,3),
      'TMLE',round(estimate_cont,4),'EE EIF',round(se_cont,4),
      'epsilon',round(eps_cont,6))
print('Cotas conocidas [0,10]; EE EIF sujeto a condiciones asintóticas y ajuste de nuisances.')

# La misma rutina para Bernoulli: coteja targeting y cota del parámetro.
n_binary=800
xb=rng_cont.choice(3,n_binary,p=p_x)
tb=rng_cont.binomial(1,e_true[xb])
yb=rng_cont.binomial(1,np.where(tb==1,mu1_true[xb],mu0_true[xb]))
cb=np.array([[np.sum(xb==x) for x in (0,1,2)]],float)
tb_count=np.array([[np.sum((xb==x)&(tb==1)) for x in (0,1,2)]],float)
eb=logistic_fit(cb,tb_count,True)[0,xb]
q0b=np.full(n_binary,yb[tb==0].mean())
q1b=np.full(n_binary,yb[tb==1].mean())
result_binary=tmle_bounded(yb,tb,q0b,q1b,eb,0,1)
assert -1<=result_binary[0]<=1
print('Binario: ATE verdadero',round(truth,4),'TMLE',round(result_binary[0],4),
      'EE EIF',round(result_binary[1],4),'epsilon',round(result_binary[2],6))

Lab: derivatives by contamination

[ ]gateaux cellBrowser
import numpy as np

# P(X=x, T=t, Y=y) construido desde factores explícitos.
# Todas las probabilidades son positivas: la EIF está bien definida.
px = np.array([0.4, 0.6])
e = np.array([0.25, 0.75])
mu0 = np.array([0.2, 0.4])
mu1 = np.array([0.5, 0.8])
p = np.empty((2, 2, 2))
for x in range(2):
    for t in range(2):
        py1 = mu1[x] if t else mu0[x]
        pt = e[x] if t else 1 - e[x]
        p[x, t, :] = px[x] * pt * np.array([1 - py1, py1])

# Contaminar con una masa puntual en (X,T,Y)=(1,1,1).
q = np.zeros_like(p)
q[1, 1, 1] = 1.0
score = (q - p) / p
y = np.arange(2)[None, None, :]
t = np.arange(2)[None, :, None]

def parametros(distribucion):
    px_local = distribucion.sum(axis=(1, 2))
    pt_local = distribucion.sum(axis=2)
    mu_local = distribucion[:, :, 1] / pt_local
    media = float(np.sum(distribucion * y))
    varianza = float(np.sum(distribucion * (y - media)**2))
    ate = float(np.sum(px_local * (mu_local[:, 1] - mu_local[:, 0])))
    return np.array([media, varianza, ate])

theta = parametros(p)
phi_media = y - theta[0]
phi_varianza = (y - theta[0])**2 - theta[1]
phi_ate = (mu1 - mu0)[:, None, None] - theta[2] + (
    t * (y - mu1[:, None, None]) / e[:, None, None]
    - (1 - t) * (y - mu0[:, None, None]) / (1 - e)[:, None, None]
)
phis = (phi_media, phi_varianza, phi_ate)
derivadas = np.array([np.sum(p * score * phi) for phi in phis])

print('Suma de P y mínimo P:', p.sum(), p.min())
print('Media del score:', np.sum(p * score))
print('Parámetros media, varianza, ATE:', np.round(theta, 8))
print('Medias de las funciones de influencia:',
      np.round([np.sum(p * phi) for phi in phis], 12))
print('Derivadas analíticas:', np.round(derivadas, 8))
print('h | derivadas hacia delante | error máximo')
for h in (0.1, 0.01, 0.001, 0.0001):
    derivada_numerica = (parametros((1 - h) * p + h * q) - theta) / h
    error = np.max(np.abs(derivada_numerica - derivadas))
    print(f'{h:g} | {np.round(derivada_numerica, 8)} | {error:.8g}')

assert np.all(p > 0) and np.isclose(p.sum(), 1)
assert np.allclose([np.sum(p * phi) for phi in phis], 0)
assert np.max(np.abs(derivada_numerica - derivadas)) < 1e-4

Comparison with libraries

This cell runs in local Python, not Pyodide. Install doubleml==0.11.4, zepid==0.9.1 and pandas==2.3.3 with dependencies in your environment. The pandas version matters: zEpid 0.9.1 can fail with pandas 3 when modifying a read-only array. The experiment is small and requires no GPU.

DoubleML uses cross-fitting and zEpid fits on the same sample, so their numbers need not agree. Each method is compared here with a manual reconstruction of its own predictions and conventions: zEpid uses two fluctuations and the previous lab one.

[ ]Comparison with DoubleML and zEpidLocal GPU
# Requiere: doubleml, zepid, numpy, pandas, scipy, scikit-learn y statsmodels.
# Comparación local reproducible; no descarga datos ni necesita GPU.
import importlib.metadata as metadata
import numpy as np
import pandas as pd
from scipy.optimize import root
from scipy.special import expit, logit
from sklearn.linear_model import LogisticRegression
from doubleml import DoubleMLData, DoubleMLIRM
from zepid.causal.doublyrobust import TMLE

for package in ['doubleml', 'zepid', 'numpy', 'pandas', 'scikit-learn', 'statsmodels']:
    print(package, metadata.version(package))

# El mismo SCM explícito del ejemplo: ATE poblacional = 0,41.
rng = np.random.default_rng(2026)
n = 1600
x = rng.binomial(1, .4, size=n)
e_true = np.where(x, .75, .25)
a = rng.binomial(1, e_true)
mu0 = np.where(x, .5, .1)
mu1 = np.where(x, .85, .55)
y = rng.binomial(1, np.where(a, mu1, mu0))
df = pd.DataFrame({'X': x, 'A': a, 'Y': y})
print('ATE del SCM:', .41)

# DoubleML ajusta tres modelos por pliegues; se reconstruye el mismo score
# a partir de SUS predicciones fuera del pliegue. El recorte por defecto es
# inactivo aquí, porque todos los scores quedan dentro de [0,01; 0,99].
np.random.seed(2026)
learner = LogisticRegression(C=1e6, max_iter=1000)
data = DoubleMLData(df, y_col='Y', d_cols='A', x_cols=['X'])
model = DoubleMLIRM(data, ml_g=learner, ml_m=learner,
                    n_folds=2, score='ATE', normalize_ipw=False)
model.fit(store_predictions=True)
q0 = model.predictions['ml_g0'][:, 0, 0]
q1 = model.predictions['ml_g1'][:, 0, 0]
ep = model.predictions['ml_m'][:, 0, 0]
assert np.all((ep > .01) & (ep < .99))
score = q1-q0+a*(y-q1)/ep-(1-a)*(y-q0)/(1-ep)
aipw = score.mean()
np.testing.assert_allclose(aipw, model.coef[0], atol=1e-10)
print('AIPW manual con las predicciones cross-fit:', round(aipw, 6))
print('DoubleML IRM ATE:', round(model.coef[0], 6),
      'error estándar:', round(model.se[0], 6))

# zEpid ajusta propensity X y outcome A+X en la misma muestra. Usa dos
# fluctuaciones: H1=A/e y H0=-(1-A)/(1-e), una por brazo. Reproducimos
# la ecuación de score con SUS predicciones iniciales, no la variante
# de una sola fluctuación del laboratorio anterior.
target = TMLE(df, exposure='A', outcome='Y')
target.exposure_model('X', print_results=False)
target.outcome_model('A + X', print_results=False)
target.fit()
g = np.asarray(target.g1W)
q0z = np.asarray(target.QA0W)
q1z = np.asarray(target.QA1W)
qobs = np.asarray(target.QAW)
H = np.column_stack([a/g, -(1-a)/(1-g)])
solution = root(lambda eps: H.T @ (y-expit(logit(qobs)+H@eps)), [0., 0.], tol=1e-10)
assert solution.success or np.max(np.abs(solution.fun)) < 1e-8
eps = solution.x
tmle = np.mean(expit(logit(q1z)+eps[0]/g)-expit(logit(q0z)-eps[1]/(1-g)))
np.testing.assert_allclose(tmle, target.risk_difference, atol=1e-8)
print('TMLE manual con dos fluctuaciones:', round(tmle, 6),
      'epsilon:', np.round(eps, 6))
print('zEpid TMLE diferencia de riesgos:', round(target.risk_difference, 6),
      'error estándar:', round(target.risk_difference_se, 6))
print('DoubleML usa cross-fitting y zEpid ajuste en muestra; sus cifras no tienen por qué coincidir.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofTwo chances to be right
Prove: Assume ignorability, consistency, and positivity. Let e,μ0,μ1e,\mu_0,\mu_1 be the true functions and e~,μ~0,μ~1\widetilde e,\widetilde\mu_0,\widetilde\mu_1 be fixed functions with 0<e~<10<\widetilde e<1. Also assume all weighted contributions are integrable. Prove both branches of AIPW double robustness.
The proof will appear here as you work.

Step 1 of 4. What is the conditional expectation of the weighted treated-arm residual?

ProofInfluence of the treated mean
Prove: In the observed nonparametric model, with uniform positivity and E[Y2]<∞E[Y^2]<\infty, derive the influence of θ1=E[μ1(X)]\theta_1=E[\mu_1(X)] for a regular submodel with score decomposed as sX+sT+sYs_X+s_T+s_Y.
The proof will appear here as you work.

Step 1 of 4. What does varying the marginal distribution of X contribute?

NumericSix AIPW contributions
For six units, y=(1,1,2,3,0,2), t=(1,0,1,0,0,1), mu0=(0,1,1,2,1,0), mu1=(1,2,2,3,2,1), and e=0.5 for all. Calculate the AIPW estimate to three decimals.
CodeEstimation and EIF standard error
Implement aipw(y, t, mu0, mu1, e). Each input is a numeric vector of equal length n >= 2. y contains observed outcomes, t binary treatments, mu0 and mu1 outcome predictions for both treatments, and e the corresponding propensity. All inputs must be finite and propensities strictly within (0, 1); reject invalid data with ValueError without trimming. Return (estimate, standard_error), where the estimate is the mean AIPW contribution and the standard error is sqrt(var(contributions, ddof=1)/n). This calculation does not prove inference is valid: interpreting standard error as causal inference requires, among other conditions, identification, positivity, appropriate sampling, and nuisance-model regularity conditions.
def aipw(y, t, mu0, mu1, e):
  # Valida los datos, calcula la contribución de cada observación
  # y devuelve la media y su error estándar empírico.
  raise NotImplementedError
Shift+Enter to run
QuizPropensity near zero
The propensity is correct but equals 0.001 for some units. What conclusion is justified?
QuizTwo incorrect models
If outcome and assignment models converge to incorrect limits, what does double robustness guarantee?
QuizThe rate boundary
Each nuisance error is O_p(n^(-1/4)). What follows without further assumptions?

To check the numeric exercise calculations after attempting it:

[ ]Check six contributionsBrowser
import numpy as np

y = np.array([1,1,2,3,0,2])
t = np.array([1,0,1,0,0,1])
mu0 = np.array([0,1,1,2,1,0])
mu1 = np.array([1,2,2,3,2,1])
e = np.full(6, 0.5)
contribuciones = mu1-mu0 + t*(y-mu1)/e - (1-t)*(y-mu0)/(1-e)
print('Contribuciones:', contribuciones)
print('AIPW y error estándar:', np.mean(contribuciones),
      np.std(contribuciones, ddof=1)/np.sqrt(len(y)))