Module contents
Lesson 16 of 28Advanced 110 min

Double machine learning and control selection with the lasso

Double machine learning combines orthogonal scores and cross-fitting to control first-order nuisance errors. Derive partially linear and ATE scores, connect Robinson to FWL, and study double selection and learner diagnostics.

After this lesson you can

  • Explain first-order regularization bias in a naive plug-in and derive orthogonality.
  • Derive the Robinson partially linear estimator and relate it to FWL.
  • Implement cross-fitted DML for partially linear models and ATE with an AIPW score.
  • Implement double lasso selection and simulate the limitations of single selection.
  • Diagnose DML sensitivity to learners, folds, and seeds.

Before you start

Many controls, one question

You want to estimate the effect of training on wages and have hundreds of prior features. Including them all in a regression may be unstable; selecting only wage predictors can discard a confounder that strongly predicts training and weakly predicts wages. A forest predicts complex relationships, but regularization and fitting on the same data also affect inference.

Double machine learning combines a score insensitive to small nuisance-model errors with out-of-sample predictions through cross-fitting. “Double” does not authorize post-treatment variables or correct unmeasured confounding. Chernozhukov and colleagues establish precise normality conditions and study them in simulation.

InteractiveThree estimators in a simulation

Each bar counts estimates standardized by their own standard error. The curve is the standard normal on the same frequency scale; the vertical line marks zero. Values outside the axis accumulate at its endpoints.

-12-8-404z = (estimated θ − true θ) / SE
  • Simulated replicates
  • Standard normal
  • Zero

Original simulation: 120 i.i.d. samples of n=300 and NumPy seed 16261. X has five independent standard normals; T=sin(X₀)+0.3X₁+V and Y=0.5T+1.5sin(X₀)+0.4X₁²+ε, with independent normal V and ε. The truth is θ=0.5. Forests with 32 trees, minimum leaf size 4 and max_features=0.8 fit E[Y|X] and E[T|X]; a different forest seed is used per replicate.

The first method residualizes Y but not T and divides by the mean of T²; even with a perfect Y model its limit is generally biased. The second uses the orthogonal score with both forests fitted on the same data. The third uses two permuted folds and out-of-fold predictions. Standard errors treat the respective scores as fixed; for methods without cross-fitting their validity is not guaranteed. Coverage counts |z|≤1.96; with 120 replicates it has Monte Carlo uncertainty and does not establish universal coverage. This simulation does not numerically reproduce the paper’s figure.

Mean z−7.622
Standard deviation of z1.272
Observed coverage0.0 %
Replicates120
Compare the standardized distribution of each procedure with the reference normal.

The figure was produced by running this simulation in local Python with NumPy and scikit-learn. The cell also prints all standardized values used for the bars so you can regenerate them; no external files are needed. Standard errors of methods evaluated on training data do not have guaranteed inferential validity.

[ ]Regenerate forest replicatesLocal GPU
"""Genera datos reproducibles para la figura PLR con bosques reales."""
import json
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold
from sklearn.base import clone

seed = 16261
rng = np.random.default_rng(seed)
n, replications = 300, 120
theta = .5
results = {name: [] for name in ("ingenuo", "ortogonal", "dml")}

def score_result(y, t, ell, m, naive=False):
    residual_y = y-ell
    residual_t = t if naive else t-m
    den = np.mean(residual_t*t) if naive else np.mean(residual_t**2)
    if den <= 0:
        raise ValueError("Denominador no positivo")
    estimate = np.mean(residual_t*residual_y)/den
    influence = residual_t*(residual_y-estimate*(t if naive else residual_t))/den
    se = np.std(influence, ddof=1)/np.sqrt(len(t))
    return estimate, se, (estimate-theta)/se

for rep in range(replications):
    x = rng.normal(size=(n, 5))
    m_true = np.sin(x[:,0])+.3*x[:,1]
    t = m_true + rng.normal(size=n)
    g_true = 1.5*np.sin(x[:,0])+.4*x[:,1]**2
    y = theta*t+g_true+rng.normal(size=n)
    base = RandomForestRegressor(n_estimators=32, min_samples_leaf=4,
                                 max_features=.8, n_jobs=1, random_state=seed+rep)
    ell_in = clone(base).fit(x,y).predict(x)
    m_in = clone(base).fit(x,t).predict(x)
    results["ingenuo"].append(score_result(y,t,ell_in,m_in,True))
    results["ortogonal"].append(score_result(y,t,ell_in,m_in))
    ell_oof, m_oof = np.empty(n),np.empty(n)
    for train,test in KFold(2,shuffle=True,random_state=seed+rep).split(x):
        ell_oof[test] = clone(base).fit(x[train],y[train]).predict(x[test])
        m_oof[test] = clone(base).fit(x[train],t[train]).predict(x[test])
    results["dml"].append(score_result(y,t,ell_oof,m_oof))

