Custom code: DML and TMLE

Cross-fit \(\hat\alpha\) from rieszreg plus a cross-fit outcome regression \(\hat\mu\) are the two ingredients of a one-step / DML / TMLE estimator for any linear-functional estimand. This page builds both estimators on the Lalonde NSW dataset in ~50 lines.

Data: Lalonde NSW (treated) + CPS (controls)

The Dehejia-Wahba dataset: NSW-treated job-trainees vs CPS observational controls, outcome re78 (1978 earnings). The standard covariates are age, education, race, marital status, schooling, and pre-period earnings.

The data come from the causaldata package. It is in the workspace’s docs dependency group, so install with uv sync --all-packages --all-extras --all-groups (see Install).

import numpy as np, pandas as pd
from causaldata import nsw_mixtape, cps_mixtape

COVARIATES = ["age", "educ", "black", "hisp", "marr", "nodegree", "re74", "re75"]

treated  = nsw_mixtape.load_pandas().data
treated  = treated[treated["treat"] == 1].copy()
controls = cps_mixtape.load_pandas().data
df = pd.concat([treated, controls], ignore_index=True)
df = df.rename(columns={"treat": "a"})
df["y"] = df["re78"]
df = df[["a", "y"] + COVARIATES].copy()
df["a"] = df["a"].astype(float)
print(f"n = {len(df)}  ({(df['a']==1).sum()} treated, {(df['a']==0).sum()} control)")
n = 16177  (185 treated, 15992 control)
library(reticulate)
cd_py <- import("causaldata")
COVARIATES <- c("age", "educ", "black", "hisp", "marr", "nodegree", "re74", "re75")

# Convert column by column; works with every pandas version.
load_cd  <- function(ds) as.data.frame(ds$load_pandas()$data$to_dict("list"))
treated  <- load_cd(cd_py$nsw_mixtape)
treated  <- treated[treated$treat == 1, ]
controls <- load_cd(cd_py$cps_mixtape)
df <- rbind(treated, controls)
df$a <- as.numeric(df$treat)
df$y <- df$re78
df <- df[, c("a", "y", COVARIATES)]
cat(sprintf("n = %d  (%d treated, %d control)\n",
            nrow(df), sum(df$a == 1), sum(df$a == 0)))
n = 16177  (185 treated, 15992 control)

Cross-fit nuisances

Split the rows into 5 folds. For each fold, fit the outcome model \(\hat\mu\) and the Riesz learner \(\hat\alpha\) on the other four folds. Then predict on the held-out fold at the observed treatment and at \(A = 1\) and \(A = 0\). Every prediction used below comes from models that never saw that row.

import xgboost as xgb
from sklearn.base import clone
from sklearn.model_selection import KFold
from rieszreg import ATE
from rieszboost import RieszBooster

Z  = df[["a"] + COVARIATES]
y  = df["y"].to_numpy(dtype=float)
Z1 = Z.assign(a=1.0)   # everyone treated
Z0 = Z.assign(a=0.0)   # everyone untreated

outcome_model = xgb.XGBRegressor(
    objective="reg:squarederror", learning_rate=0.05,
    max_depth=4, reg_lambda=1.0, n_estimators=300,
    random_state=0, verbosity=0,
)
booster = RieszBooster(
    estimand=ATE(treatment="a", covariates=tuple(COVARIATES)),
    n_estimators=2000, early_stopping_rounds=20, validation_fraction=0.2,
    learning_rate=0.05, max_depth=3, reg_lambda=10.0, random_state=0,
)

n = len(df)
mu_obs, mu1, mu0 = np.zeros(n), np.zeros(n), np.zeros(n)
alpha_hat, alpha_1, alpha_0 = np.zeros(n), np.zeros(n), np.zeros(n)
for train, test in KFold(n_splits=5, shuffle=True, random_state=0).split(Z):
    mu_k = clone(outcome_model).fit(Z.iloc[train], y[train])
    mu_obs[test] = mu_k.predict(Z.iloc[test])
    mu1[test]    = mu_k.predict(Z1.iloc[test])
    mu0[test]    = mu_k.predict(Z0.iloc[test])

    alpha_k = clone(booster).fit(Z.iloc[train])
    alpha_hat[test] = alpha_k.predict(Z.iloc[test])
    alpha_1[test]   = alpha_k.predict(Z1.iloc[test])
    alpha_0[test]   = alpha_k.predict(Z0.iloc[test])
