Module contents
Stage 3 of 9Advanced 110 min

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 YY alone is also insufficient: a model can predict levels without ranking effect differences well.

In a partially linear model, Y=θ0T+g0(X)+ϵY=\theta_0T+g_0(X)+\epsilon and T=m0(X)+VT=m_0(X)+V, assume E[ϵ∣T,X]=0E[\epsilon\mid T,X]=0, E[V∣X]=0E[V\mid X]=0, and positive residual variation in TT. The quantity θ0\theta_0 is constant in this model. Define ℓ0(X)=E[Y∣X]\ell_0(X)=E[Y\mid X] and m0(X)=E[T∣X]m_0(X)=E[T\mid X]. The double machine learning score with cross-fitting is

ψ(W;θ,ℓ,m)=(T−m(X)){Y−ℓ(X)−θ[T−m(X)]}.\psi(W;\theta,\ell,m)=(T-m(X))\{Y-\ell(X)-\theta[T-m(X)]\}.

First divide observations into KK folds. For each fold fit both nuisance models outside it and predict within it; pool residuals and solve for mean ψ\psi 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 θ\theta, 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 ℓ\ell or mm is zero at the true functions. If hℓh_\ell perturbs ℓ\ell, the derivative is −E[Vhℓ(X)]=0-E[Vh_\ell(X)]=0. If hmh_m perturbs mm, it is E[hm(X)(θ0V−ϵ)]=0E[h_m(X)(\theta_0V-\epsilon)]=0. 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 n−1/4n^{-1/4} 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.

InteractiveCumulative intervals with and without residualization
0.10.511.51.9

Blue: contains 1; orange: does not. Endpoints outside the axis are drawn at its edge. Coverage uses all cumulative intervals, not only the 20 visible.

40
Observed coverage85.0 %
Intervals40
True effect1
Deterministic browser simulation with regressions by X bins; these are not the lab's LightGBM results.

Here XX is uniform between -1 and 1, T=0.7X+VT=0.7X+V, Y=T+X+ϵY=T+X+\epsilon, and V,ϵV,\epsilon are independent standard normals. In nonlinear mode we add 0.7sin⁡(5X)0.7\sin(5X) to the outcome. Nuisance models average YY and TT in 12 XX 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, T=0.5X0+0.3X1+VT=0.5X_0+0.3X_1+V, Y=T+0.6X0−0.3X1+ϵY=T+0.6X_0-0.3X_1+\epsilon, 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 YY but not TT, 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 τ(x)=E[Y(1)−Y(0)∣X=x]\tau(x)=E[Y(1)-Y(0)\mid X=x]. 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 TT and XX 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 μ0\mu_0 and μ1\mu_1. True effect is the difference between those simulated means, not an observed individual effect of a real policy. Root PEHE is n−1∑i[τ^(Xi)−τ(Xi)]2\sqrt{n^{-1}\sum_i[\hat\tau(X_i)-\tau(X_i)]^2} 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.

MethodMean root PEHEStandard deviation across replicates
S3.7787.792
T3.0856.102
X3.7557.314
DR3.2885.942
Causal forest3.8267.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.

[ ]DML and comparison with librariesLocal GPU
"""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')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Quiz
The treated group is ten times smaller than the control group. Which method is worth trying because of how it combines effect imputations across groups?
Numeric
All ten true effects are 1; five predictions are 2 and five are 1. What is root PEHE?
ProofDerive the orthogonal moment
Prove: The directional derivative of expected PLR score is zero at the true functions.
0
Write V = T − m₀(X) and ε = Y − θ₀T − g₀(X).

Step 1 of 2. What appears when perturbing the outcome function along direction h(X)?

Code
Implement dml_plr(y, t, X, learner, k). Use k deterministic folds by index modulo k, an independent learner clone for each variable and fold, and return estimate and robust score standard error. Inputs are NumPy arrays, k between 2 and n, and a learner with fit and predict.
def dml_plr(y, t, X, learner, k):
  pass
Shift+Enter to run

Summary

Key idea
Orthogonal residualization and cross-fitting reduce specific routes of bias under assumptions and rate conditions. Evaluating heterogeneity needs known truth or an appropriate validation design, and finite-sample coverage must be measured.