DEV Community

Nylah Reynard
Nylah Reynard

Posted on

Why Regularized ML Plug-In Crashed Our 95% CI Coverage to 20.6% (Orthogonal DML in Python)

A common intuition among machine learning engineers moving into observational causal inference goes something like this:

"We have an outcome Y, an observed treatment D, and high-dimensional confounders X. Why not simply train a penalized regressor or an ensemble on [D, X], unpenalize the treatment column D, evaluate on a test split, and extract the resulting treatment coefficient?"

On paper, this sounds reasonable. You are using flexible machine learning to control for nonlinear confounding, and you are not penalizing the coefficient of interest.

In practice, this plug-in strategy fails catastrophically. Even when your model predicts Y with high accuracy on held-out test data, your 95% confidence intervals can collapse to an empirical coverage of barely 20%.

Here is why that happens mathematically, how Victor Chernozhukov and colleagues resolved it via Double Machine Learning (DML) in their foundational 2018 paper (The Econometrics Journal), and a 500-run Monte Carlo benchmark you can run directly in pure NumPy.


The Regularization Leakage Mechanism

Consider the classic partially linear regression setup:

Y = theta_0 × D + g_0(X) + U, where E[U | D, X] = 0

D = m_0(X) + V, where E[V | X] = 0

Here, theta_0 is the constant causal treatment effect we want to estimate, g_0(X) is the true confounding response surface, and m_0(X) is the treatment assignment mechanism (the propensity or exposure function).

When you fit a regularized estimator (such as Lasso, Ridge, gradient-boosted trees, or neural networks) to predict Y directly from [D, X], the algorithm minimizes prediction error under an inductive bias or shrinkage penalty. That shrinkage forces the learned nuisance function g_hat(X) toward zero.

Because treatment assignment D is correlated with confounders X through m_0(X), D and X share collinear variance. When g_hat(X) underfits or shrinks the true confounding surface g_0(X), the unmodeled residual g_0(X) - g_hat(X) does not disappear into white noise. Instead, it projects straight onto D.

That regularization shrinkage spills directly into your treatment parameter estimate theta_hat. Specifically, the estimation error decomposes into:

theta_hat - theta_0 = (D^T D)^(-1) D^T (g_0(X) - g_hat(X)) + (D^T D)^(-1) D^T U

The second term is mean-zero estimation noise that scales at O_P(n^(-1/2)). But the first term—the regularization bias—scales at the convergence rate of your machine learning estimator g_hat, which is at best O_P(n^(-1/4)) in high-dimensional or nonparametric settings.

Because n^(-1/4) is orders of magnitude larger than n^(-1/2) in moderate sample sizes, that regularization bias dominates the sampling distribution. The entire sampling distribution of theta_hat shifts systematically away from theta_0. When you construct standard 95% confidence intervals centered on an offset estimate, your intervals miss the true effect in 4 out of 5 experiments.


A Self-Contained Monte Carlo Benchmark in Pure NumPy

To verify this phenomenon without third-party dependencies, we run 500 independent Monte Carlo trials. In each trial, we generate N = 600 observations with p = 20 raw covariates expanded into 99 nonlinear basis features (linear, quadratic, sinusoidal, and adjacent pairwise interactions).

We compare two approaches under the exact same L2 regularization penalty (lam = 6.0):

  • Non-orthogonal Plug-In ML: Fits Ridge on split 1 with unpenalized treatment D, predicts g_hat onto split 2, and runs OLS on the residual outcome.
  • 5-Fold Double Machine Learning: Cross-fits out-of-fold residuals for both outcome Y and treatment D, then partials them out.
import numpy as np

rng = np.random.default_rng(20261130)
theta_true = 0.50
n_obs, p_raw, n_trials = 600, 20, 500

def build_basis(X):
    cols = [X, X ** 2 - 1.0, np.sin(X), np.cos(X)]
    inter = [X[:, i : i + 1] * X[:, i + 1 : i + 2] for i in range(p_raw - 1)]
    return np.hstack(cols + inter)