library(xgboost)
suppressPackageStartupMessages(library(rsample))
set.seed(0)

X  <- as.matrix(df[, c("a", COVARIATES)])
y  <- df$y
X1 <- X; X1[, "a"] <- 1   # everyone treated
X0 <- X; X0[, "a"] <- 0   # everyone untreated
df_a1 <- df; df_a1$a <- 1
df_a0 <- df; df_a0$a <- 0

n <- nrow(df)
mu_obs <- mu1 <- mu0 <- numeric(n)
alpha_hat <- alpha_1 <- alpha_0 <- numeric(n)
for (split in vfold_cv(df, v = 5)$splits) {
  test  <- complement(split)
  train <- setdiff(seq_len(n), test)

  mu_k <- xgb.train(
    params = list(objective = "reg:squarederror", eta = 0.05,
                  max_depth = 4, lambda = 1.0, verbosity = 0),
    data = xgb.DMatrix(X[train, , drop = FALSE], label = y[train]),
    nrounds = 300
  )
  mu_obs[test] <- predict(mu_k, X[test, , drop = FALSE])
  mu1[test]    <- predict(mu_k, X1[test, , drop = FALSE])
  mu0[test]    <- predict(mu_k, X0[test, , drop = FALSE])

  alpha_k <- RieszBooster$new(
    estimand = ATE(treatment = "a", covariates = COVARIATES),
    n_estimators = 2000, early_stopping_rounds = 20, validation_fraction = 0.2,
    learning_rate = 0.05, max_depth = 3, reg_lambda = 10.0
  )
  alpha_k$fit(df[train, ])
  alpha_hat[test] <- alpha_k$predict(df[test, ])
  alpha_1[test]   <- alpha_k$predict(df_a1[test, ])
  alpha_0[test]   <- alpha_k$predict(df_a0[test, ])
}

DML / one-step

The efficient influence function for ATE is \(\mathrm{IF}(O) = m(\hat\mu)(Z) + \hat\alpha(Z)\,(Y - \hat\mu(Z))\), with \(m(\hat\mu)(Z) = \hat\mu(1, X) - \hat\mu(0, X)\). Average it for \(\hat\psi\); its sample variance gives the SE.

eif = (mu1 - mu0) + alpha_hat * (y - mu_obs)
psi = float(eif.mean())
se  = float(np.sqrt(np.var(eif, ddof=1) / len(eif)))
ci  = (psi - 1.96 * se, psi + 1.96 * se)
print(f"ψ̂_ATE  = {psi:.2f}")
ψ̂_ATE  = -2416.43
print(f"SE     = {se:.2f}")
SE     = 219.69
print(f"95% CI = [{ci[0]:.2f}, {ci[1]:.2f}]")
95% CI = [-2847.01, -1985.84]
eif <- (mu1 - mu0) + alpha_hat * (y - mu_obs)
psi <- mean(eif)
se  <- sqrt(var(eif) / length(eif))
ci  <- c(psi - 1.96 * se, psi + 1.96 * se)
cat(sprintf("psi_ATE = %.2f\nSE      = %.2f\n95%% CI  = [%.2f, %.2f]\n",
            psi, se, ci[1], ci[2]))
psi_ATE = -2139.10
SE      = 230.09
95% CI  = [-2590.08, -1688.13]

The experimental NSW-only ATE benchmark is roughly $1,794 (Dehejia-Wahba 1999); the NSW-treated vs CPS-controls comparison drifts further from that benchmark when covariates fail to absorb the experimental-vs-observational gap.

TMLE

