Double machine learning and heterogeneous effects
Use gradient boosting in double machine learning with orthogonal moments and cross-fitting, and measure interval coverage in simulation. Estimate heterogeneous effects with S-, T-, X-, and DR-learners and causal forests on a semi-synthetic benchmark with known effects.
After this lesson you can
- Implement partially linear DML with cross-fitting and measure coverage by simulation.
- Explain why Neyman orthogonality protects against regularization bias.
- Implement meta-learners and a DR-learner and compare them with causal forests.
- Measure heterogeneous-effect error (PEHE) on a semi-synthetic benchmark.
Before you start
Learning a prediction is not enough
A flexible predictor can approximate the outcome well yet bias the treatment coefficient: regularization leaves some confounder signal in the residual. A final regression ignoring dependence between treatment and confounders can attribute that signal to treatment. Evaluating prediction error for alone is also insufficient: a model can predict levels without ranking effect differences well.
In a partially linear model, and , assume , , and positive residual variation in . The quantity is constant in this model. Define and . The double machine learning score with cross-fitting is
First divide observations into folds. For each fold fit both nuisance models outside it and predict within it; pool residuals and solve for mean equal to zero. Each unit is thus used once to estimate the parameter with predictions made without it. The lab’s standard error uses empirical score variance divided by the squared derivative with respect to , and a normal approximation. Near-zero residual variation makes the denominator unstable.
Neyman orthogonality means the derivative of expected score with respect to small perturbations of or is zero at the true functions. If perturbs , the derivative is . If perturbs , it is . The first-order nuisance-error term vanishes, while higher-order terms remain. Sufficient rates depend on the product of errors and the score; requiring both functions to converge faster than is a common sufficient condition, not a universal DML law. See Chernozhukov and colleagues and the DoubleML documentation.
Cross-fitting reduces bias from reusing observations to fit and evaluate flexible functions, but does not remove unmeasured confounding or ensure positivity or exact finite-sample coverage. If tuning hyperparameters, do so within each training set or with external data; choosing them using the evaluation fold contaminates the separation.
Here is uniform between -1 and 1, , , and are independent standard normals. In nonlinear mode we add to the outcome. Nuisance models average and in 12 bins; with cross-fitting enabled, each mean uses the opposite fold. Each sample has an approximate normal interval. The last 20 plotted replicates and cumulative coverage reflect the chosen settings; endpoints outside the scale are visually clipped. These are simulations, not general proofs of validity.
Measured coverage
The local lab uses another simulation: five normal covariates, , , with independent normal errors. We fix 500 samples of 600 units, seeds 201 through 700, two folds, and LightGBM with 60 trees of maximum depth three. Coverage of the nominal 95% DML interval was 90.2%, with approximate Monte Carlo error of 1.33 percentage points; mean estimate was 0.991. The nonorthogonal variant, residualizing but not , covered 0.2% with mean 0.779. Its formula is not a valid estimator of the same orthogonal equation; it illustrates the shortcut’s failure rather than attributing it to every non-DML procedure.
The observed 90.2% lies outside the range expected for this exercise. It is evidence about this configuration, not guaranteed coverage or a general refutation of asymptotic theory. The 500 indicators are simulated; their Monte Carlo uncertainty describes variation across experimental repetitions, not uncertainty in a real study. Orthogonality does not automatically fix finite-sample nuisance-model errors or a poor normal approximation.
From an average effect to conditional effects
Heterogeneous effects describe . Their observational identification requires consistency, conditional ignorability, and support in the region of interest, among other assumptions. A treatment may work better for some groups, but exploring many splits and reporting only the largest exaggerates differences; reserve data, adjust for multiplicity, and distinguish hypotheses from confirmatory findings.
An S-learner fits one outcome model with and and compares its two predictions. A T-learner fits one model per treatment. An X-learner imputes differences in each group, fits models of those differences, and combines predictions using a propensity function; it can help with highly unequal groups but does not always win. A DR-learner constructs an AIPW-corrected pseudo-outcome and fits a conditional-difference model; extreme weights can destabilize it. A causal forest seeks partitions for effect differences and uses honesty and inference mechanisms requiring specific conditions. Wager and Athey explain its guarantees; Kennedy studies doubly robust heterogeneous-effect estimation.
A benchmark with constructed truth
IHDP combines covariates from a child study with simulated potential outcomes: it is a semi-synthetic benchmark. The 100-replicate files distributed for CFRNet contain 672 training and 75 test observations per replicate, with potential means and . True effect is the difference between those simulated means, not an observed individual effect of a real policy. Root PEHE is on test.
On the first 20 replicates, with 80-tree forests and seed 201, the lab obtained the following means and standard deviations across replicates. Models are fitted only on train; 75 effects per replicate are measured on test. For DR, nuisance predictions use two folds and propensity is numerically clipped to [0.02, 0.98]; that choice may introduce bias and should be studied. Scale variation is large, and these 20 replicates are not directly comparable with published tables using 100 or 1,000 replicates.
| Method | Mean root PEHE | Standard deviation across replicates |
|---|---|---|
| S | 3.778 | 7.792 |
| T | 3.085 | 6.102 |
| X | 3.755 | 7.314 |
| DR | 3.288 | 5.942 |
| Causal forest | 3.826 | 7.410 |
Variability is dominated by some high-scale replicates; inspect individual values rather than declaring a universal winner from a mean. These models and seeds form an educational configuration without hyperparameter search. For the files and their 100 replicates, use the source linked by the CFRNet repository; its covariates are reused across simulated scenarios, so these are not 20 independent studies of a real intervention.
Laboratory
Use Python 3.12 with NumPy 2.2.6, SciPy 1.15.3, scikit-learn 1.6.1, LightGBM 4.6.0, DoubleML 0.10.1, and EconML 0.16.0. For example: python -m pip install "numpy==2.2.6" "scipy==1.15.3" "scikit-learn==1.6.1" "lightgbm==4.6.0" "doubleml==0.10.1" "econml==0.16.0". The first cell runs one sample and checks the estimator against DoubleML. Downloadable scripts reproduce the 500 samples and 20 IHDP replicates; fitting can take several minutes.
Download dml.py, plr_coverage.py, ihdp.py, test_learners.py, and library_checks.py into one directory. The coverage results and IHDP results by replicate are also available with settings and versions. Run:
python library_checks.py
python test_learners.py
python plr_coverage.py --out coverage_results.json --reps 500
python ihdp.py --data ihdp_data --out ihdp_results.json --reps 20
Result programs do not overwrite files; use another name if you downloaded the JSON files. The IHDP script downloads the two original NPZ files and checks their SHA-256. EconML implements the causal forest; DoubleML and LinearDML serve as comparisons in the partially linear model. In this sample the custom implementation and DoubleML agree on coefficient and standard error; LinearDML agrees on coefficient. This checks implementation in that configuration, not causal assumptions in another application.
"""Regresión parcialmente lineal por residuos fuera de pliegue."""
import numpy as np
import warnings
from sklearn.base import clone
from sklearn.model_selection import KFold
def dml_plr(y, t, X, learner, k=2, seed=201, cross_fit=True, orthogonal=True):
y,t,X=np.asarray(y,float),np.asarray(t,float),np.asarray(X,float)
if y.ndim!=1 or t.shape!=y.shape or X.ndim!=2 or len(X)!=len(y) or k<2 or k>len(y):
raise ValueError('Dimensiones o número de pliegues inválidos')
if not all(np.isfinite(a).all() for a in (y,t,X)): raise ValueError('Datos no finitos')
l=np.empty_like(y);m=np.empty_like(t)
folds=list(KFold(n_splits=k,shuffle=True,random_state=seed).split(X)) if cross_fit else [(np.arange(len(y)),np.arange(len(y)))]
for train,test in folds:
# LightGBM 4.6/sklearn 1.6 emite este aviso con matrices NumPy aunque
# el entrenamiento y la predicción conservan el mismo orden de columnas.
with warnings.catch_warnings():
warnings.filterwarnings('ignore',message='X does not have valid feature names.*',category=UserWarning)
l[test]=clone(learner).fit(X[train],y[train]).predict(X[test])
m[test]=clone(learner).fit(X[train],t[train]).predict(X[test]) if orthogonal else 0.
v=t-m; residual=y-l
denom=np.mean(v*v)
if denom<1e-12: raise ValueError('Tratamiento residual sin variación')
theta=float(np.mean(v*residual)/denom)
score=v*(residual-theta*v)
se=float(np.sqrt(np.mean(score**2)/len(y))/denom)
return theta,se
"""Cobertura Monte Carlo fija: 500 muestras, efecto verdadero uno."""
import argparse, json, platform
from pathlib import Path
import numpy as np
import sklearn
import lightgbm
from lightgbm import LGBMRegressor
def generate(seed,n,complexity):
rng=np.random.default_rng(seed);x=rng.normal(size=(n,5))
m=.5*x[:,0]+.3*x[:,1]
g=.6*x[:,0]-.3*x[:,1]
if complexity=='nonlinear':m=m+.3*np.sin(x[:,2]);g=g+.3*np.cos(x[:,2])
t=m+rng.normal(size=n)
y=t+g+rng.normal(size=n)
return y,t,x
def run(n=600,reps=500,complexity='linear',seed=201):
learner=LGBMRegressor(n_estimators=60,max_depth=3,num_leaves=8,learning_rate=.08,verbosity=-1,n_jobs=1,random_state=201)
outputs={'dml':[],'naive':[]}
for rep in range(reps):
y,t,x=generate(seed+rep,n,complexity)
for name,orth in [('dml',True),('naive',False)]:
theta,se=dml_plr(y,t,x,learner,k=2,seed=seed,cross_fit=True,orthogonal=orth)
outputs[name].append([theta,se,abs(theta-1)<=1.96*se])
if (rep+1)%50==0:print('muestras',rep+1,flush=True)
result={'seed':seed,'n':n,'reps':reps,'complexity':complexity,'truth':1.,
'settings':{'folds':2,'n_estimators':60,'max_depth':3,'num_leaves':8,'learning_rate':.08},
'versions':{'python':platform.python_version(),'numpy':np.__version__,'sklearn':sklearn.__version__,'lightgbm':lightgbm.__version__},'methods':{}}
for name,rows in outputs.items():
a=np.array(rows,float)
result['methods'][name]={'coverage':float(a[:,2].mean()),'mean':float(a[:,0].mean()),
'mc_se':float(np.sqrt(a[:,2].mean()*(1-a[:,2].mean())/reps)),
'intervals':[[float(v) for v in row[:2]] for row in rows]}
return result
"""Comparar PLR propio con DoubleML y EconML sobre la misma muestra."""
import warnings
import numpy as np
from lightgbm import LGBMRegressor
from sklearn.model_selection import KFold
from doubleml import DoubleMLData, DoubleMLPLR
from econml.dml import LinearDML
warnings.filterwarnings('ignore',message='X does not have valid feature names.*',category=UserWarning)
y,t,x=generate(201,600,'linear')
learner=LGBMRegressor(n_estimators=60,max_depth=3,num_leaves=8,learning_rate=.08,verbosity=-1,n_jobs=1,random_state=201)
own,se=dml_plr(y,t,x,learner,k=2,seed=201)
folds=list(KFold(n_splits=2,shuffle=True,random_state=201).split(x))
obj=DoubleMLPLR(DoubleMLData.from_arrays(x,y,t),ml_l=learner,ml_m=learner,n_folds=2)
obj.set_sample_splitting(folds);obj.fit()
print('propio',own,se,'DoubleML',obj.coef[0],obj.se[0])
assert np.allclose([own,se],[obj.coef[0],obj.se[0]],rtol=1e-9,atol=1e-9)
econ=LinearDML(model_y=learner,model_t=learner,cv=folds,random_state=201)
econ.fit(y,t,W=x)
print('EconML LinearDML efecto constante',np.asarray(econ.effect()).item(),'su ajuste final incluye intercepto')npm run lab and open the connection link.Exercises
Step 1 of 2. What appears when perturbing the outcome function along direction h(X)?
def dml_plr(y, t, X, learner, k):
pass