out={"seed":seed,"n":n,"replicas":replications,"theta":theta,"resultados":results}
print("Valores z de las figuras:", json.dumps({k: [round(v[2], 7) for v in values] for k, values in results.items()}))
for name,values in results.items():
    a=np.asarray(values)
    print(name,"media theta",round(a[:,0].mean(),4),"media z",round(a[:,2].mean(),4),
          "desv z",round(a[:,2].std(ddof=1),4),"cobertura",round(np.mean(abs(a[:,2])<=1.96),4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Partialling out without assuming linearity in controls

Consider the partially linear model

Y=θ0T+g0(X)+ε,E[ε∣T,X]=0,T=m0(X)+V,E[V∣X]=0.Y=\theta_0T+g_0(X)+\varepsilon,\quad E[\varepsilon\mid T,X]=0, \qquad T=m_0(X)+V,\quad E[V\mid X]=0.

Here θ0\theta_0 is constant, g0g_0 is an unknown function, and residual variation E[V2]E[V^2] must be positive. Define ℓ0(X)=E[Y∣X]=θ0m0(X)+g0(X)\ell_0(X)=E[Y\mid X]=\theta_0m_0(X)+g_0(X). Subtracting conditional expectations gives

Y−ℓ0(X)=θ0{T−m0(X)}+ε,θ0=E[(T−m0)(Y−ℓ0)]E[(T−m0)2].Y-\ell_0(X)=\theta_0\{T-m_0(X)\}+\varepsilon,\qquad \theta_0=\frac{E[(T-m_0)(Y-\ell_0)]}{E[(T-m_0)^2]}.

This is Robinson’s idea: first remove the predictable part of both sides, then compare residuals. It is a functional version of Frisch–Waugh–Lovell, which projects linearly onto a finite control space. In data, after obtaining predictions ℓ^i,m^i\widehat\ell_i,\widehat m_i, the residual cross-product ratio estimates θ0\theta_0. With out-of-fold predictions, each observation is evaluated by models that did not train on it.

In the finite linear case, let PXP_X be the orthogonal projection onto columns of the control matrix and MX=I−PXM_X=I-P_X. Normal equations for regression of YY on TT and XX give θ^=(T⊤MXT)−1T⊤MXY\widehat\theta=(T^\top M_XT)^{-1}T^\top M_XY when the denominator is nonzero. This ratio is exactly the no-intercept regression of MXYM_XY on MXTM_XT. Replacing PXP_X with nonlinear learners permits approximation of more general conditional expectations, but is no longer an algebraic least-squares identity: prediction errors and their sample dependence must be studied.

If TT is binary and effect varies with XX, the residualized slope is generally not ATE: under appropriate conditions it weights conditional effects by e(X){1−e(X)}e(X)\{1-e(X)\}. The interactive regression model with AIPW score estimates ATE under its own assumptions. Before selecting an estimator, decide the population and effect of interest.

Neyman orthogonality

A score ψ(O;θ,η)\psi(O;\theta,\eta) is Neyman orthogonal at truth if E[ψ(O;θ0,η0)]=0E[\psi(O;\theta_0,\eta_0)]=0 and the directional derivative of its expectation with respect to nuisance η\eta is zero in every admissible direction. For η=(ℓ,m)\eta=(\ell,m), the partially linear score is

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

Let δℓ=ℓ~−ℓ0\delta_\ell=\widetilde\ell-\ell_0 and δm=m~−m0\delta_m=\widetilde m-m_0. Substituting Y−ℓ0=θ0V+εY-\ell_0=\theta_0V+\varepsilon and T−m0=VT-m_0=V, using E[V∣X]=0E[V\mid X]=0 and E[ε∣T,X]=0E[\varepsilon\mid T,X]=0, gives the exact identity

E[ψ(O;θ0,ℓ~,m~)]=E[δℓδm−θ0δm2].E[\psi(O;\theta_0,\widetilde\ell,\widetilde m)] =E[\delta_\ell\delta_m-\theta_0\delta_m^2].

There is no linear term in either perturbation. This does not make the PLR score doubly robust with respect to ℓ\ell and mm: if only ℓ\ell is correct and mm fails, the square can leave bias. Nor does it ensure efficiency without further conditions.

For contrast consider another naive moment, T{Y−θT−g~(X)}T\{Y-\theta T-\widetilde g(X)\}, where g~=g0+δg\widetilde g=g_0+\delta_g. At truth its expectation is −E[Tδg(X)]=−E[m0(X)δg(X)]-E[T\delta_g(X)]=-E[m_0(X)\delta_g(X)]. A regularization error in gg can therefore cause first-order bias even if the moment with g0g_0 were valid. This differs from the ratio that residualizes only YY in the first figure. Orthogonality removes this linear derivative around true nuisances, not every possible bias.

For ATE, the score is the AIPW contribution minus τ\tau. Let δe=e~−e\delta_e=\widetilde e-e and δt=μ~t−μt\delta_t=\widetilde\mu_t-\mu_t, with integrable contributions and e~\widetilde e bounded away from zero and one. Conditioning on XX, the identity from the previous lesson gives

E[ψAIPW(O;τ,e~,μ~)]=E[δe{δ1e~+δ01−e~}].E[\psi_{\rm AIPW}(O;\tau,\widetilde e,\widetilde\mu)] =E\left[\delta_e\left\{\frac{\delta_1}{\widetilde e}+ \frac{\delta_0}{1-\widetilde e}\right\}\right].

On a regular path perturbing all three functions by quantities of order hh, the right side has order h2h^2 under suitable moment conditions. Its derivative at h=0h=0 is zero: the ATE score is also orthogonal. Its remainder is a different product from PLR’s and leads to different rate conditions.

InteractiveA first-order flat score

Zero perturbation corresponds to the true functions. The curves show exact population expectations, with the effect fixed at its true value.

−1.70.01.7-1-0.500.51perturbation r
  • Naive score
  • Orthogonal score
  • Selected perturbation

Model: X, V and ε are independent, centered, and have unit variance; T = 1.5X + V and Y = 0.5T + 0.4X + ε. The true functions are g₀(X) = 0.4X, ℓ₀(X) = E[Y|X] = 1.15X and m₀(X) = E[T|X] = 1.5X. The naive score uses gᵣ = g₀ + arX; the orthogonal score uses ℓᵣ = ℓ₀ + arX and mᵣ = m₀ + brX.

Taking expectations gives -1.5ar for the naive score and (ab - 0.5b²)r² for the orthogonal score. The latter has zero derivative at r = 0, although it can change at second order. If b = 0, it is exactly flat for this perturbation. Orthogonality alone does not establish valid inference or correct unobserved confounding.

0.50
1.0
1.0
Naive score: expectation−0.750
Orthogonal score: expectation0.125
Naive slope at r = 0−1.500
Orthogonal slope at r = 00.000
Perturb nuisance functions and compare drift in both scores.

To see why orthogonality matters, imagine a naive estimator residualizing YY against XX, but dividing its product with TT by E[T2]E[T^2] without residualizing treatment. Even with ℓ0\ell_0 known it converges to θ0E[V2]/E[T2]\theta_0E[V^2]/E[T^2] under the model above. This attenuates toward zero when TT has a predictable component in XX with positive variance. Not every naive plug-in takes this form: the simulation specifies exactly what it compares.

Split and rotate

In cross-fitting divide observations into KK folds. For each fold fit ℓ^\widehat\ell and m^\widehat m on the other K−1K-1 and predict the held-out fold; concatenate predictions and solve the score with all observations. No observation is predicted by a model trained on it, although models for different folds share training data.

Splitting helps control the empirical term arising when estimated nuisances replace unknown ones: conditional on training, the held-out evaluation did not participate in fitting. It does not make that term exactly zero or guarantee valid inference without convergence, moments, identification, and design conditions. Rotation uses every observation for evaluation and training in other folds; it uses data better than one simple split, but efficiency requires the particular estimator’s conditions.

For PLR, a sufficient bound on the previous remainder is

∥m^−m0∥2{∥ℓ^−ℓ0∥2+∥m^−m0∥2}=op(n−1/2).\|\widehat m-m_0\|_2 \{\|\widehat\ell-\ell_0\|_2+\|\widehat m-m_0\|_2\} =o_p(n^{-1/2}).

Thus requiring only the product of errors in ℓ\ell and mm is insufficient: the square of error in mm also appears. Two rates Op(n−1/4)O_p(n^{-1/4}) do not ensure the scaled remainder vanishes. With i.i.d. data, suitable moments and relevance, nuisance consistency, and product and empirical-process conditions, the score expansion gives asymptotic normality.

With out-of-fold residuals vi=Ti−m^iv_i=T_i-\widehat m_i and ui=Yi−ℓ^iu_i=Y_i-\widehat\ell_i, define θ^=∑viui/∑vi2\widehat\theta=\sum v_iu_i/\sum v_i^2 and ψ^i=vi(ui−θ^vi)\widehat\psi_i=v_i(u_i-\widehat\theta v_i). A common standard-error estimate is

SE^=Pn[ψ^i2]n Pn[vi2].\widehat{SE}= \frac{\sqrt{\mathbb P_n[\widehat\psi_i^2]}} {\sqrt n\,\mathbb P_n[v_i^2]}.

This is an asymptotic formula for independent samples. With clustered or time-series data, respect dependence when splitting and estimating variance; mixing dependent observations across training and evaluation can invalidate the argument.

Select controls twice

Double selection by Belloni, Chernozhukov and Hansen runs lasso for YY on XX and for TT on XX, takes the union of selected controls, and fits a final regression of YY on TT and that union. A variable appearing weak for predicting YY may be decisive for predicting TT; the second selection gives another chance to retain it.

To quantify risk, suppose after removing included controls, residual treatment T~\widetilde T remains correlated with omitted residual confounder X~j\widetilde X_j whose outcome coefficient is βj\beta_j. The incomplete-regression slope contains βjE[T~X~j]/E[T~2]\beta_j E[\widetilde T\widetilde X_j]/E[\widetilde T^2] in addition to the target effect under other model conditions. Moderate βj\beta_j can matter greatly if treatment association is strong. The selection union reduces this risk under the method’s assumptions but does not guarantee every relevant confounder enters a finite sample.

The paper’s uniform inference result depends on assumptions such as approximate sparsity, design regularity, and penalty calibration. Running arbitrary lasso with arbitrary penalty does not yield it. Nor does it protect against unmeasured confounders. Selection is only over pretreatment variables justified by the causal graph; a later mediator can improve prediction while changing the causal question.

InteractiveSingle versus double selection

Both histograms use the same samples; each bar counts the replicates in its interval. The dashed line marks the true effect θ=1. Heights are replicate counts, not densities or probabilities.

021410.711.33Estimate of D effectReplicates
  • Single selection
  • Double selection
  • True value

Selection of confounder X₀: single 69.2 %; double-selection outcome branch 100.0 % and treatment branch 100.0 %. Double selection uses their union. There were 120 valid replicates out of 120; 0 did not converge or had singular fits.

Reproducible model: the 20 covariates, V and ε are independent N(0,1); D=1.2X₀+V and Y=D+0.35X₀+ε. A fixed seed 16016 is used, with new samples when n changes. The reference omitting X₀ is 1+0.35·1.2/(1+1.2²)≈1.172.

In single selection, lasso predicts Y using D and X, leaving the intercept and D unpenalized; OLS then re-estimates the effect with selected controls. Double selection runs lasso of Y on X and D on X, takes the union, and fits OLS. Both minimize ||residual||²/(2n)+λ||β||₁ and use the same λ in each branch.

Means and frequencies vary across simulations. Double selection does not guarantee recovery of every confounder or protect against unobserved confounding. Results depend on the model, n and λ; they do not establish coverage or uniform validity. Reference procedure: Belloni, Chernozhukov and Hansen; this simulation is original.

200
0.12
Mean single-selection bias0.035
Mean double-selection bias−0.019
Confounder: single69.2 %
Confounder: double100.0 %
Change sample size and penalty; observe the confounder and bias in both procedures.

From PLR to ATE and instruments

For ATE use out-of-fold predictions of e(X)e(X) and means μ0(X),μ1(X)\mu_0(X),\mu_1(X) in the AIPW score. It is an interactive model allowing heterogeneous effects and requires ignorability and overlap in the target population. Limiting extreme predictions can control calculations, but changes the procedure and creates no support where none exists; report how many predictions were modified.

With instrument ZZ, a partially linear version uses the moment

{Y−ℓ(X)−θ[T−m(X)]}{Z−r(X)},r(X)=E[Z∣X].\{Y-\ell(X)-\theta[T-m(X)]\}\{Z-r(X)\},\qquad r(X)=E[Z\mid X].

Besides nuisance models and orthogonality it needs instrument exogeneity, for example E[ε∣Z,X]=0E[\varepsilon\mid Z,X]=0 in the structural model, a valid exclusion restriction, and residual relevance E[(Z−r(X))(T−m(X))]≠0E[(Z-r(X))(T-m(X))]\ne0. A weak instrument can destabilize the denominator; DML does not replace weak-instrument diagnosis.

Choose learners and diagnose

Compare lasso, forest, and boosting with out-of-fold prediction criteria, respecting sample size and temporal or cluster structure. Good predictive error does not prove ignorability or identify the effect. Examine overlap, denominators, residuals, extremes, and sensitivity to choices. Changing split seeds reveals partition variability without turning splits of the same sample into independent experiments.

Repeating splits and taking the median estimate can stabilize one realization. For uncertainty, use a justified aggregation rule for estimates and standard errors; variation across splits does not replace sampling error. Fold count trades training size, evaluation size, and compute cost: there is no universally optimal value.

Lab: DML with scikit-learn

The first world is our own, not the published experiment. Compare the nonorthogonal ratio, orthogonal score evaluated on training data, and the same score with two folds. Twenty replicates only illustrate variation; they cannot establish nominal coverage.

[ ]numpyBrowser
import numpy as np
[ ]scipyBrowser
import scipy
[ ]scipy sparseBrowser
import scipy.sparse
[ ]scipy specialBrowser
import scipy.special
[ ]sklearn baseBrowser
from sklearn.base import clone
[ ]sklearn modelsBrowser
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import Lasso
from sklearn.model_selection import KFold
[ ]plr setupBrowser
# DGP propio: no son los datos ni la simulación exacta del artículo.
# La variable de tratamiento es continua y las covariables son previas.
def muestra_plr(seed, n=300, p=8):
    rng = np.random.default_rng(seed)
    x = rng.normal(size=(n, p))
    m = 1.5*np.sin(x[:, 0]) + 0.8*x[:, 1]
    g = 1.8*np.sin(x[:, 0]) + 0.7*x[:, 1]**2 + x[:, 2]
    t = m + rng.normal(size=n)
    y = 1.0*t + g + rng.normal(size=n)
    return x, t, y

def dml_plr(y, t, x, learner_y, learner_t, k=2, seed=1, crossfit=True):
    n = len(y)
    if not 2 <= k <= n:
        raise ValueError('k debe estar entre 2 y n')
    ell = np.empty(n); m = np.empty(n)
    if crossfit:
        folds = KFold(n_splits=k, shuffle=True, random_state=seed).split(x)
    else:
        folds = [(np.arange(n), np.arange(n))]
    for train, test in folds:
        model_y = clone(learner_y).fit(x[train], y[train])
        model_t = clone(learner_t).fit(x[train], t[train])
        ell[test] = model_y.predict(x[test])
        m[test] = model_t.predict(x[test])
    ry, rt = y-ell, t-m
    jac = np.mean(rt**2)
    if jac < 1e-12:
        raise ValueError('Sin variación residual del tratamiento')
    theta = np.mean(rt*ry)/jac
    psi = rt*(ry-theta*rt)
    se = np.sqrt(np.mean(psi**2)/n)/jac
    return theta, se, ell, m

def bosque(seed=2, leaf=2):
    return RandomForestRegressor(n_estimators=12, min_samples_leaf=leaf,
                                 max_features=0.8, random_state=seed, n_jobs=1)

def una_replica(seed):
    x, t, y = muestra_plr(seed)
    model = bosque(seed+500)
    fit = dml_plr(y, t, x, model, model, k=2, seed=seed+2000, crossfit=False)
    cross = dml_plr(y, t, x, model, model, k=2, seed=seed+2000, crossfit=True)
    # Esta puntuación no ortogonal utiliza la media E[Y|X], no g(X).
    # El denominador es E[T²], no E[(T-m(X))²].
    naive = np.mean(t*(y-fit[2]))/np.mean(t*t)
    return naive, fit[0], fit[1], cross[0], cross[1]

print('PLR: theta = 1; X previo, ruido independiente y E[(T-m(X))²] = 1')
[ ]plr simulationBrowser
# Primera mitad: la siguiente celda completa las 20 réplicas.
resultados = [una_replica(s) for s in range(10)]
print('Completadas 10 réplicas')
[ ]plr simulation endBrowser
resultados.extend(una_replica(s) for s in range(10, 20))
resultados = np.array(resultados)
for nombre, col in [('ingenuo', 0), ('ortogonal, sin partición', 1),
                    ('DML, dos pliegues', 3)]:
    a = resultados[:, col]
    print(nombre, 'media =', round(a.mean(), 4),
          'sesgo =', round(a.mean()-1, 4),
          'desviación =', round(a.std(ddof=1), 4))
for nombre, col in [('sin partición', 1), ('DML', 3)]:
    a, se = resultados[:, col], resultados[:, col+1]
    print(nombre, 'cobertura IC 95% =', round(np.mean(abs(a-1) <= 1.96*se), 3),
          'error estándar medio =', round(se.mean(), 4))
[ ]plr oracleBrowser
# Solo diagnóstico: θ=1 es conocido porque generamos los datos. En un estudio
# real no podemos construir Y-θT sin estimar θ. La división es externa.
def plugin_con_oraculo(seed):
    x, t, y = muestra_plr(seed)
    ghat = np.empty(len(y))
    for train, test in KFold(n_splits=2, shuffle=True, random_state=seed+2000).split(x):
        ghat[test] = bosque(seed+500).fit(x[train], y[train]-t[train]).predict(x[test])
    return np.mean(t*(y-ghat))/np.mean(t*t)

oraculo = np.array([plugin_con_oraculo(s) for s in range(12)])
print('Plug-in con g entrenada con θ verdadero, promedio =', round(oraculo.mean(), 4),
      'sesgo =', round(oraculo.mean()-1, 4))
[ ]plr sensitivityBrowser
x, t, y = muestra_plr(2026)
for kind, learner in [
    ('Lasso', Lasso(alpha=0.06, max_iter=2000)),
    ('bosque', bosque(12)),
    ('boosting', GradientBoostingRegressor(n_estimators=30, max_depth=2, random_state=12))]:
    for k in (2, 5):
        vals = [dml_plr(y, t, x, learner, learner, k=k, seed=s)[:2]
                for s in (1, 7, 29)]
        vals = np.array(vals)
        median = np.median(vals[:, 0])
        # Agregación mediana de varianzas con variación entre particiones.
        se_med = np.sqrt(np.median(vals[:, 1]**2 + (vals[:, 0]-median)**2))
        print(kind, 'K =', k, 'estimaciones =', np.round(vals[:, 0], 3),
              'mediana =', round(median, 3), 'SE agregado =', round(se_med, 3))

The following generator implements the figure 1 DGP documented by DoubleML. Twelve replicates and a small forest are a brief check, not a numerical reproduction of the paper’s histograms. The diagnostic plug-in uses the true θ to train g, information unavailable in a real study.

[ ]paper plr setupBrowser
# DGP publicado por el equipo DoubleML para la figura 1 de Chernozhukov et al.
# https://docs.doubleml.org/stable/api/generated/doubleml.plm.datasets.make_plr_CCDDHNR2018.html
def muestra_paper(seed,n=500,p=20):
    rng=np.random.default_rng(seed)
    innovations=rng.normal(size=(n,p))
    X=np.empty_like(innovations)
    X[:,0]=innovations[:,0]
    for j in range(1,p):
        X[:,j]=.7*X[:,j-1]+np.sqrt(1-.7**2)*innovations[:,j]
    # Esta construcción AR(1) da Cov(X_j,X_k)=0,7^|j-k|.
    prob=lambda z: 1/(1+np.exp(-z))
    m=X[:,0]+.25*prob(X[:,2])
    g=prob(X[:,0])+.25*X[:,2]
    t=m+rng.normal(size=n)
    y=.5*t+g+rng.normal(size=n)
    return X,t,y

def paper_replica(seed):
    X,t,y=muestra_paper(seed)
    model=bosque(seed+600)
    fitted=dml_plr(y,t,X,model,model,k=2,seed=seed+700,crossfit=False)
    held=dml_plr(y,t,X,model,model,k=2,seed=seed+700,crossfit=True)
    # Diagnóstico: entrenar g con theta verdadero solo es posible en simulación.
    ghat=np.empty(len(y))
    for train,test in KFold(n_splits=2,shuffle=True,random_state=seed+700).split(X):
        ghat[test]=bosque(seed+600).fit(X[train],y[train]-.5*t[train]).predict(X[test])
    naive=np.mean(t*(y-ghat))/np.mean(t*t)
    return naive,fitted[0],held[0],held[1]

paper_values=[]
print('DGP oficial n=500 p=20 θ=0,5; 12 réplicas, bosque de 12 árboles y K=2.')
print('Solo el plug-in diagnóstico utiliza θ verdadero al ajustar g; no es un estimador aplicable directamente.')
[ ]paper plr 1Browser
paper_values.extend(paper_replica(s+16000) for s in range(4))
print('Completadas 4 de 12 réplicas')
[ ]paper plr 2Browser
paper_values.extend(paper_replica(s+16004) for s in range(4))
print('Completadas 8 de 12 réplicas')
[ ]paper plr 3Browser
paper_values.extend(paper_replica(s+16008) for s in range(4))
paper_values=np.asarray(paper_values)
print('Medias: plug-in diagnóstico, ortogonal en muestra, DML:',np.round(paper_values[:,:3].mean(axis=0),4))
print('Cobertura DML:',np.mean(abs(paper_values[:,2]-.5)<=1.96*paper_values[:,3]),'sobre',len(paper_values),'réplicas')
print('Comparación exploratoria: 12 réplicas no determinan cobertura ni reproducen el histograma publicado.')

For ATE, generate binary treatment and outcome with pretreatment covariates and calculate true ATE by quadrature. Imports and replicates are split into cells so each computation is manageable in the browser.

[ ]ate imports scipyBrowser
import scipy
[ ]ate imports sparseBrowser
import scipy.sparse
[ ]ate imports specialBrowser
import scipy.special
[ ]ate imports linalgBrowser
import scipy.linalg
[ ]ate imports baseBrowser
from sklearn.base import clone
[ ]ate imports ensembleBrowser
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
[ ]ate imports modelsBrowser
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
[ ]ate imports pipelineBrowser
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
[ ]ate setupBrowser
def sigmoid_dml(z):
    return 1/(1+np.exp(-np.clip(z,-35,35)))

def ate_data(seed=161601, n=1400, p=8):
    """T binario e Y binario con ignorabilidad por construcción.

    X = tanh(Z), Z normal i.i.d.; U_T y U_Y independientes, y potenciales bajo una
    probabilidad que depende de X y tratamiento. No se usan covariables futuras.
    """
    rng=np.random.default_rng(seed)
    X=np.tanh(rng.normal(size=(n,p)))
    e=sigmoid_dml(-.2+.6*X[:,0]-.4*X[:,1])
    t=rng.binomial(1,e)
    q0=sigmoid_dml(-.6+.5*X[:,0]-.35*X[:,1])
    q1=sigmoid_dml(-.2+.5*X[:,0]-.35*X[:,1]+.2*X[:,2])
    y=rng.binomial(1,np.where(t==1,q1,q0))
    # Cuadratura de Gauss-Hermite sobre las tres normales independientes.
    # Repetir con dos órdenes detecta discrepancias por truncar la cuadratura.
    def quadrature(order):
        nodes,weights=np.polynomial.hermite.hermgauss(order)
        z=np.tanh(np.sqrt(2)*nodes)
        w=weights/np.sqrt(np.pi)
        linear=.5*z[:,None,None]-.35*z[None,:,None]
        diff=sigmoid_dml(-.2+linear+.2*z[None,None,:])-sigmoid_dml(-.6+linear)
        return np.einsum('i,j,k,ijk->',w,w,w,diff)
    target=quadrature(40)
    assert abs(target-quadrature(32))<1e-6
    return X,t,y,float(target)

def ate_learners(kind,seed):
    if kind=='logistica':
        def model(): return make_pipeline(StandardScaler(),LogisticRegression(C=1e4,max_iter=200))
    elif kind=='bosque':
        def model(): return RandomForestClassifier(n_estimators=30,max_depth=5,min_samples_leaf=12,random_state=seed,n_jobs=1)
    elif kind=='boosting':
        def model(): return HistGradientBoostingClassifier(max_iter=35,max_leaf_nodes=7,l2_regularization=2.,random_state=seed)
    else:
        raise ValueError('Aprendiz desconocido')
    return model(),model()

def dml_ate(y,t,X,learner_e,learner_y,k=3,seed=1,lower=.02):
    """AIPW con predicciones fuera de pliegue; tasas e identificación importan."""
    y,t,X=np.asarray(y,float),np.asarray(t,float),np.asarray(X,float)
    if y.ndim!=1 or t.ndim!=1 or X.ndim!=2 or len(y)!=len(t) or len(X)!=len(y) or not 0<lower<.5:
        raise ValueError('Entradas o umbral inválidos')
    if not np.isfinite(X).all() or not np.isfinite(y).all() or not np.isin(t,[0,1]).all():
        raise ValueError('Datos inválidos')
    if not np.isin(y,[0,1]).all(): raise ValueError('Se espera resultado binario')
    eh=np.full(len(y),np.nan);q0=np.full(len(y),np.nan);q1=np.full(len(y),np.nan)
    # La partición se genera independientemente de los valores observados.
    folds=KFold(n_splits=k,shuffle=True,random_state=seed)
    for train,test in folds.split(X):
        ee=clone(learner_e).fit(X[train],t[train])
        eh[test]=ee.predict_proba(X[test])[:,1]
        for arm,out in ((0,q0),(1,q1)):
            subset=train[t[train]==arm]
            if len(np.unique(y[subset]))!=2: raise ValueError('Un brazo carece de clases de Y')
            yy=clone(learner_y).fit(X[subset],y[subset])
            out[test]=yy.predict_proba(X[test])[:,1]
    if not all(np.isfinite(v).all() for v in (eh,q0,q1)):
        raise ValueError('Predicciones incompletas')
    clipped=np.mean((eh<lower)|(eh>1-lower))
    eh=np.clip(eh,lower,1-lower)
    score=q1-q0+t*(y-q1)/eh-(1-t)*(y-q0)/(1-eh)
    estimate=score.mean();se=score.std(ddof=1)/np.sqrt(len(score))
    return estimate,se,clipped

def report_ate(kind,seed=161602):
    le,ly=ate_learners(kind,seed)
    est,se,clipped=dml_ate(y_ate,t_ate,X_ate,le,ly,k=3,seed=seed)
    print(kind,'ATE',round(est,4),'EE',round(se,4),'IC 95%',np.round([est-1.96*se,est+1.96*se],4),
          'fracción con propensión limitada',round(clipped,4))
    return est,se,clipped

X_ate,t_ate,y_ate,true_ate=ate_data()
print('n=',len(y_ate),'tratados=',int(t_ate.sum()),'ATE poblacional por cuadratura=',round(true_ate,6))
print('Cada observación se evalúa fuera del pliegue que ajustó ambas nuisances.')
[ ]ate logitBrowser
ate_logistic=report_ate('logistica')
[ ]ate forestBrowser
ate_forest=report_ate('bosque')
[ ]ate boostingBrowser
ate_boost=report_ate('boosting')
[ ]ate repetitionsBrowser
# Tres particiones del mismo conjunto, no tres estudios independientes.
fits=[]
for split_seed in (41,42,43):
    le,ly=ate_learners('logistica',split_seed)
    fits.append(dml_ate(y_ate,t_ate,X_ate,le,ly,k=3,seed=split_seed)[:2])
fits=np.asarray(fits)
median=np.median(fits[:,0])
# Regla de agregación por medianas: incorpora variabilidad de particiones.
# Las repeticiones comparten la muestra y suponen inferencia DML válida.
aggregate_se=np.sqrt(np.median(fits[:,1]**2+(fits[:,0]-median)**2))
print('Tres particiones, pares estimación/EE:',np.round(fits,4))
print('Mediana:',round(median,4),'EE agregado:',round(aggregate_se,4),
      'IC 95%:',np.round([median-1.96*aggregate_se,median+1.96*aggregate_se],4))

The following check repeats sampling 100 times for the logistic learner; its coverage is a simulated frequency with Monte Carlo error, not a general guarantee.

[ ]ate coverage setupBrowser
def coverage_block(start, repetitions=25):
    """Cobertura Monte Carlo de un solo aprendiz y tamaño fijo; semillas diferentes."""
    rows=[]
    for rep in range(start,start+repetitions):
        x,t,y,true=ate_data(seed=162000+rep,n=700)
        le,ly=ate_learners('logistica',162500+rep)
        est,se,clipped=dml_ate(y,t,x,le,ly,k=2,seed=163000+rep)
        rows.append((est-true,se,clipped))
    return rows
coverage_rows=[]
[ ]ate coverage 1Browser
coverage_rows.extend(coverage_block(0))
[ ]ate coverage 2Browser
coverage_rows.extend(coverage_block(25))
[ ]ate coverage 3Browser
coverage_rows.extend(coverage_block(50))
[ ]ate coverage 4Browser
coverage_rows.extend(coverage_block(75))
arr=np.asarray(coverage_rows)
covered=np.abs(arr[:,0])<=1.96*arr[:,1]
rate=covered.mean();mcse=np.sqrt(rate*(1-rate)/len(covered))
print('DML logístico: réplicas',len(covered),'sesgo',round(arr[:,0].mean(),4),
      'cobertura',round(rate,3),'EE Monte Carlo',round(mcse,3),
      'fracción media de predicciones limitadas',round(arr[:,2].mean(),4))
print('Resultado exploratorio de una simulación, no garantía de cobertura en otras poblaciones.')

Lab: selection and comparison with DoubleML

This cell runs in local Python with a connection to download official DoubleML 401(k) eligibility data. Install doubleml==0.11.4 along with scikit-learn, statsmodels, and dependencies. One thread is used to contain resource usage.

Covariates come from the survey and not all have been shown to precede eligibility: interpret these figures as associations unless timing, ignorability, and other causal assumptions are justified. The PLR slope and interactive ATE may answer different targets. IRM limits propensities to [0.01, 0.99]; the count outside is reported and the same limit is used for manual comparison.

[ ]local 401kLocal GPU
import numpy as np
import doubleml as dml
import statsmodels.api as sm
from doubleml.datasets import fetch_401K
from doubleml.utils import PSProcessorConfig
from sklearn.base import clone
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.linear_model import LassoCV
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from threadpoolctl import threadpool_limits

# Las variables proceden del ejemplo oficial de DoubleML. Son medidas en la
# encuesta y no está garantizado que todas precedan a la elegibilidad.
controls = ['age', 'inc', 'educ', 'fsize', 'marr', 'twoearn', 'db', 'pira', 'hown']
raw = fetch_401K(return_type='DataFrame')
frame = raw[['net_tfa', 'e401'] + controls].dropna().reset_index(drop=True)
y = frame['net_tfa'].to_numpy(dtype=float)
t = frame['e401'].to_numpy(dtype=float)
x = frame[controls].to_numpy(dtype=float)
print('DoubleML', dml.__version__, '| observaciones:', len(frame), '| elegibles:', int(t.sum()))

# Doble selección: mismo conjunto muestral; todas las columnas resultantes del
# polinomio se seleccionan sin usar e401 como entrada. Eliminamos duplicados y
# columnas constantes antes de estimar el OLS, y conservamos interacciones.
poly = PolynomialFeatures(degree=2, include_bias=False)
xp = poly.fit_transform(x)
names = poly.get_feature_names_out(controls)
_, keep = np.unique(xp, axis=1, return_index=True)
keep = sorted(j for j in keep if np.std(xp[:, j]) > 1e-12)
xp, names = xp[:, keep], names[keep]
with threadpool_limits(limits=1):
    def select(target):
        model = make_pipeline(StandardScaler(), LassoCV(cv=3, alphas=50, max_iter=20000))
        model.fit(xp, target)
        return np.abs(model[-1].coef_) > 1e-10
    selected_y = select(y)
    selected_t = select(t)
    union = selected_y | selected_t
    design = sm.add_constant(np.column_stack([t, xp[:, union]]), has_constant='add')
    if np.linalg.matrix_rank(design) != design.shape[1]:
        raise ValueError('Matriz OLS singular: revisa variables seleccionadas')
    pds = sm.OLS(y, design).fit(cov_type='HC1')
    print('Doble selección: controles candidatos', xp.shape[1],
          '| seleccionados resultado', int(selected_y.sum()),
          '| tratamiento', int(selected_t.sum()), '| unión', int(union.sum()))
    print('Doble selección: efecto =', round(pds.params[1], 2),
          '| SE HC1 =', round(pds.bse[1], 2))

    # La misma muestra, predictores, arquitectura y particiones para ambos;
    # la variable que predice el modelo de Y difiere por definición en IRM.
    data = dml.DoubleMLData(frame, y_col='net_tfa', d_cols='e401', x_cols=controls)
    learner_y = RandomForestRegressor(n_estimators=30, min_samples_leaf=12,
                                      max_features=0.8, random_state=2026, n_jobs=1)
    learner_t = RandomForestClassifier(n_estimators=30, min_samples_leaf=12,
                                        max_features=0.8, random_state=2027, n_jobs=1)
    folds = list(KFold(n_splits=3, shuffle=True, random_state=42).split(x))
    plr = dml.DoubleMLPLR(data, ml_l=clone(learner_y), ml_m=clone(learner_t),
                           n_folds=3, draw_sample_splitting=False)
    irm = dml.DoubleMLIRM(data, ml_g=clone(learner_y), ml_m=clone(learner_t),
                           n_folds=3, score='ATE', draw_sample_splitting=False,
                           ps_processor_config=PSProcessorConfig(clipping_threshold=0.01))
    plr.set_sample_splitting(folds); irm.set_sample_splitting(folds)
    plr.fit(); irm.fit()
    for label, obj in [('DoubleML PLR', plr), ('DoubleML IRM ATE', irm)]:
        print(label, 'efecto =', round(obj.coef[0], 2), '| SE =', round(obj.se[0], 2))

    # Una implementación transparente del score PLR, usando exactamente las
    # mismas divisiones y los mismos aprendices, para detectar discrepancias.
    ell, m = np.empty(len(y)), np.empty(len(y))
    for train, test in folds:
        ell[test] = clone(learner_y).fit(x[train], y[train]).predict(x[test])
        m[test] = clone(learner_t).fit(x[train], t[train]).predict_proba(x[test])[:, 1]
    ry, rt = y - ell, t - m
    jac = np.mean(rt**2)
    own = np.mean(rt*ry)/jac
    own_se = np.sqrt(np.mean((rt*(ry-own*rt))**2)/len(y))/jac
    print('PLR propio: efecto =', round(own, 2), '| SE =', round(own_se, 2))
    print('Diferencia absoluta propia frente a DoubleML =', round(abs(own-plr.coef[0]), 8))
    print('Propensión estimada, mínimo y máximo =', round(m.min(), 4), round(m.max(), 4))
    print('Observaciones con propensión fuera de [0,01, 0,99] =',
          int(np.sum((m < 0.01) | (m > 0.99))),
          '| IRM recorta sus predicciones a ese intervalo')

    # IRM propio: misma muestra y particiones, con el mismo recorte explícito.
    mu0, mu1 = np.empty(len(y)), np.empty(len(y))
    for train, test in folds:
        idx0, idx1 = train[t[train] == 0], train[t[train] == 1]
        mu0[test] = clone(learner_y).fit(x[idx0], y[idx0]).predict(x[test])
        mu1[test] = clone(learner_y).fit(x[idx1], y[idx1]).predict(x[test])
    q = np.clip(m, 0.01, 0.99)
    scores = mu1-mu0 + t*(y-mu1)/q - (1-t)*(y-mu0)/(1-q)
    own_irm = scores.mean()
    own_irm_se = np.sqrt(np.mean((scores-own_irm)**2)/len(y))
    print('IRM propio: ATE =', round(own_irm, 2), '| SE =', round(own_irm_se, 2))
    print('Diferencias absolutas IRM propio frente a DoubleML:',
          round(abs(own_irm-irm.coef[0]), 8), round(abs(own_irm_se-irm.se[0]), 8))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofDerive orthogonality
Prove: In the PLR model, define V=T−m0(X)V=T-m_0(X) and ε=Y−ℓ0(X)−θ0V\varepsilon=Y-\ell_0(X)-\theta_0V. Assume E[V∣X]=0E[V\mid X]=0, E[ε∣T,X]=0E[\varepsilon\mid T,X]=0 and sufficient moments. Prove score orthogonality with respect to (ℓ,m)(\ell,m).
The proof will appear here as you work.

Step 1 of 3. What residuals appear after substituting perturbations δℓ and δm?

ProofThe term that does not vanish on its own
Prove: A complex learner estimates η^\widehat\eta using the same observations that evaluate the score. Explain why orthogonality alone does not eliminate (Pn−P){ψ(η^)−ψ(η0)}(\mathbb P_n-P)\{\psi(\widehat\eta)-\psi(\eta_0)\}.
The proof will appear here as you work.

Step 1 of 2. Why is it insufficient to say the average has zero expectation for a fixed nuisance?

NumericOut-of-fold residuals
Eight residuals are v=(-2,-1,0,1,2,-2,1,1) for T and u=(-3,-1,1,2,3,-4,2,1) for Y. Calculate the Robinson estimator sum(vu)/sum(v²).
NumericRobinson uncertainty
Use the same eight residuals and the previous estimate. Calculate the score’s HC0 standard error to four decimals.
CodeSplit and residualize
Implement dml_plr(y, t, X, learner_y, learner_t, k), with scikit-learn interface learners and continuous response. Return (theta, se). Check that y and t are finite vectors of equal length, X is a finite numeric matrix with one row per unit, and k is an integer between 2 and n. Reject invalid inputs with ValueError. Use KFold(n_splits=k, shuffle=True, random_state=271616). In each fold, clone and train each learner only on other observations and predict exclusively held-out observations. With out-of-fold residuals v = t - m_hat and u = y - l_hat, calculate theta = sum(vu)/sum(vv). Reject a zero or non-finite denominator. Calculate robust HC0 standard error as sqrt(sum((v(u-thetav))*2))/sum(vv) and reject non-finite or incorrectly shaped predictions. Leave input learners intact. The standard error corresponds to a partially linear score with i.i.d. data; inferential validity requires identification, residual variation, moments, and suitable learner rates.
def dml_plr(y, t, X, learner_y, learner_t, k):
  # Predice cada observación con modelos entrenados fuera de su pliegue.
  # Calcula el coeficiente de Robinson y su error estándar HC0.
  raise NotImplementedError
Shift+Enter to run
QuizFew observations
You have little data and many plausible pretreatment controls. Which strategy is most defensible?
QuizNonlinear relationships
With substantial data and plausible nonlinear relationships, what diagnostics accompany a forest in DML?
QuizTemporally dependent data
Records form a strongly dependent time series. What revision does the illustrated i.i.d. DML require?

After solving the numeric exercise, you can check its calculations:

[ ]Check Robinson residualsBrowser
import numpy as np

v = np.array([-2,-1,0,1,2,-2,1,1], dtype=float)
u = np.array([-3,-1,1,2,3,-4,2,1], dtype=float)
denom = np.sum(v*v)
theta = np.sum(v*u)/denom
scores = v*(u-theta*v)
se = np.sqrt(np.sum(scores*scores))/denom
print('Residuos del tratamiento:', v)
print('Residuos del resultado:', u)
print('Suma v², suma vu:', denom, np.sum(v*u))
print('Robinson y EE HC0:', theta, se)