TMLE solves the same EIF=0 estimating equation as one-step but does it by targeting \(\hat\mu\): fit a one-parameter fluctuation \(\mu^\star(\cdot) = \hat\mu(\cdot) + \epsilon \hat\alpha(\cdot)\) on a “clever covariate” \(\hat\alpha\) to drive the empirical mean of \(\hat\alpha(O)(Y - \mu^\star(O))\) to zero, then take the plug-in \(\hat\psi = (1/n) \sum \mu^\star(1, X) - \mu^\star(0, X)\). For continuous \(Y\) the targeting is a single linear regression of the outcome residual on \(\hat\alpha\).

The targeting step also needs \(\hat\alpha\) at \(A=1\) and \(A=0\). The cross-fitting loop above already produced them (alpha_1, alpha_0).

# Fluctuation: ε from OLS of (y - μ̂) on α̂, no intercept.
eps = float(np.dot(alpha_hat, y - mu_obs) / np.dot(alpha_hat, alpha_hat))

# Targeted counterfactual regressions and observed-row regression.
mu1_star    = mu1   + eps * alpha_1
mu0_star    = mu0   + eps * alpha_0
mu_obs_star = mu_obs + eps * alpha_hat

psi_tmle = float((mu1_star - mu0_star).mean())
eif_tmle = (mu1_star - mu0_star - psi_tmle) + alpha_hat * (y - mu_obs_star)
se_tmle  = float(np.sqrt(np.var(eif_tmle, ddof=1) / len(eif_tmle)))
ci_tmle  = (psi_tmle - 1.96 * se_tmle, psi_tmle + 1.96 * se_tmle)
print(f"ψ̂_TMLE = {psi_tmle:.2f}")
ψ̂_TMLE = -2539.97
print(f"SE     = {se_tmle:.2f}")
SE     = 219.48
print(f"95% CI = [{ci_tmle[0]:.2f}, {ci_tmle[1]:.2f}]")
95% CI = [-2970.15, -2109.79]
eps          <- sum(alpha_hat * (y - mu_obs)) / sum(alpha_hat^2)
mu1_star     <- mu1   + eps * alpha_1
mu0_star     <- mu0   + eps * alpha_0
mu_obs_star  <- mu_obs + eps * alpha_hat

psi_tmle <- mean(mu1_star - mu0_star)
eif_tmle <- (mu1_star - mu0_star - psi_tmle) + alpha_hat * (y - mu_obs_star)
se_tmle  <- sqrt(var(eif_tmle) / length(eif_tmle))
ci_tmle  <- c(psi_tmle - 1.96 * se_tmle, psi_tmle + 1.96 * se_tmle)
cat(sprintf("psi_TMLE = %.2f\nSE       = %.2f\n95%% CI   = [%.2f, %.2f]\n",
            psi_tmle, se_tmle, ci_tmle[1], ci_tmle[2]))
psi_TMLE = -2016.33
SE       = 230.25
95% CI   = [-2467.63, -1565.03]

For continuous \(Y\), one-step and TMLE point estimates coincide to \(O_p(n^{-1})\). TMLE’s plug-in is a parameter of an updated regression, which preserves bounds (e.g. probabilities stay in \([0, 1]\) for binary outcomes via the logistic-fluctuation variant — replace the OLS targeting step with a logistic-link single-covariate GLM on the bounded outcome).

Other estimands

The pattern generalizes verbatim. Swap the estimand factory and the \(m(\hat\mu)(Z)\) formula:

Estimand \(m(\hat\mu)(Z)\) Riesz factory
ATT \(A(\hat\mu(1, X) - \hat\mu(0, X))\), then divide by \(\hat{P}(A=1)\) ATT(...)
TSM at \(a^\star\) \(\hat\mu(a^\star, X)\) TSM(level=a_star)
Additive shift \(\delta\) \(\hat\mu(A + \delta, X) - \hat\mu(A, X)\) AdditiveShift(delta)

Worked examples for each: rieszboost/examples/ (tsm.py, nhefs_shift.py, lee_schuler/binary_dgp.py).

See also