Skip to content

Machine learning for causal effects: double ML and honest causal forests

Double ML uses flexible models only for nuisance parts, with cross-fitting; honest causal forests estimate how effects vary. What orthogonality and honesty protect against, and what no model can fix.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Write the partialling-out DML estimator and explain cross-fitting
  • Say what Neyman orthogonality protects against and what it doesn't
  • Describe how a causal forest's local weights estimate a conditional effect, and what honesty adds
  • Separate average effects, conditional predictions and searched-for subgroups when reporting

Read first

01

Prediction tools, causal questions

Read

Flexible learners are good at predicting outcomes, but plugging one into a causal question goes wrong in quiet ways: regularization shrinks the treatment coefficient, and overfitting leaks the outcome into the adjustment. Both methods here use machine learning only for the nuisance parts, the pieces you need but don't care about, and protect the target from their errors.

Neither creates identification. Unconfoundedness (all common causes measured), overlap and no interference must be argued from the design, before any model is fit.

02

Double ML: residuals on residuals

Read

In the partially linear model, predict the outcome ℓ(x)=E[Y∣X]\ell(x)=\mathbb E[Y\mid X] and the treatment m(x)=E[D∣X]m(x)=\mathbb E[D\mid X] with any learners, fit out of fold (cross-fitting): each row's predictions come from models trained on the other folds. Then regress residual on residual:

Y~i=Yi−ℓ^−k(i)(Xi),D~i=Di−m^−k(i)(Xi),θ^=∑iD~iY~i∑iD~i2.\tilde Y_i=Y_i-\hat\ell_{-k(i)}(X_i),\quad \tilde D_i=D_i-\hat m_{-k(i)}(X_i),\quad \hat\theta=\frac{\sum_i\tilde D_i\tilde Y_i}{\sum_i\tilde D_i^2}.

In the reference's simulation the estimate is 1.59 with standard error 0.0532; the true effect was 1.50.

03

Why the residual trick works

Read

The partialling-out score is Neyman orthogonal: small errors in ℓ^\hat\ell or m^\hat m change θ^\hat\theta only to second order, through the product of the two errors. So two moderately good learners can still give n\sqrt n-consistent estimates with valid intervals. Cross-fitting removes the overfitting bias that comes from predicting rows the learner trained on.

Double machine learning (PLR, ATE (partially linear))Recorded · Python and R agreeRecorded 2026-11-17 · 18 values compared
R

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θ̂SEzp95% CI low95% CI high
treated1.9920.073327.165< .0011.8492.136

Partially linear model, score 'partialling out'; 5-fold cross-fitting with splits from seed 42.

Nuisance models (out of fold)

ModelRMSE
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
))
Python

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θ̂SEzp95% CI low95% CI high
treated1.9920.073327.165< .0011.8492.136

Partially linear model, score 'partialling out'; 5-fold cross-fitting with splits from seed 42.

Nuisance models (out of fold)

ModelRMSE
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,
})

Change the model and you change the estimand: the interactive model's ATE on the same data was 1.90 against 1.99 for the partially linear one, which weights units differently.

04

A perfect nuisance fit

Predict

Predict first

Your outcome and treatment models predict superbly on held-out folds. But a strong common cause of treatment and outcome was never measured. Is the DML estimate unbiased?

Yes, the learners are excellentNo, an unmeasured common cause biases it anyway
Reveal

No. Orthogonality protects against estimation error in the nuisance functions, not against variables that aren't there. Omitted confounders, adjusting for something the treatment caused, or weak overlap bias every version of DML. Good nuisance fit doesn't establish identification.

05

Honest causal forests

Read

A causal forest estimates the conditional effect τ(x)\tau(x) for each kind of unit. Its trees split to find regions where the effect differs; together they give each training row a weight αi(x)\alpha_i(x) of relevance to a target xx. With nuisance estimates m^\hat m and e^\hat e (the propensity), τ(x)\tau(x) solves the locally weighted residual equation

