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.
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.
"""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))npm run lab and open the connection link.Partialling out without assuming linearity in controls
Consider the partially linear model
Here is constant, is an unknown function, and residual variation must be positive. Define . Subtracting conditional expectations gives
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 , the residual cross-product ratio estimates . With out-of-fold predictions, each observation is evaluated by models that did not train on it.
In the finite linear case, let be the orthogonal projection onto columns of the control matrix and . Normal equations for regression of on and give when the denominator is nonzero. This ratio is exactly the no-intercept regression of on . Replacing 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 is binary and effect varies with , the residualized slope is generally not ATE: under appropriate conditions it weights conditional effects by . 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 is Neyman orthogonal at truth if and the directional derivative of its expectation with respect to nuisance is zero in every admissible direction. For , the partially linear score is
Let and . Substituting and , using and , gives the exact identity
There is no linear term in either perturbation. This does not make the PLR score doubly robust with respect to and : if only is correct and fails, the square can leave bias. Nor does it ensure efficiency without further conditions.
For contrast consider another naive moment, , where . At truth its expectation is . A regularization error in can therefore cause first-order bias even if the moment with were valid. This differs from the ratio that residualizes only 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 . Let and , with integrable contributions and bounded away from zero and one. Conditioning on , the identity from the previous lesson gives
On a regular path perturbing all three functions by quantities of order , the right side has order under suitable moment conditions. Its derivative at is zero: the ATE score is also orthogonal. Its remainder is a different product from PLR’s and leads to different rate conditions.
To see why orthogonality matters, imagine a naive estimator residualizing against , but dividing its product with by without residualizing treatment. Even with known it converges to under the model above. This attenuates toward zero when has a predictable component in 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 folds. For each fold fit and on the other 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
Thus requiring only the product of errors in and is insufficient: the square of error in also appears. Two rates 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 and , define and . A common standard-error estimate is
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 on and for on , takes the union of selected controls, and fits a final regression of on and that union. A variable appearing weak for predicting may be decisive for predicting ; the second selection gives another chance to retain it.
To quantify risk, suppose after removing included controls, residual treatment remains correlated with omitted residual confounder whose outcome coefficient is . The incomplete-regression slope contains in addition to the target effect under other model conditions. Moderate 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.
From PLR to ATE and instruments
For ATE use out-of-fold predictions of and means 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 , a partially linear version uses the moment
Besides nuisance models and orthogonality it needs instrument exogeneity, for example in the structural model, a valid exclusion restriction, and residual relevance . 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.
import numpy as npimport scipyimport scipy.sparseimport scipy.specialfrom sklearn.base import clonefrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import Lasso
from sklearn.model_selection import KFold# 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')# Primera mitad: la siguiente celda completa las 20 réplicas.
resultados = [una_replica(s) for s in range(10)]
print('Completadas 10 réplicas')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))# 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))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.
# 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_values.extend(paper_replica(s+16000) for s in range(4))
print('Completadas 4 de 12 réplicas')paper_values.extend(paper_replica(s+16004) for s in range(4))
print('Completadas 8 de 12 réplicas')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.
import scipyimport scipy.sparseimport scipy.specialimport scipy.linalgfrom sklearn.base import clonefrom sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifierfrom sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFoldfrom sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScalerdef 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_logistic=report_ate('logistica')ate_forest=report_ate('bosque')ate_boost=report_ate('boosting')# 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.
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=[]coverage_rows.extend(coverage_block(0))coverage_rows.extend(coverage_block(25))coverage_rows.extend(coverage_block(50))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.
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))npm run lab and open the connection link.Exercises
Step 1 of 3. What residuals appear after substituting perturbations δℓ and δm?
Step 1 of 2. Why is it insufficient to say the average has zero expectation for a fixed nuisance?
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 NotImplementedErrorAfter solving the numeric exercise, you can check its calculations:
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)