Covariate adjustment and double robustness versus the experiment
Use NSW program data and observational controls to compare regression, matching, IPW, and AIPW with an experimental benchmark. Diagnose covariate balance and overlap and examine how trimming changes the target population.
After this lesson you can
- Implement regression adjustment, propensity-score matching, IPW, and AIPW from scratch.
- Diagnose standardized mean differences and overlap in propensity-score distributions.
- Apply trimming and explain how it changes the estimand.
- Compare estimates with an experimental benchmark using bootstrap intervals.
Before you start
- P02Causal question and estimandDAG-based identification strategy
- 27Propensity scoreMatching estimatorsInverse probability weighting
- 11Logistic regressionClassifier calibration
- 05Nonparametric bootstrapBootstrap percentile and basic intervals
- 14Self-normalized importance samplingImportance-sampling effective sample size
- 13Importance weight variance and Rényi divergence
The same program, different groups
The previous lesson defined ATT for the 185 NSW participants in the Dehejia and Wahba subsample. Their experimental controls provide a reference based on random assignment; PSID and CPS controls come from surveys and require additional assumptions. The Dehejia and Wahba data page contains the original files. The historical comparison evaluates procedures for this intervention and these samples; it does not establish the effect of any current program.
The raw mean difference mixes the effect with initial differences. Regression linearly adjusts outcome for treatment and covariates; matching finds the control with closest propensity for each treated unit, here with replacement and no maximum distance; IPW reweights controls by and normalizes weights. None automatically removes unmeasured confounding. Similar propensity does not guarantee similarity on every covariate, especially with a misspecified model.
Covariate balance compares distributions before and after adjustment. A standardized difference divides the mean difference by a common scale; here we use the unweighted pooled standard deviation in the retained sample. The figure averages absolute values of eight differences after weighting controls. A small average can hide an individually imbalanced variable, so each distribution should also be inspected. A significance test of differences does not replace this examination: it depends on sample size.
In untrimmed PSID, standardized age difference changes from -1.009 to 0.073 and 1975 earnings difference from -1.774 to -0.021 after weighting. Individual values for all eight covariates before and after are in the downloadable JSON. These mean summaries do not guarantee balance in tails or interactions or reveal omitted variables. Matching can be examined similarly in an extension; its nearest neighbor may be distant when support is lacking.
Overlap requires comparable controls for treated units of interest. If approaches one among treated units, control weights can be enormous. Kish effective size summarizes concentration; it is not a literal count of independent observations. Trimming by propensity removes units and can change the target ATT. Probabilities are estimated, so the threshold is also a decision subject to uncertainty.
Numerical protection clips probabilities to to calculate weights without division by zero; it removes no rows. Minimum unclipped propensity in PSID was approximately and maximum 0.935. Without trimming there are 185 treated, 2,490 controls, and control ESS 42.6. At threshold 0.05, 177 treated and 241 controls remain. The figure refits the outcome model on retained controls and keeps logistic regression fitted on the full sample. The curve has no uncertainty bands and the threshold should not be chosen to move the bar toward the experiment.
Double correction
For ATE define and . Doubly robust AIPW averages the score
If both outcome models are correct, residuals have zero conditional expectation even with incorrect propensity. If propensity is correct, each residual term recovers the difference between true conditional outcome and its model; summing leaves . Both arguments also need consistency, conditional absence of confounding, positivity, and regularity. Both models cannot be arbitrarily wrong, and double robustness does not protect against omitted confounders.
To see the cancellation, write and for true functions, and and for functions used in the score. Conditioning on and treating these functions as fixed:
If , both residuals vanish; if , ratios equal one and the four estimated outcome functions cancel. Then average over the target distribution of . Statistical equality with observed outcomes becomes a causal claim only under the stated assumptions. A second-order correction or asymptotic promise does not prevent substantial finite-sample problems with extreme weights.
For this project’s ATT we use another score, with , , and :
The first term compares treated units with predicted untreated outcome; the second corrects prediction error using weighted controls. The ATT formula uses the treated distribution, while the earlier ATE score averages over the whole sample. Its double robustness requires either the control outcome model or assignment model to be correct under ATT identification assumptions. Fitting both in the same sample, as this lab does, does not provide the additional cross-fitting guarantees studied later.
What the historical samples show
The experimental benchmark is the NSW treated-minus-experimental-control mean difference: 1,794 dollars of 1978, with bootstrap percentile interval 522 to 3,134 in this run. It used 200 replicates per group and seed 201. This uncertain estimate is not exact truth or universal validation; treated units also appear in the observational sample, so formal comparisons must consider their dependence.
| Controls | Raw difference | Adjusted regression | Matching | IPW ATT | AIPW ATT | Trimmed AIPW |
|---|---|---|---|---|---|---|
| PSID | -15,205 | 752 | 2,119 | 1,757 | 2,046 | 2,479 |
| CPS | -8,498 | 699 | 2,038 | 1,173 | 1,269 | 1,605 |
Figures are rounded 1978 dollars; regression includes the same eight covariates and assumes a constant treatment coefficient. In PSID, the raw difference is outside the experimental interval and adjusted regression falls inside. This does not prove the latter correct: the experimental interval is not a test of equality between estimators and one benchmark does not certify absence of bias. Trimmed AIPW concerns retained treated units, so comparison with the full benchmark is descriptive. Original data and Dehejia and Wahba’s analysis provide context; table figures are from this run, not a transcription of theirs.
In PSID, this run’s percentile intervals are 372 to 3,493 for AIPW and 687 to 4,175 for trimmed AIPW. Each replicate separately resamples treated and control units and refits logistic and outcome models; no replicates failed. Two hundred replicates provide limited endpoint precision. The ordinary matching bootstrap interval has no general validity guarantee because of nonsmoothness: Abadie and Imbens analyze that failure. For matching inference, use a procedure justified for the chosen estimator.
PSID intervals for remaining estimators are -16,373 to -13,920 for raw difference, -666 to 2,268 for regression, -586 to 3,054 for matching, and 48 to 3,222 for IPW; matching is descriptive only because of the limitation above. The JSON also retains CPS intervals and unrounded values. Checking whether one method’s point falls in another’s interval is not a calibrated test of their difference.
Reproducible laboratory
Install Python 3.12, NumPy 2.2.6, pandas 2.3.3, SciPy 1.15.3, scikit-learn 1.6.1, DoWhy 0.14, and EconML 0.16.0 in a local environment: python -m pip install "numpy==2.2.6" "pandas==2.3.3" "scipy==1.15.3" "scikit-learn==1.6.1" "dowhy==0.14" "econml==0.16.0". Files are downloaded from historical sources and SHA-256 verified. The plan is created before estimation in the session, but is not a public registry and historical data and results are already available. CPS analysis, regularization value, numerical protection, and exact matching rule are additional exploratory choices.
Download into one directory estimators.py, its tests, experiment.py, nsw_data.py, save_plan.py, and library_checks.py. Also keep the plan for this run and its complete results with propensities, intervals, and versions. In a terminal in that directory run:
python test_estimators.py
python save_plan.py --out plan.json
python experiment.py --project causal_project --plan plan.json --out results.json --bootstrap 200
python library_checks.py
The program overwrites neither plan nor results. The DoWhy check compares its normalized IPW ATT using the same propensity and reproduces 1,756.74 for PSID; EconML checks fit LinearDML and DRLearner to synthetic data with true effect 2, obtaining 1.969 and 1.970. DRLearner with two folds, a final linear model, and logistic propensity predicts effects whose treated mean was -8,686 for PSID and -770 for CPS. This mean is not algebraically the table’s AIPW ATT: fitting changes, it includes out-of-sample predictions, and it models heterogeneity. The divergence calls for investigating sensitivity and support; it does not justify selecting a preferred value or establish that the NSW estimand is identified.
"""Descarga verificable de NSW y PSID de la página de Dehejia y Wahba."""
from pathlib import Path
import hashlib
import urllib.request
import pandas as pd
FILES = {
'nswre74_treated.txt':'e7b742fe0ff07a0f45e129b4ff108bb9611cd83d53604732c48a8a0a3e20eda3',
'nswre74_control.txt':'a1364cea459d953dc691a667d99194b4ad335d6d550354fe23a5d2dc58d729b5',
'psid_controls.txt':'73ffcdd8feb7f965f8e1de9bfdb80a095542c7a95ce7f56b2e2b2a9716e858cc',
}
BASE = 'https://users.nber.org/~rdehejia/data/'
COLUMNS = ['treat','age','education','black','hispanic','married','nodegree','re74','re75','re78']
def fetch_data(directory):
directory = Path(directory)
directory.mkdir(parents=True, exist_ok=True)
for name, expected in FILES.items():
path = directory / name
if not path.exists():
with urllib.request.urlopen(BASE+name, timeout=60) as response:
data = response.read()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError(f'Hash inesperado: {name}')
path.write_bytes(data)
if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
raise ValueError(f'Archivo local modificado: {name}')
return directory
def load_data(directory):
directory = fetch_data(directory)
treated, controls, psid = [pd.read_csv(directory / n, sep=r'\s+', header=None, names=COLUMNS)
for n in ('nswre74_treated.txt','nswre74_control.txt','psid_controls.txt')]
if (len(treated),len(controls),len(psid)) != (185,260,2490):
raise ValueError('El número de filas no coincide con la documentación')
if not (treated.treat.eq(1).all() and controls.treat.eq(0).all() and psid.treat.eq(0).all()):
raise ValueError('Indicadores de tratamiento inesperados')
return pd.concat([treated,controls], ignore_index=True), pd.concat([treated,psid], ignore_index=True)
"""Escribir un plan fechado antes de estimar; no demostrar registro externo."""
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
def write_plan(path):
plan = {
'created_at_utc': datetime.now(timezone.utc).isoformat(),
'scope': 'Ejemplo educativo; no constituye un registro público ni afirma prioridad histórica.',
'question': 'Efecto del programa NSW en ingresos reales de 1978 para participantes de la submuestra Dehejia-Wahba.',
'estimand': 'ATT de la participación en NSW para los tratados de la submuestra, en dólares de 1978.',
'data': 'NSW tratados y controles experimentales, y PSID controles; archivos publicados por Dehejia y Wahba.',
'main': 'AIPW para ATT con propensity logístico y resultado lineal en controles; benchmark diferencia experimental en ingresos de 1978.',
'covariates': ['age','education','black','hispanic','married','nodegree','re74','re75'],
'diagnostics': ['balance y solapamiento','comparación con benchmark experimental','sensibilidad a confusión no medida'],
'inference': 'Bootstrap de 200 réplicas por grupo con semilla 201; reportar intervalos percentiles y réplicas fallidas.',
'overlap': 'Estimación principal sin recorte; sensibilidad con propensity entre 0.05 y 0.95, declarando cambio de población.',
'assumptions': ['consistencia','positividad para tratados','ausencia de confusión no medida en comparación observacional','comparabilidad de medición'],
'changes': 'Cualquier desviación posterior se registra con fecha y motivo, como exploratoria si procede.',
}
content = (json.dumps(plan, ensure_ascii=False, indent=2)+'\n').encode('utf8')
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('xb') as file:
file.write(content)
return hashlib.sha256(content).hexdigest()
"""Estimadores ATT para NSW: modelos explícitos, sin garantía de identificación."""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
COVARIATES = ['age','education','black','hispanic','married','nodegree','re74','re75']
METHODS = ('naive','regression','matching','ipw','aipw','aipw_trim')
def fit_nuisance(frame):
t = frame.treat.to_numpy(int)
y = frame.re78.to_numpy(float)
x = frame[COVARIATES].to_numpy(float)
if set(np.unique(t)) != {0,1}: raise ValueError('Se necesitan tratados y controles')
scaler = StandardScaler().fit(x)
xs = scaler.transform(x)
raw = LogisticRegression(C=1e6, max_iter=1000).fit(xs,t).predict_proba(xs)[:,1]
# Protección numérica, no recorte de observaciones; reportar extremos sin protección.
propensity = np.clip(raw, 1e-6, 1-1e-6)
return t,y,xs,propensity,raw
def att_scores(frame, trim=(.05,.95)):
t,y,x,e,raw = fit_nuisance(frame)
treated,control = t==1,t==0
x1 = np.column_stack([np.ones(len(t)),t,x])
regression = np.linalg.lstsq(x1,y,rcond=None)[0][1]
order = np.argsort(e[control],kind='stable')
sorted_e = e[control][order]
sorted_y = y[control][order]
positions = np.searchsorted(sorted_e,e[treated])
left = np.clip(positions-1,0,len(sorted_e)-1)
right = np.clip(positions,0,len(sorted_e)-1)
match = np.where(abs(sorted_e[left]-e[treated])<=abs(sorted_e[right]-e[treated]),left,right)
matching = np.mean(y[treated]-sorted_y[match])
odds = e[control]/(1-e[control])
ipw = y[treated].mean()-np.average(y[control],weights=odds)
design = np.column_stack([np.ones(len(t)),x])
beta = np.linalg.lstsq(design[control],y[control],rcond=None)[0]
mu0 = design@beta
aipw = (np.sum(y[treated]-mu0[treated])-np.sum(odds*(y[control]-mu0[control])))/treated.sum()
retained = (e>=trim[0]) & (e<=trim[1])
tr,co = treated & retained,control & retained
if tr.sum()==0 or co.sum()<=design.shape[1]: raise ValueError('Sin soporte suficiente tras recortar')
beta_trim = np.linalg.lstsq(design[co],y[co],rcond=None)[0]
mu_trim = design@beta_trim
odds_trim=e[co]/(1-e[co])
aipw_trim=(np.sum(y[tr]-mu_trim[tr])-np.sum(odds_trim*(y[co]-mu_trim[co])))/tr.sum()
ess=(odds.sum()**2)/np.sum(odds**2)
return dict(naive=y[treated].mean()-y[control].mean(), regression=regression,
matching=matching, ipw=ipw, aipw=aipw, aipw_trim=aipw_trim), dict(
min_e=float(raw.min()),max_e=float(raw.max()),ess_control=float(ess),
treated_retained=int(tr.sum()),control_retained=int(co.sum()))
def aipw_ate(y,t,mu0,mu1,e):
y,t,mu0,mu1,e = [np.asarray(v,float) for v in (y,t,mu0,mu1,e)]
if not (y.shape == t.shape == mu0.shape == mu1.shape == e.shape) or y.ndim != 1 or len(y)<2:
raise ValueError('Se requieren vectores de igual longitud y al menos dos unidades')
if not all(np.isfinite(x).all() for x in (y,t,mu0,mu1,e)) or not np.isin(t,[0,1]).all() or np.any((e<=0)|(e>=1)):
raise ValueError('Datos no finitos, tratamiento no binario o falta de positividad')
pseudo=mu1-mu0+t*(y-mu1)/e-(1-t)*(y-mu0)/(1-e)
estimate=float(pseudo.mean())
se=float(pseudo.std(ddof=1)/np.sqrt(len(y)))
return estimate,se
def kish(weights):
w=np.asarray(weights,float)
if w.ndim!=1 or not len(w) or not np.isfinite(w).all() or np.any(w<0) or not w.sum():
raise ValueError('Pesos finitos no negativos y suma positiva requeridos')
return float(w.sum()**2/np.sum(w**2))
"""Reproducir comparación NSW/PSID/CPS, reestimando modelos en cada bootstrap."""
import argparse
import hashlib
import json
import platform
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
import sklearn
from threadpoolctl import threadpool_limits
CPS_URL='https://users.nber.org/~rdehejia/data/cps_controls.txt'
CPS_HASH='dce640066f8bcdf447864b158b2cb0390bd3f8d6cbe3a27576a06926477d51f8'
def load_cps(data_dir, treated):
path=Path(data_dir)/'cps_controls.txt'
if not path.exists():
with urllib.request.urlopen(CPS_URL,timeout=60) as response: content=response.read()
if hashlib.sha256(content).hexdigest()!=CPS_HASH: raise ValueError('Hash CPS inesperado')
path.write_bytes(content)
if hashlib.sha256(path.read_bytes()).hexdigest()!=CPS_HASH: raise ValueError('CPS local modificado')
controls=pd.read_csv(path,sep=r'\s+',header=None,names=COLUMNS)
if len(controls)!=15992 or not controls.treat.eq(0).all(): raise ValueError('CPS inesperado')
return pd.concat([treated,controls],ignore_index=True)
def bootstrap(frame, reps, seed):
rng=np.random.default_rng(seed)
treated=np.flatnonzero(frame.treat.to_numpy()==1)
controls=np.flatnonzero(frame.treat.to_numpy()==0)
results={key:[] for key in METHODS}; failures=0
for _ in range(reps):
indices=np.r_[rng.choice(treated,len(treated),replace=True),rng.choice(controls,len(controls),replace=True)]
try:
values,_=att_scores(frame.iloc[indices])
for key in METHODS: results[key].append(float(values[key]))
except (ValueError,np.linalg.LinAlgError):
failures+=1
return {key:[float(x) for x in np.quantile(values,[.025,.975])] if values else None for key,values in results.items()},failures
def benchmark(frame,reps,seed):
a=frame.loc[frame.treat==1,'re78'].to_numpy();b=frame.loc[frame.treat==0,'re78'].to_numpy()
rng=np.random.default_rng(seed)
samples=[rng.choice(a,len(a),replace=True).mean()-rng.choice(b,len(b),replace=True).mean() for _ in range(reps)]
return {'estimate':float(a.mean()-b.mean()),'interval':[float(x) for x in np.quantile(samples,[.025,.975])]}
def diagnostics(frame, threshold):
t,y,x,e,raw=fit_nuisance(frame)
kept=(e>=threshold)&(e<=1-threshold);tr=(t==1)&kept;co=(t==0)&kept
if tr.sum()==0 or co.sum()==0:return None
weights=e[co]/(1-e[co]);values=frame[COVARIATES].to_numpy(float)
diffs=[]
for j in range(values.shape[1]):
a,b=values[tr,j],values[co,j]
pooled=np.sqrt((np.var(a,ddof=1)+np.var(b,ddof=1))/2)
if pooled>0:diffs.append(abs((a.mean()-np.average(b,weights=weights))/pooled))
estimate,_=att_scores(frame,trim=(threshold,1-threshold))
return dict(threshold=threshold,treated=int(tr.sum()),controls=int(co.sum()),
ess=float(kish(weights)),mean_abs_smd=float(np.mean(diffs)),aipw=float(estimate['aipw_trim']))
def balance(frame):
t,_,_,e,_=fit_nuisance(frame)
a=frame.loc[t==1,COVARIATES].to_numpy(float)
b=frame.loc[t==0,COVARIATES].to_numpy(float)
w=e[t==0]/(1-e[t==0])
scale=np.sqrt((a.var(axis=0,ddof=1)+b.var(axis=0,ddof=1))/2)
before=np.divide(a.mean(axis=0)-b.mean(axis=0),scale,out=np.zeros_like(scale),where=scale>0)
after=np.divide(a.mean(axis=0)-np.average(b,axis=0,weights=w),scale,out=np.zeros_like(scale),where=scale>0)
return {key:{'before':float(x),'weighted':float(y)} for key,x,y in zip(COVARIATES,before,after)}
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--project',default='causal_project')
parser.add_argument('--plan',required=True)
parser.add_argument('--out',default='causal_results.json')
parser.add_argument('--bootstrap',type=int,default=200)
args=parser.parse_args()
if args.bootstrap<2:raise ValueError('Se requieren al menos dos réplicas')
plan=Path(args.plan).read_bytes()
if 'ATT' not in json.loads(plan)['estimand']:raise ValueError('El plan no define ATT')
project=Path(args.project);data_dir=project/'data'
with threadpool_limits(limits=1):
exp,psid=load_data(data_dir)
treated=exp[exp.treat==1]
cps=load_cps(data_dir,treated)
result={'plan_sha256':hashlib.sha256(plan).hexdigest(),'bootstrap':args.bootstrap,'seed':201,
'versions':{'python':platform.python_version(),'numpy':np.__version__,
'pandas':pd.__version__,'scikit_learn':sklearn.__version__},
'settings':{'propensity':'logística escalada, C=1e6','numerical_clip':[1e-6,1-1e-6],
'trim':[.05,.95],'covariates':COVARIATES},
'benchmark':benchmark(exp,args.bootstrap,201),'datasets':{}}
for name,frame in [('PSID',psid),('CPS',cps)]:
values,detail=att_scores(frame)
intervals,failures=bootstrap(frame,args.bootstrap,201)
result['datasets'][name]={'n':len(frame),'estimates':{k:float(v) for k,v in values.items()},
'diagnostics':detail,'balance':balance(frame),'intervals':intervals,'failed_replicates':failures}
print(name,result['datasets'][name],flush=True)
t,y,x,e,raw=fit_nuisance(psid)
result['psid_propensity']={'treated':e[t==1].tolist(),'controls':e[t==0].tolist()}
result['trim_curve']=[diagnostics(psid,threshold) for threshold in (0.,.05,.1,.15,.2)]
target=Path(args.out)
with target.open('x',encoding='utf8') as file:json.dump(result,file,indent=2)
print('Benchmark:',result['benchmark'],'guardado:',target,flush=True)
import sys
from datetime import datetime, timezone
stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
project=Path('causal_project')
plan_file=project/('plan_'+stamp+'.json')
write_plan(plan_file)
sys.argv=['experiment','--project',str(project),'--plan',str(plan_file),
'--out',str(project/('results_'+stamp+'.json')),'--bootstrap','200']
main()npm run lab and open the connection link.Exercises
def aipw(y, t, mu0, mu1, e):
passProve the two routes to double robustness for the ATE by conditioning on , and explain why neither proves that the eight covariates close all confounding paths. The exercise’s standard error treats models as fixed and needs additional conditions for inference when they are estimated; the laboratory also resamples the models.