∑iαi(x)(Wi−e^i)[Yi−m^i−τ(x)(Wi−e^i)]=0.\sum_i\alpha_i(x)(W_i-\hat e_i)\big[Y_i-\hat m_i-\tau(x)(W_i-\hat e_i)\big]=0.

Honesty uses one half of each tree's sample to choose splits and the other half to estimate effects in the leaves, so the same noise can't both create a split and fill it.

Causal forestRecorded · Python and R agreeRecorded 2026-11-17 · 24 values compared · largest relative difference 1.1e-1
R

The causal forest (2000 trees) estimates the average effect of true vs false on outcome at 1.93 (95% CI [1.77, 2.10], p < .001). Individual effects range from 0.76 to 3.11 (10th–90th percentile); 100% are positive.

ATE
1.934
95% CI
[1.769, 2.098]
p
< .001
Share with a positive effect
100.0%

Assumptions

  • Overlap (positivity) — 0.0% of rows have propensity scores below .05 or above .95; 0.6% lie outside the common support [0.156, 0.837].
  • 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.
  • Effect heterogeneity — Individual effect estimates are noisy; compare groups of rows (quintiles) rather than single rows, and confirm heterogeneity on new data.

Effects by quintile of predicted effect

QuintilenMean predicted effectObserved difference (treated − control)
12370.76910.7725
22371.3831.180
32371.9842.107
42372.5092.526
52373.1312.860

Observed differences are unadjusted; with confounding they are only a rough check of the ranking.

Variable importance

CovariateImportance
x10.7373
x20.1110
income (k)0.1086
member: true0.0186
segment: b0.0123
segment: c0.0121

grf::variable_importance (depth-weighted split frequency).

  • 15 of 1200 rows were left out because a value was missing.
  • R: grf::causal_forest (out-of-bag CATE, AIPW average effect); Python: EconML CausalForestDML. Same estimand, different implementations (parity tier P3).
The exact R script · R R version 4.5.1 (2025-06-13)
# Causal forest (heterogeneous treatment effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.forest 1.1.1 · spec 1ade787b1be02d3c
# 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)
library(grf)

# %% 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 draws the same folds and resamples
tr_info <- cs_causal_treatment(df, treatment, NULL)
t <- tr_info$t
treated_level <- tr_info$treated
control_level <- tr_info$control
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
labels <- des$labels
binary <- des$binary
if (ncol(X) > 0) cs_causal_check_rank(X, labels)
n <- length(t)
n_treated <- as.integer(sum(t))
n_control <- as.integer(n - sum(t))
outcome_text <- if (!is.null(event_level)) sprintf("%s = %s", outcome, event_level) else outcome
contrast_text <- sprintf("%s = %s vs %s", treatment, treated_level, control_level)
n_trees <- as.integer(ceiling(as.integer(2000) / 4) * 4)  # same count as Python (EconML grows trees in fours)
min_node <- as.integer(5)
frac <- 0.5
honest <- TRUE

# %% Causal forest (Python: EconML CausalForestDML with the same honesty, subsample and leaf size)
cf <- grf::causal_forest(X, y, t, num.trees = n_trees, sample.fraction = frac, min.node.size = min_node, honesty = honest,
                         seed = seed, num.threads = 1)
tau <- as.numeric(predict(cf)$predictions)  # out-of-bag predictions
ate_res <- grf::average_treatment_effect(cf, target.sample = "all")
ate <- unname(ate_res[["estimate"]])
se <- unname(ate_res[["std.err"]])
zc <- stats::qnorm(1 - (1 - conf) / 2)
z <- ate / se
p_value <- 2 * stats::pnorm(abs(z), lower.tail = FALSE)
summ <- cs_causal_cate_summary(tau)
groups <- cs_causal_group_effects(tau, t, y, NULL)
importance <- as.numeric(grf::variable_importance(cf))
ord <- order(-importance, method = "radix")
imp_rows <- lapply(ord, function(j) list(feature = labels[j], importance = importance[j]))