def ridge_fit_pred(Phi_tr, y_tr, Phi_ev, lam=6.0):
    mu = y_tr.mean()
    m_phi = Phi_tr.mean(axis=0, keepdims=True)
    P_c = Phi_tr - m_phi
    beta = np.linalg.solve(P_c.T @ P_c + lam * np.eye(P_c.shape[1]), P_c.T @ (y_tr - mu))
    return mu + (Phi_ev - m_phi) @ beta

no_e, no_c, dm_e, dm_c = [], 0, [], 0
for _ in range(n_trials):
    X = rng.normal(0.0, 1.0, size=(n_obs, p_raw))
    m0 = 1.4 * np.sin(X[:, 0]) + 1.1 * (X[:, 1] ** 2 - 1.0) + 0.9 * X[:, 2] * X[:, 3] + 0.7 * np.cos(X[:, 4])
    g0 = 1.6 * np.sin(X[:, 0]) + 1.3 * (X[:, 1] ** 2 - 1.0) + 1.1 * X[:, 2] * X[:, 3] + 0.8 * np.cos(X[:, 4])
    D = m0 + rng.normal(0.0, 1.0, size=n_obs)
    Y = theta_true * D + g0 + rng.normal(0.0, 1.0, size=n_obs)
    Phi = build_basis(X)

    h = n_obs // 2
    Z_1 = np.column_stack([D[:h], Phi[:h]])
    Z_c = Z_1 - Z_1.mean(axis=0, keepdims=True)
    pen = 6.0 * np.eye(Z_1.shape[1])
    pen[0, 0] = 0.0
    w_hat = np.linalg.solve(Z_c.T @ Z_c + pen, Z_c.T @ (Y[:h] - Y[:h].mean()))
    g_hat_2 = (Y[:h].mean() - w_hat[0] * D[:h].mean()) + (Phi[h:] - Phi[:h].mean(axis=0, keepdims=True)) @ w_hat[1:]
    th_no = float(np.dot(D[h:], Y[h:] - g_hat_2) / np.dot(D[h:], D[h:]))
    res_no = (Y[h:] - g_hat_2 - th_no * D[h:]) * D[h:]
    se_no = float(np.sqrt(np.mean(res_no ** 2) / (np.mean(D[h:] ** 2) ** 2) / (n_obs - h)))
    no_e.append(th_no)
    if abs(th_no - theta_true) <= 1.96 * se_no:
        no_c += 1

    ry_cf = np.zeros(n_obs)
    rd_cf = np.zeros(n_obs)
    idx = np.arange(n_obs)
    step = n_obs // 5
    for k in range(5):
        te = idx[k * step : (k + 1) * step]
        tr = np.concatenate([idx[: k * step], idx[(k + 1) * step :]])
        ry_cf[te] = Y[te] - ridge_fit_pred(Phi[tr], Y[tr], Phi[te], lam=6.0)
        rd_cf[te] = D[te] - ridge_fit_pred(Phi[tr], D[tr], Phi[te], lam=6.0)
    th_cf = float(np.dot(rd_cf, ry_cf) / np.dot(rd_cf, rd_cf))
    psi_cf = (ry_cf - th_cf * rd_cf) * rd_cf
    se_cf = float(np.sqrt(np.mean(psi_cf ** 2) / (np.mean(rd_cf ** 2) ** 2) / n_obs))
    dm_e.append(th_cf)
    if abs(th_cf - theta_true) <= 1.96 * se_cf:
        dm_c += 1

print(f"Non-orthogonal ML: mean={np.mean(no_e):.4f}, bias={np.mean(no_e)-theta_true:+.4f}, 95% CI coverage={no_c}/{n_trials} ({no_c/n_trials:.2%})")
print(f"5-fold DML:        mean={np.mean(dm_e):.4f}, bias={np.mean(dm_e)-theta_true:+.4f}, 95% CI coverage={dm_c}/{n_trials} ({dm_c/n_trials:.2%})")
Enter fullscreen mode Exit fullscreen mode

Dissecting the Benchmark Results

Running this benchmark yields the following exact metrics across 500 trials:

  • Non-orthogonal ML: mean=0.6069, bias=+0.1069, 95% CI coverage=103/500 (20.60%)
  • 5-fold DML: mean=0.5111, bias=+0.0111, 95% CI coverage=451/500 (90.20%)

