Double machine learning
Use flexible models to remove confounding from both treatment and outcome, and keep valid inference through cross-fitting.
What runs in CodeSplash
- Double/debiased machine learning (DoubleML) Verified in Python and R
You will be able to
- Explain partialling out as residual-on-residual regression
- Say why plugging in a machine-learning model directly gives biased inference
- Choose between partially linear and interactive models
Read first
Regress residuals on residuals
ReadRegression can be read this way: remove from what the covariates predict, remove from what the covariates predict, and regress what's left.
Double machine learningDouble machine learningUses flexible models to remove confounding from treatment and outcome, with cross-fitting to keep inference valid. does the same with any flexible model:
Why not fit one big model?
ReadRegularization shrinks coefficients on purpose, and that shrinkage biases the treatment's coefficient too. Its confidence interval then doesn't cover the truth as it should.
Two fixes make inference work again:
- Orthogonal scores: small errors in the two models cancel to first order.
- Cross-fitting: each row's residuals come from models trained on the other rows.
Will the two models agree?
PredictPredict first
On simulated data, compare the partially linear model with the interactive model, which lets the effect vary. How close will the estimates be?
Reveal
1.99 and 1.90. They target slightly different things: the interactive model estimates an average of varying effects, and the partially linear one assumes a single effect. Agreement here suggests that assumption isn't doing much harm.
Read a run
In the appDouble machine learning (partially linear model, partialling out score, linear/logistic regression nuisances cross-fitted on 5 folds) estimates the effect of treated = true vs false on outcome as 1.99 (95% CI [1.85, 2.14], p < .001).
- θ̂
- 1.992
- 95% CI
- [1.849, 2.136]
- p
- < .001
Assumptions
- No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.
DoubleML estimate
| Term | θ̂ | SE | z | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| treated | 1.992 | 0.0733 | 27.165 | < .001 | 1.849 | 2.136 |
Partially linear model, score 'partialling out'; 5-fold cross-fitting with splits from seed 42.
Nuisance models (out of fold)
| Model | RMSE |
|---|---|
| Outcome (outcome) | 1.447 |
| Treatment (treated) | 0.4586 |
- 15 of 1200 rows were left out because a value was missing.
- Same DoubleML sample splits in Python and R (portable Wichmann–Hill stream).
The exact R script · R R version 4.5.1 (2025-06-13)
# Double/debiased machine learning (DoubleML)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.dml 1.0.1 · spec 1170f1d86a11a842
# Dataset: c2_obs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages({
library(DoubleML)
library(mlr3)
library(mlr3learners)
})
lgr::get_logger("mlr3")$set_threshold("warn")
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c2_obs.parquet", col_select = c("outcome", "treated", "x1", "x2", "segment", "member", "income (k)")))
n_input <- nrow(df)
df[["treated"]] <- factor(df[["treated"]], levels = c("false", "true")) # stored level order
df[["segment"]] <- factor(df[["segment"]], levels = c("a", "b", "c")) # stored level order
df[["member"]] <- factor(df[["member"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("outcome", "treated", "x1", "x2", "segment", "member", "income (k)")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("outcome", "treated", "x1", "x2", "segment", "member", "income (k)")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treated"
outcome <- "outcome"
covariates <- c("x1", "x2", "segment", "member", "income (k)")
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python gets the same sample splits
model_kind <- "plr" # plr | irm
learner <- "linear" # linear | xgboost
k <- as.integer(5)
trimming <- 0.01
if (is.factor(df[[treatment]])) {
tr_info <- cs_causal_treatment(df, treatment, NULL)
t <- tr_info$t
treated_level <- tr_info$treated
control_level <- tr_info$control
contrast_text <- sprintf("%s = %s vs %s", treatment, treated_level, control_level)
} else {
if (model_kind == "irm") stop("The interactive model needs a binary treatment; use the partially linear model for a numeric treatment.")
t <- as.numeric(df[[treatment]])
treated_level <- NULL
control_level <- NULL
contrast_text <- sprintf("one unit of %s", treatment)
}
y_info <- cs_causal_outcome(df, outcome)
y <- y_info$y
event_level <- y_info$event
des <- cs_causal_design(df, covariates)
X <- des$X
cs_causal_check_rank(X, des$labels)
n <- length(y)
outcome_text <- if (!is.null(event_level)) sprintf("%s = %s", outcome, event_level) else outcome
score <- if (model_kind == "plr") "partialling out" else "ATE"
# %% Learners (deterministic: same predictions as the Python twins under the same splits)
if (learner == "xgboost") {
xgb <- list(nrounds = as.integer(100), eta = 0.1, max_depth = as.integer(3),
nthread = 1L, verbose = 0L, seed = seed)
reg <- function() do.call(lrn, c(list("regr.xgboost"), xgb))
clf <- function() do.call(lrn, c(list("classif.xgboost", predict_type = "prob"), xgb))
} else {
reg <- function() lrn("regr.lm")
clf <- function() lrn("classif.log_reg", predict_type = "prob", epsilon = 1e-12, maxit = 1000)
}
Xn <- X
colnames(Xn) <- paste0("X", seq_len(ncol(X)))
data <- data.frame(Xn, y = y, d = t)
dml_data <- DoubleMLData$new(data, y_col = "y", d_cols = "d", x_cols = colnames(Xn))
splits <- cs_causal_dml_splits(n, k, seed)
if (model_kind == "plr") {
obj <- if (score == "IV-type") DoubleMLPLR$new(dml_data, reg(), reg(), reg(), n_folds = k, score = score, draw_sample_splitting = FALSE)
else DoubleMLPLR$new(dml_data, reg(), reg(), n_folds = k, score = score, draw_sample_splitting = FALSE)
} else {
obj <- DoubleMLIRM$new(dml_data, reg(), clf(), n_folds = k, score = score, trimming_rule = "truncate", trimming_threshold = trimming,
draw_sample_splitting = FALSE)
}
obj$set_sample_splitting(splits)
obj$fit(store_predictions = TRUE)
est <- unname(obj$coef[1])
se <- unname(obj$se[1])
zc <- stats::qnorm(1 - (1 - conf) / 2)
z <- est / se
p_value <- 2 * stats::pnorm(abs(z), lower.tail = FALSE)
ci_low <- est - zc * se
ci_high <- est + zc * se
pred <- obj$predictions
if (model_kind == "plr") {
rmse_y <- sqrt(mean((y - pred$ml_l[, 1, 1])^2))
} else {
g <- t * pred$ml_g1[, 1, 1] + (1 - t) * pred$ml_g0[, 1, 1]
rmse_y <- sqrt(mean((y - g)^2))
}
m_hat <- pred$ml_m[, 1, 1]
if (model_kind == "irm") m_hat <- pmin(pmax(m_hat, trimming), 1 - trimming) # the packages store trimmed vs raw scores
rmse_d <- sqrt(mean((t - m_hat)^2))
# %% Result
estimand <- if (model_kind == "plr") "ATE (partially linear)" else if (score == "ATTE") "ATT" else "ATE"
mname <- if (model_kind == "plr") "partially linear model" else "interactive regression model"
lname <- if (learner == "xgboost") "XGBoost" else "linear/logistic regression"
effect_label <- sprintf("Effect of %s on %s (%s, double machine learning)", contrast_text, outcome_text, estimand)
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("Double machine learning (%s, %s score, %s nuisances cross-fitted on %d folds) estimates the effect of %s on %s as %s (%s CI [%s, %s], %s).",
mname, score, lname, k, contrast_text, outcome_text, cs_fmt_num(est), pct, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p_value))
checks <- list(cs_causal_no_confounding_check())
if (model_kind == "irm") checks <- c(list(cs_causal_overlap_check(m_hat, t)), checks)
values <- list(estimate = est, se = se, ci_low = ci_low, ci_high = ci_high, z = z, p_value = p_value, n = n, estimand = estimand,
effect_label = effect_label, claim_level_max = "L2", model = model_kind, score = score, learner = learner, folds = k,
rmse_outcome = rmse_y, rmse_treatment = rmse_d, treated_level = treated_level, control_level = control_level)
cs_publish(list(
method = "causal.dml",
methodVersion = "1.0.1",
title = sprintf("Double machine learning (%s, %s)", toupper(model_kind), estimand),
engine = do.call(cs_engine_info, as.list(c("DoubleML", "mlr3", "mlr3learners", if (learner == "xgboost") "xgboost"))),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = "θ̂", value = est),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p_value, format = "p")),
tables = list(
list(key = "estimate", title = "DoubleML estimate", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "θ̂", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = list(list(term = treatment, coef = est, se = se, z = z, p = p_value, ci_low = ci_low, ci_high = ci_high)),
note = sprintf("%s%s, score '%s'; %d-fold cross-fitting with splits from seed %d.", toupper(substr(mname, 1, 1)), substr(mname, 2, nchar(mname)), score, k, seed)),
list(key = "nuisance", title = "Nuisance models (out of fold)", columns = list(
list(key = "model", label = "Model", type = "string"), list(key = "rmse", label = "RMSE", type = "number")),
rows = list(list(model = sprintf("Outcome (%s)", outcome), rmse = rmse_y), list(model = sprintf("Treatment (%s)", treatment), rmse = rmse_d)))),
assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
checks = checks,
warnings = warnings,
notes = list("Same DoubleML sample splits in Python and R (portable Wichmann–Hill stream)."),
values = values
))
Double machine learning (partially linear model, partialling out score, linear/logistic regression nuisances cross-fitted on 5 folds) estimates the effect of treated = true vs false on outcome as 1.99 (95% CI [1.85, 2.14], p < .001).
- θ̂
- 1.992
- 95% CI
- [1.849, 2.136]
- p
- < .001
Assumptions
- No unmeasured confounding — The estimate is causal only if the covariates include every common cause of treatment and outcome; check how strong an omitted confounder would have to be with the sensitivity analysis.
DoubleML estimate
| Term | θ̂ | SE | z | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| treated | 1.992 | 0.0733 | 27.165 | < .001 | 1.849 | 2.136 |
Partially linear model, score 'partialling out'; 5-fold cross-fitting with splits from seed 42.
Nuisance models (out of fold)
| Model | RMSE |
|---|---|
| Outcome (outcome) | 1.447 |
| Treatment (treated) | 0.4586 |
- 15 of 1200 rows were left out because a value was missing.
- Same DoubleML sample splits in Python and R (portable Wichmann–Hill stream).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Double/debiased machine learning (DoubleML)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.dml 1.0.1 · spec 1170f1d86a11a842
# Dataset: c2_obs (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import warnings as _warnings
import numpy as np
import pandas as pd
import doubleml as dml
from scipy import stats
from sklearn.linear_model import LinearRegression, LogisticRegression
import codesplash as cs
from codesplash.causal import dml as csdml
from codesplash.causal import weighting as csw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c2_obs.parquet", columns=["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"])
n_input = len(df)
df["treated"] = pd.Categorical(df["treated"], categories=["false", "true"]) # stored level order
df["segment"] = pd.Categorical(df["segment"], categories=["a", "b", "c"]) # stored level order
df["member"] = pd.Categorical(df["member"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"]) # listwise deletion over the analysis columns
df["treated"] = df["treated"].cat.remove_unused_categories()
df["segment"] = df["segment"].cat.remove_unused_categories()
df["member"] = df["member"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["outcome", "treated", "x1", "x2", "segment", "member", "income (k)"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treated"
outcome = "outcome"
covariates = ["x1", "x2", "segment", "member", "income (k)"]
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R gets the same sample splits
model_kind = "plr" # plr | irm
learner = "linear" # linear | xgboost
k = int(5)
trimming = 0.01
if isinstance(df[treatment].dtype, pd.CategoricalDtype):
t, treated_level, control_level = csw.treatment_indicator(df, treatment, None)
contrast_text = f"{treatment} = {treated_level} vs {control_level}"
else:
if model_kind == "irm":
raise ValueError("The interactive model needs a binary treatment; use the partially linear model for a numeric treatment.")
t = df[treatment].to_numpy(dtype=float)
treated_level = control_level = None
contrast_text = f"one unit of {treatment}"
y, event_level = csw.outcome_vector(df, outcome)
X, labels, binary, sources = csw.covariate_matrix(df, covariates)
csw.check_rank(X, labels)
n = len(y)
outcome_text = f"{outcome} = {event_level}" if event_level is not None else outcome
score = "partialling out" if model_kind == "plr" else "ATE"
# %% Learners (deterministic: same predictions as the R twins under the same splits)
if learner == "xgboost":
from xgboost import XGBClassifier, XGBRegressor
xgb = dict(n_estimators=int(100), learning_rate=0.1, max_depth=int(3),
n_jobs=1, random_state=seed, tree_method="hist")
reg = lambda: XGBRegressor(**xgb) # noqa: E731 — = mlr3 lrn("regr.xgboost", nrounds, eta, max_depth, nthread = 1)
clf = lambda: XGBClassifier(**xgb) # noqa: E731
else:
reg = LinearRegression # = mlr3 lrn("regr.lm")
clf = lambda: LogisticRegression(C=np.inf, solver="newton-cholesky", tol=1e-12, max_iter=1000) # noqa: E731 — = lrn("classif.log_reg")
names = [f"X{j + 1}" for j in range(X.shape[1])]
data = pd.DataFrame(X, columns=names)
data["y"] = y
data["d"] = t
dml_data = dml.DoubleMLData(data, y_col="y", d_cols="d", x_cols=names)
splits = csdml.sample_splits(n, k, seed)
with _warnings.catch_warnings():
_warnings.simplefilter("ignore")
if model_kind == "plr":
obj = dml.DoubleMLPLR(dml_data, reg(), reg(), ml_g=reg() if score == "IV-type" else None, n_folds=k, score=score, draw_sample_splitting=False)
else:
obj = dml.DoubleMLIRM(dml_data, reg(), clf(), n_folds=k, score=score, trimming_rule="truncate", trimming_threshold=trimming, draw_sample_splitting=False)
obj.set_sample_splitting(all_smpls=splits)
obj.fit(store_predictions=True)
est, se = float(obj.coef[0]), float(obj.se[0])
zc = stats.norm.ppf(1 - (1 - conf) / 2)
z = est / se
p_value = float(2 * stats.norm.sf(abs(z)))
ci_low, ci_high = est - zc * se, est + zc * se
pred = obj.predictions
if model_kind == "plr":
rmse_y = float(np.sqrt(np.mean((y - pred["ml_l"][:, 0, 0]) ** 2)))
else:
g = t * pred["ml_g1"][:, 0, 0] + (1 - t) * pred["ml_g0"][:, 0, 0]
rmse_y = float(np.sqrt(np.mean((y - g) ** 2)))
m_hat = pred["ml_m"][:, 0, 0]
if model_kind == "irm":
m_hat = np.clip(m_hat, trimming, 1 - trimming) # the packages store trimmed vs raw scores; compare the trimmed ones
rmse_d = float(np.sqrt(np.mean((t - m_hat) ** 2)))
# %% Result
estimand = {"plr": "ATE (partially linear)", "ATE": "ATE", "ATTE": "ATT"}[model_kind if model_kind == "plr" else score]
mname = "partially linear model" if model_kind == "plr" else "interactive regression model"
lname = "XGBoost" if learner == "xgboost" else "linear/logistic regression"
effect_label = f"Effect of {contrast_text} on {outcome_text} ({estimand}, double machine learning)"
pct = f"{conf:.0%}"
summary = (
f"Double machine learning ({mname}, {score} score, {lname} nuisances cross-fitted on {k} folds) estimates the effect of "
f"{contrast_text} on {outcome_text} as {cs.fmt_num(est)} ({pct} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p_value)})."
)
checks = [csw.no_confounding_check()]
if model_kind == "irm":
checks.insert(0, csw.overlap_check(m_hat, t))
values = {
"estimate": est, "se": se, "ci_low": ci_low, "ci_high": ci_high, "z": z, "p_value": p_value, "n": n, "estimand": estimand,
"effect_label": effect_label, "claim_level_max": "L2", "model": model_kind, "score": score, "learner": learner, "folds": k,
"rmse_outcome": rmse_y, "rmse_treatment": rmse_d, "treated_level": treated_level, "control_level": control_level,
}
cs.publish({
"method": "causal.dml",
"methodVersion": "1.0.1",
"title": f"Double machine learning ({model_kind.upper()}, {estimand})",
"engine": cs.engine_info("doubleml", "scikit-learn", *(["xgboost"] if learner == "xgboost" else []), "numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": "θ̂", "value": est},
{"key": "ci", "label": f"{pct} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p_value, "format": "p"},
],
"tables": [
{"key": "estimate", "title": "DoubleML estimate", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "θ̂", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": [{"term": treatment, "coef": est, "se": se, "z": z, "p": p_value, "ci_low": ci_low, "ci_high": ci_high}],
"note": f"{mname.capitalize()}, score {score!r}; {k}-fold cross-fitting with splits from seed {seed}."},
{"key": "nuisance", "title": "Nuisance models (out of fold)", "columns": [
{"key": "model", "label": "Model", "type": "string"}, {"key": "rmse", "label": "RMSE", "type": "number"}],
"rows": [{"model": f"Outcome ({outcome})", "rmse": rmse_y}, {"model": f"Treatment ({treatment})", "rmse": rmse_d}]},
],
"assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
"checks": checks,
"warnings": warnings,
"notes": ["Same DoubleML sample splits in Python and R (portable Wichmann–Hill stream)."],
"values": values,
})
Check the two nuisance fits: the outcome's error is 1.45 and the treatment's is 0.459, across 5 folds. Poor nuisance models leave confounding in the residuals, and the interval won't warn you.
On the LaLonde data, with boosted trees, the estimate is 789, with p = .310. Flexible learners can't rescue a small sample with poor overlap.
Check your understanding
CheckpointCheck yourself
Why cross-fit?
Show the answer
Answer: b
Overfit models make in-sample residuals too small and correlated with the noise. Out-of-fold predictions avoid that.
Check yourself
You use DML with 200 covariates. Have you solved confounding?
Show the answer
Answer: b
DML handles high-dimensional adjustment, but it doesn't choose what to adjust for. You still need your DAG.
Check yourself
The partially linear estimate is 1.992 with a standard error of 0.073. What's the lower end of its 95% interval? Use 1.96, and give two decimals.
Show the answer
Answer: 1.84854720592015
Estimate minus 1.96 standard errors. The interval covers sampling error only: it assumes you've measured the confounders.
Try it
In the appIn the Causal studio, choose double machine learning on the Estimate step. Start with linear learners, since they're fast and easy to check, then see whether boosted trees change the answer. A large change suggests nonlinear confounding.
Method guide · causal.dmlDouble/debiased machine learning (DoubleML)What is the treatment effect when flexible machine-learning models adjust for the confounders?Recap
Recap- DML regresses residuals on residuals, with flexible models removing what covariates predict.
- Orthogonal scores and cross-fitting keep the inference valid.
- It adjusts for what you give it: choosing the covariates is still your job.
Concepts in this lesson