# %% Per-row effects (artifact)
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.forest/obs-heterogeneous/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rownames(df)) - 1L, cate = tau), file.path(out, "cate.parquet"))

# %% Result
effect_label <- sprintf("Average treatment effect of %s on %s (causal forest)", contrast_text, outcome_text)
pct <- sprintf("%.0f%%", conf * 100)
summary <- paste0(
  sprintf("The causal forest (%d trees) estimates the average effect of %s vs %s on %s at %s (%s CI [%s, %s], %s). ", n_trees, treated_level, control_level,
          outcome_text, cs_fmt_num(ate), pct, cs_fmt_num(ate - zc * se), cs_fmt_num(ate + zc * se), cs_fmt_p(p_value)),
  sprintf("Individual effects range from %s to %s (10th–90th percentile); %.0f%% are positive.", cs_fmt_num(summ$cate_p10), cs_fmt_num(summ$cate_p90),
          100 * summ$share_positive))
# Positivity on grf's out-of-bag propensity scores (EconML's out-of-fold scores in Python).
e_hat <- as.numeric(cf$W.hat)
checks <- list(cs_causal_overlap_check(e_hat, t), cs_causal_no_confounding_check(),
               list(id = "heterogeneity", label = "Effect heterogeneity", status = "info",
                    detail = "Individual effect estimates are noisy; compare groups of rows (quintiles) rather than single rows, and confirm heterogeneity on new data."))
values <- c(list(estimate = ate, se = se, ci_low = ate - zc * se, ci_high = ate + zc * se, z = z, p_value = p_value, n = n,
                 estimand = "ATE", effect_label = effect_label, claim_level_max = "L2"), summ,
            list(n_trees = n_trees, treated_level = treated_level, control_level = control_level,
                 ps_min = min(e_hat), ps_max = max(e_hat), share_extreme_ps = mean(e_hat < 0.05 | e_hat > 0.95)))
cs_publish(list(
  method = "causal.forest",
  methodVersion = "1.1.1",
  title = "Causal forest",
  engine = cs_engine_info("grf", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "estimate", label = "ATE", value = ate),
    list(key = "ci", label = paste(pct, "CI"), value = c(ate - zc * se, ate + zc * se)),
    list(key = "p_value", label = "p", value = p_value, format = "p"),
    list(key = "share_positive", label = "Share with a positive effect", value = summ$share_positive, format = "percent")),
  tables = list(
    list(key = "groups", title = "Effects by quintile of predicted effect", columns = list(
      list(key = "group", label = "Quintile", type = "integer"), list(key = "n", label = "n", type = "integer"),
      list(key = "cate_mean", label = "Mean predicted effect", type = "number"),
      list(key = "observed", label = "Observed difference (treated − control)", type = "number")),
      rows = lapply(groups, function(r) r[c("group", "n", "cate_mean", "observed")]),
      note = "Observed differences are unadjusted; with confounding they are only a rough check of the ranking."),
    list(key = "importance", title = "Variable importance", columns = list(
      list(key = "feature", label = "Covariate", type = "string"), list(key = "importance", label = "Importance", type = "number")),
      rows = imp_rows, note = "grf::variable_importance (depth-weighted split frequency).")),
  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,
  artifacts = list(list(key = "cate", path = "cate.parquet", format = "parquet", title = "Conditional average treatment effect per row")),
  warnings = warnings,
  notes = list("R: grf::causal_forest (out-of-bag CATE, AIPW average effect); Python: EconML CausalForestDML. Same estimand, different implementations (parity tier P3)."),
  charts = list(
    cs_chart("cate", "histogram", "Distribution of individual effect estimates", list(x = cs_col("Estimated effect", tau))),
    cs_chart("importance", "importance-bar", "Variable importance", list(
      feature = cs_col("Covariate", vapply(imp_rows, `[[`, "", "feature"), kind = "categorical"),
      importance = cs_col("Importance", vapply(imp_rows, `[[`, 0, "importance")))),
    cs_chart("overlap", "overlap-density", "Out-of-fold propensity scores by group", list(
      score = cs_col("Propensity score", e_hat), group = cs_col(treatment, ifelse(t == 1, treated_level, control_level), kind = "categorical")))),
  values = values
))
Python