With the true treatment effect set at theta_true = 0.50, the non-orthogonal plug-in model displays a systematic bias of +0.1069. Because standard errors shrink as sample size grows, this constant bias pushes the estimated confidence interval entirely away from the ground truth. Only 20.60% of the nominal 95% confidence intervals cover 0.50.

In contrast, 5-fold DML slashes the bias by an order of magnitude down to +0.0111, restoring coverage to 90.20% (which approaches 95% as sample size scales).

Why does DML succeed where plug-in ML fails?


Neyman Orthogonality and Double Residualization

The breakthrough of Double Machine Learning rests on two pillars: Neyman orthogonality and K-fold cross-fitting.

Instead of estimating only the outcome regression E[Y | X], DML solves an auxiliary problem: predicting the treatment from confounders, m_0(X) = E[D | X].

By the generalized Frisch-Waugh-Lovell theorem, we construct two residual vectors:

  • Outcome residual: Y_tilde = Y - l_hat(X), where l_0(X) = E[Y | X]
  • Treatment residual: D_tilde = D - m_hat(X), where m_0(X) = E[D | X]

We then identify theta_0 by regressing Y_tilde onto D_tilde.

The moment condition is orthogonal: the Gateaux derivative of the estimating equation with respect to each nuisance function (l and m) evaluated at the true parameters is exactly zero:

d/d r { E[ ( (Y - (l_0 + r × delta_l)(X)) - theta_0 × (D - (m_0 + r × delta_m)(X)) ) × (D - (m_0 + r × delta_m)(X)) ] } |_{r=0} = 0

Because the first-order derivatives vanish, the remaining nuisance error becomes a second-order product of two estimation errors:

Error term ~ (l_0(X) - l_hat(X)) × (m_0(X) - m_hat(X))

By the Cauchy-Schwarz inequality, if learner l_hat converges at rate o_P(n^(-1/4)) and learner m_hat converges at rate o_P(n^(-1/4)), their product vanishes at:

o_P(n^(-1/4)) × o_P(n^(-1/4)) = o_P(n^(-1/2))

The nuisance regularization bias disappears faster than root-N sampling variation. As a result, sqrt(n) × (theta_hat - theta_0) converges to a centered normal distribution, restoring valid asymptotic confidence intervals.


Why Cross-Fitting Is Not Optional for High-Entropy Learners

Neyman orthogonality removes first-order bias from regularized estimators, but it assumes your out-of-fold residuals are statistically independent of the weights fitted by your models.

If you compute residuals in-sample using high-capacity algorithms—such as gradient-boosted decision trees (LightGBM, XGBoost) or deep random forests—the models memorize idiosyncratic sample variation. In-sample residuals correlate directly with the learner's estimation errors.

This correlation introduces Donsker class violations and stochastic equicontinuity breakdown: the empirical process term no longer vanishes at root-N speed.

Cross-fitting solves this problem systematically:

  • Partition the dataset into K disjoint folds (typically K = 5 or K = 10).
  • For each fold k, train l_hat and m_hat exclusively on the remaining K - 1 folds.
  • Generate out-of-sample predictions for fold k using the models trained outside fold k.
  • Combine the out-of-fold residual vectors across all N samples and compute the orthogonal score estimator.

Cross-fitting guarantees that every residual used to compute theta_hat was generated by a model that never saw that specific data point during training.


Production Recipes: DoubleML, EconML, and grf

You do not need to implement cross-fitted orthogonal moments from scratch for production systems. Established open-source libraries implement these exact estimators.

1. Python DoubleML (v0.11.4)

For continuous treatments or linear additive structures, use DoubleMLPLR (Partially Linear Regression) with score='partialling out'. You supply two scikit-learn compatible learners: ml_l for outcome regression and ml_m for treatment regression:

import doubleml as dml
from sklearn.ensemble import RandomForestRegressor

# Wrap features, treatment, and outcome in DoubleMLData
obj_dml_data = dml.DoubleMLData.from_arrays(x=X, y=Y, d=D)

# Initialize base learners
ml_l = RandomForestRegressor(n_estimators=100, max_depth=6, random_state=42)
ml_m = RandomForestRegressor(n_estimators=100, max_depth=6, random_state=42)

