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
- 27Inverse probability weightingStandardization and g-computationPropensity scoreConditional ignorability and overlapOverlap, trimming and overlap weights
- 05M-estimators and Z-estimatorsSandwich variance estimatorRegression diagnostics: residuals, leverage and influenceCramér-Rao lower boundFisher information
- 03Directional derivativeFréchet derivativeTaylor polynomial
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.
AIPW: prediction plus weighted residuals
Let with , and . With pretreatment covariates and the earlier causal assumptions, ATE is . The augmented inverse probability weighting or AIPW estimator replaces unknown functions with models and adds residuals:
Here 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 with positive denominators and integrable contributions. Conditioning on and subtracting , the expectation of the uncentered expression is
Check arm by arm: , and the control term is analogous with a negative sign. The expression vanishes if 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 is bounded away from zero and one, Cauchy–Schwarz bounds absolute bias by a constant times
Therefore the expression is orthogonal to small first-order errors in either piece when the other is true. For an interval centered at scale , the product is usually required to be , alongside other inference conditions. Two errors of order only ensure product : it may remain as large as the standard error. Two errors 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.
The surface uses a fully specified population model and calculates exact bias, not fabricated experimental results. Change both rates and observe bias multiplied by . 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 assigns a parameter to a distribution. Let be a regular submodel with and score of mean zero and finite second moment. An efficient influence function represents the derivative via
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 , differentiating the integral gives , hence if . For variance the influence is if, for example, . These conditions ensure representatives belong to . The lab checks derivatives by contaminating finite distributions, but numerical checking does not replace proof for all regular submodels.
In that figure, for and plug-in , the functional is . The mean under of influence evaluated at is ; adding it to leaves exact error . 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 , factor the density as and decompose the score into , each component conditionally centered. Differentiating the distribution of gives . Differentiating the conditional mean of in the treated arm gives
The factor cancels the probability of observing the treated arm. The functional does not directly depend on the assignment mechanism; its product with has expectation zero. Thus,
The same reasoning for arm zero followed by subtraction gives
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 ; strict positivity alone does not guarantee the weighted variance exists. If indicates observation of a missing-at-random outcome, is also the influence for its population mean, with 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 . Therefore
The semiparametric efficiency bound of Hahn is this variance for , or that quantity divided by 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 removes assignment tangent directions, but the previous influence is already orthogonal to them: conditional on its residuals have zero mean and the remaining term depends only on . Thus knowing 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 with the average of . For ATE this gives exactly the AIPW expression above. Under suitable conditions, if both nuisance functions converge to truth, their product error is , necessary moments are finite, and the empirical process is controlled, we obtain
With i.i.d. observations and positive variance, estimate standard error using the sample standard deviation of centered AIPW contributions divided by , 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 in and estimated propensity in , define the clever covariate
Fit 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 . Then predict both outcomes for each using and ; 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 and resulting ATE in ; 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 , transform to , use logistic quasi-likelihood fluctuation for the mean, and rescale by . 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.
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.
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.
print('Propensión correcta, resultado correcto')
result_cc = mc_scenario(True,True,151501)print('Propensión correcta, resultado incorrecto')
result_ci = mc_scenario(True,False,151502)print('Propensión incorrecta, resultado correcto')
result_ic = mc_scenario(False,True,151503)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.
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
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-4Comparison 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.
# 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.')npm run lab and open the connection link.Exercises
Step 1 of 4. What is the conditional expectation of the weighted treated-arm residual?
Step 1 of 4. What does varying the marginal distribution of X contribute?
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 NotImplementedErrorTo check the numeric exercise calculations after attempting it:
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)))