The causal forest (2000 trees) estimates the average effect of true vs false on outcome at 1.96 (95% CI [1.79, 2.12], p < .001). Individual effects range from 0.85 to 2.95 (10th–90th percentile); 99% are positive.

ATE
1.955
95% CI
[1.793, 2.117]
p
< .001
Share with a positive effect
99.3%

Assumptions

  • Overlap (positivity) — 0.0% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.132, 0.767].
  • 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.
  • Effect heterogeneity — Individual effect estimates are noisy; compare groups of rows (quintiles) rather than single rows, and confirm heterogeneity on new data.

Effects by quintile of predicted effect

QuintilenMean predicted effectObserved difference (treated − control)
12370.76290.2943
22371.5051.206
32371.9901.993
42372.4552.451
52373.0603.526

Observed differences are unadjusted; with confounding they are only a rough check of the ranking.

Variable importance

CovariateImportance
x10.7485
income (k)0.1010
x20.0940
member: true0.0272
segment: c0.0235
segment: b0.0058

EconML's impurity-based importance of the final forest.

  • 15 of 1200 rows were left out because a value was missing.
  • Python: EconML CausalForestDML (random-forest nuisances, 5-fold cross-fitting); R: grf::causal_forest. Same estimand, different implementations (parity tier P3).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Causal forest (heterogeneous treatment effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.forest 1.1.1 · spec 1ade787b1be02d3c
# 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 os
import warnings as _warnings

import numpy as np
import pandas as pd
from scipy import stats
from econml.dml import CausalForestDML
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor

import codesplash as cs
from codesplash.causal import meta as csmeta
from codesplash.causal import weighting as csw
from codesplash.ml.run import out_dir as cs_out_dir

# %% 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 draws the same folds and resamples
t, treated_level, control_level = csw.treatment_indicator(df, treatment, None)
y, event_level = csw.outcome_vector(df, outcome)
X, labels, binary, sources = csw.covariate_matrix(df, covariates)
if X.shape[1]:
    csw.check_rank(X, labels)
n = len(t)
n_treated, n_control = int(t.sum()), int(n - t.sum())
outcome_text = f"{outcome} = {event_level}" if event_level is not None else outcome
contrast_text = f"{treatment} = {treated_level} vs {control_level}"
n_trees = int(np.ceil(int(2000) / 4) * 4)  # EconML grows trees in groups of four
min_node = int(5)
frac = 0.5
honest = True

# %% Causal forest (R: grf::causal_forest with the same honesty, subsample and leaf size)
est = CausalForestDML(
    model_y=RandomForestRegressor(n_estimators=500, min_samples_leaf=20, max_samples=0.5, random_state=seed, n_jobs=1),
    model_t=RandomForestClassifier(n_estimators=500, min_samples_leaf=20, max_samples=0.5, random_state=seed, n_jobs=1),
    discrete_treatment=True, n_estimators=n_trees, min_samples_leaf=min_node, max_samples=frac, honest=honest,
    inference=True, cv=5, random_state=seed, n_jobs=1,
)
with _warnings.catch_warnings():
    _warnings.simplefilter("ignore")
    est.fit(y, t, X=X, cache_values=True)
tau = np.asarray(est.effect(X), dtype=float).ravel()
# Average effect from doubly robust scores, exactly as grf::average_treatment_effect computes them:
# Γ = τ(x) + (W − ê)/(ê(1 − ê)) · (Y − m̂ − (W − ê)·τ(x)), with EconML's out-of-fold residuals Y − m̂ and W − ê.
y_res, t_res = (np.asarray(r, dtype=float).reshape(n, -1)[:, 0] for r in est.residuals_[:2])
e_hat = t - t_res
gamma = tau + t_res / (e_hat * (1 - e_hat)) * (y_res - t_res * tau)
ate = float(gamma.mean())
se = float(np.std(gamma, ddof=1) / np.sqrt(n))
zc = stats.norm.ppf(1 - (1 - conf) / 2)
z = ate / se
p_value = float(2 * stats.norm.sf(abs(z)))
summ = csmeta.cate_summary(tau)
groups = csmeta.group_effects(tau, t, y, None)
importance = np.asarray(est.feature_importances_, dtype=float)
imp_rows = sorted(({"feature": lab, "importance": float(v)} for lab, v in zip(labels, importance)), key=lambda r: -r["importance"])

# %% Per-row effects (artifact)
out = cs_out_dir("target/academy-parity/run-953/causal.forest/obs-heterogeneous/out-python")
pd.DataFrame({"row": df.index.to_numpy(dtype=np.int64), "cate": tau}).to_parquet(os.path.join(out, "cate.parquet"), index=False)

# %% Result
effect_label = f"Average treatment effect of {contrast_text} on {outcome_text} (causal forest)"
pct = f"{conf:.0%}"
summary = (
    f"The causal forest ({n_trees} trees) estimates the average effect of {treated_level} vs {control_level} on {outcome_text} at "
    f"{cs.fmt_num(ate)} ({pct} CI [{cs.fmt_num(ate - zc * se)}, {cs.fmt_num(ate + zc * se)}], {cs.fmt_p(p_value)}). Individual effects range from "
    f"{cs.fmt_num(summ['cate_p10'])} to {cs.fmt_num(summ['cate_p90'])} (10th–90th percentile); {summ['share_positive']:.0%} are positive."
)
# Positivity on the forest's out-of-fold propensity scores (EconML cross-fitting; grf's out-of-bag W.hat in R).
checks = [csw.overlap_check(e_hat, t), csw.no_confounding_check(),
          {"id": "heterogeneity", "label": "Effect heterogeneity", "status": "info",
           "detail": "Individual effect estimates are noisy; compare groups of rows (quintiles) rather than single rows, and confirm heterogeneity on new data."}]
values = {
    "estimate": ate, "se": se, "ci_low": ate - zc * se, "ci_high": ate + zc * se, "z": z, "p_value": p_value, "n": n,
    "estimand": "ATE", "effect_label": effect_label, "claim_level_max": "L2", **summ, "n_trees": n_trees,
    "treated_level": treated_level, "control_level": control_level,
    "ps_min": float(e_hat.min()), "ps_max": float(e_hat.max()), "share_extreme_ps": float(np.mean((e_hat < 0.05) | (e_hat > 0.95))),
}
cs.publish({
    "method": "causal.forest",
    "methodVersion": "1.1.1",
    "title": "Causal forest",
    "engine": cs.engine_info("econml", "scikit-learn", "numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "estimate", "label": "ATE", "value": ate},
        {"key": "ci", "label": f"{pct} CI", "value": [ate - zc * se, ate + zc * se]},
        {"key": "p_value", "label": "p", "value": p_value, "format": "p"},
        {"key": "share_positive", "label": "Share with a positive effect", "value": summ["share_positive"], "format": "percent"},
    ],
    "tables": [
        {"key": "groups", "title": "Effects by quintile of predicted effect", "columns": [
            {"key": "group", "label": "Quintile", "type": "integer"}, {"key": "n", "label": "n", "type": "integer"},
            {"key": "cate_mean", "label": "Mean predicted effect", "type": "number"},
            {"key": "observed", "label": "Observed difference (treated − control)", "type": "number"}],
         "rows": [{k: r[k] for k in ("group", "n", "cate_mean", "observed")} for r in groups],
         "note": "Observed differences are unadjusted; with confounding they are only a rough check of the ranking."},
        {"key": "importance", "title": "Variable importance", "columns": [
            {"key": "feature", "label": "Covariate", "type": "string"}, {"key": "importance", "label": "Importance", "type": "number"}],
         "rows": imp_rows, "note": "EconML's impurity-based importance of the final forest."},
    ],
    "assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
    "checks": checks,
    "artifacts": [{"key": "cate", "path": "cate.parquet", "format": "parquet", "title": "Conditional average treatment effect per row"}],
    "warnings": warnings,
    "notes": ["Python: EconML CausalForestDML (random-forest nuisances, 5-fold cross-fitting); R: grf::causal_forest. Same estimand, different implementations (parity tier P3)."],
    "charts": [
        cs.chart("cate", "histogram", "Distribution of individual effect estimates", {"x": cs.col("Estimated effect", tau)}),
        cs.chart("importance", "importance-bar", "Variable importance",
                 {"feature": cs.col("Covariate", [r["feature"] for r in imp_rows], kind="categorical"),
                  "importance": cs.col("Importance", [r["importance"] for r in imp_rows])}),
        cs.chart("overlap", "overlap-density", "Out-of-fold propensity scores by group",
                 {"score": cs.col("Propensity score", e_hat), "group": cs.col(treatment, np.where(t == 1, str(treated_level), str(control_level)), kind="categorical")}),
    ],
    "values": values,
})

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

06

Reading heterogeneity

Read

The estimated effects ranged from 0.765 at the 10th percentile to 3.11 at the 90th, around an average of 1.93.

Spread in predicted effects isn't proof of real heterogeneity: flexible searches find patterns in noise. Test it with held-out calibration (does the top predicted group really benefit more?), prespecify the subgroups you report, and check overlap near each prediction: where the propensity is close to 0 or 1, the local denominator is tiny and estimates swing.

07

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Double ML with cross-fitting (UNC014)Runs in CodeSplash: Double/debiased machine learning (DoubleML), partially linear or interactive model
Honest causal forests (UNC015)Runs in CodeSplash: Causal forest (heterogeneous treatment effects)

Both also appear in the Causal Studio, which walks you through the design questions first.

08

Check your understanding

Checkpoint

Check yourself

Why does double ML predict each row's outcome and treatment with models trained on other folds?

Show the answer

Answer: b

Cross-fitting keeps each residual honest, which the inference relies on.

Check yourself

What does Neyman orthogonality buy double ML?

Show the answer

Answer: a

It reduces sensitivity to estimation error. It can't fix missing variables or a wrong estimand.

Check yourself

You try five learners for the nuisance models and report the one whose effect is most significant. What's wrong?

Show the answer

Answer: b

Pick learners by held-out prediction of the nuisances, decided before you look at the effect.

Check yourself

What does honesty mean in a causal forest?

Show the answer

Answer: b

Splitting and estimating on the same rows lets noise both create a split and inflate its effect. Honesty separates them.

Check yourself

For some units the estimated propensity is 0.98. What does that do to their conditional effect estimates?

Show the answer

Answer: b

Check overlap before trusting local effects. Extrapolating beyond support isn't reliable.

Check yourself

The forest's predicted effects vary widely. How do you check the variation is real?

Show the answer

Answer: a

Flexible searches find noise. Held-out checks and prespecified subgroups separate signal from search.

09

Do it on your own data

In the app

Open the Causal Studio, state the treatment, outcome and adjustment set, and check overlap. Then estimate the average effect with Double/debiased machine learning (DoubleML) and look for variation with Causal forest, holding out data to test any subgroup you'd report.

Concepts in this lesson