# Fit cross-fitted partially linear regression
dml_plr = dml.DoubleMLPLR(
    obj_dml_data,
    ml_l=ml_l,
    ml_m=ml_m,
    n_folds=5,
    score='partialling out'
)
dml_plr.fit()
print(dml_plr.summary)
Enter fullscreen mode Exit fullscreen mode

For binary treatment D in {0, 1} with potential treatment-confounder interactions, switch to DoubleMLIRM (Interactive Regression Model). Note the key parameter distinction: whereas DoubleMLPLR takes ml_l to estimate E[Y | X], DoubleMLIRM requires ml_g (passing ml_l raises TypeError: DoubleMLIRM.__init__() got an unexpected keyword argument 'ml_l'). In DoubleMLIRM, ml_g models the interactive response surface g_0(D, X) = E[Y | D, X] separately across binary treatment arms D in {0, 1}, while ml_m must be a calibrated probabilistic classifier predicting propensity scores P(D = 1 | X):

from lightgbm import LGBMClassifier, LGBMRegressor

ml_g = LGBMRegressor(n_estimators=100, max_depth=6, random_state=42)
ml_m = LGBMClassifier(n_estimators=100, max_depth=6, random_state=42)

dml_irm = dml.DoubleMLIRM(
    obj_dml_data,
    ml_g=ml_g,
    ml_m=ml_m,
    n_folds=5,
    score='ATE'
)
dml_irm.fit()
print(dml_irm.summary)
Enter fullscreen mode Exit fullscreen mode

2. EconML (v0.17.1) and Causal Forests

When treatment effects are heterogeneous (theta(X) varies across subgroups), standard partially linear DML yields only an average effect. Microsoft's EconML provides CausalForestDML, combining DML residualization with generalized random forests:

from econml.dml import CausalForestDML
from sklearn.ensemble import GradientBoostingRegressor

cf_dml = CausalForestDML(
    model_y=GradientBoostingRegressor(n_estimators=100, max_depth=4),
    model_t=GradientBoostingRegressor(n_estimators=100, max_depth=4),
    n_estimators=1000,
    subforest_size=4,
    cv=5,
    random_state=42
)
cf_dml.fit(Y, D, X=X_features)
cate_preds = cf_dml.effect(X_features)
cate_intervals = cf_dml.effect_interval(X_features, alpha=0.05)
Enter fullscreen mode Exit fullscreen mode

3. R grf (v2.6.1) Calibration Testing

If your team works in R, Susan Athey and Stefan Wager's grf package remains a benchmark. When fitting a causal_forest, pass tune.parameters = "all" to tune honesty, pruning, and sub-sampling parameters, and run test_calibration() to evaluate whether detected effect heterogeneity reflects genuine signal or fitting artifacts:

library(grf)

# Fit cross-fitted causal forest with automated parameter tuning
c_forest <- causal_forest(
  X = X_mat,
  Y = Y_vec,
  W = D_vec,
  tune.parameters = "all",
  num.trees = 2000
)

# Test calibration of mean effect and heterogeneity
test_calibration(c_forest)
Enter fullscreen mode Exit fullscreen mode

The output of test_calibration() provides two diagnostic coefficients:

  • The mean forest prediction coefficient should be close to 1. If it deviates significantly, the overall treatment effect scale is miscalibrated.
  • The differential forest prediction coefficient measures whether predicted heterogeneity aligns with observed outcome variance. A p-value < 0.05 confirms that subgroup effect differences are statistically meaningful rather than random noise.

Summary Checklist for Applied Causal Inference

Before reporting treatment effects or confidence intervals from an observational model, verify these three conditions:

  • Did you orthogonalize the score? Never read off coefficients from an un-orthogonalized model fitted to [D, X]. Use double residualization so nuisance errors shrink as a second-order product.
  • Did you cross-fit? Ensure out-of-fold predictions evaluate on data points excluded during learner training to prevent in-sample noise overfitting.
  • Are nuisance models sufficiently convergent? Verify that both outcome and treatment learners achieve o_P(n^(-1/4)) convergence so their product vanishes faster than n^(-1/2).

Top comments (0)