Skip to content

CCausal inference · causal.metalearner

Meta-learners for heterogeneous effects (S, T, X, DR)

How large is the treatment effect for each kind of unit, estimated with standard machine-learning models?

Conditional average treatment effects from meta-learners built on ordinary regression models: the S-learner (one model with the treatment as a feature), T-learner (one model per arm), X-learner (imputed effects per arm combined with the propensity score) and DR-learner (cross-fitted doubly robust pseudo-outcomes regressed on the covariates). Base models are least squares or LightGBM (same core in both engines; folds from a shared random stream), so Python and R agree exactly. Reports the average effect (with an influence-function interval for the DR-learner), the CATE distribution, effects by quintile of predicted benefit, and saves every row's CATE.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Dr lightgbm”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

DR-learner (LightGBM)Recorded · Python and R agreeRecorded 2026-11-17 · 35 values compared
R

The DR-learner with LightGBM base models puts the average effect of true vs false on outcome at 1.82 (95% CI [1.57, 2.07], p < .001). Individual effects range from 0.15 to 3.38 (10th–90th percentile); 91% are positive.

Average effect
1.820
95% CI
[1.569, 2.070]
p
< .001
Share with a positive effect
91.1%

Assumptions

  • Overlap (positivity) — 0.6% of rows have propensity scores below .05 or above .95; 0.9% lie outside the common support [0.034, 0.904].
  • Clipped propensity scores — 0 of 1185 out-of-fold propensity scores clipped to [0.01, 0.99].
  • 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 — Compare quintiles of predicted effect (with DR scores for the DR-learner) rather than single rows; confirm heterogeneity on new data.

Effects by quintile of predicted effect

QuintilenMean predicted effectDoubly robust effectSE
1237−0.4271−1.0790.4417
22371.3380.98870.1519
32372.0122.0400.1525
42372.6072.8170.1528
52373.5694.3320.2750

DR: mean doubly robust score per quintile (GATES-style check of the ranking).

  • 15 of 1200 rows were left out because a value was missing.
  • Folds from seed 42 (portable Wichmann–Hill stream).
Python

The DR-learner with LightGBM base models puts the average effect of true vs false on outcome at 1.82 (95% CI [1.57, 2.07], p < .001). Individual effects range from 0.15 to 3.38 (10th–90th percentile); 91% are positive.

Average effect
1.820
95% CI
[1.569, 2.070]
p
< .001
Share with a positive effect
91.1%

Assumptions

  • Overlap (positivity) — 0.6% of rows have propensity scores below .05 or above .95; 0.9% lie outside the common support [0.034, 0.904].
  • Clipped propensity scores — 0 of 1185 out-of-fold propensity scores clipped to [0.01, 0.99].
  • 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 — Compare quintiles of predicted effect (with DR scores for the DR-learner) rather than single rows; confirm heterogeneity on new data.

Effects by quintile of predicted effect

QuintilenMean predicted effectDoubly robust effectSE
1237−0.4271−1.0790.4417
22371.3380.98870.1519
32372.0122.0400.1525
42372.6072.8170.1528
52373.5694.3320.2750

DR: mean doubly robust score per quintile (GATES-style check of the ranking).

  • 15 of 1200 rows were left out because a value was missing.
  • Folds from seed 42 (portable Wichmann–Hill stream).

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

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Dr lightgbmc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
  • X linearc2_obs · covariates: x1, x2, segment, member · outcome: outcome · treatment: treated
  • T lightgbm upliftc2_uplift · covariates: recency, frequency, segment · outcome: converted · treatment: offer
  • S lightgbm lalondec2_lalonde · covariates: age, educ, race, married, re74, re75 · outcome: earnings 1978 · treatment: treat
  • Degenerate constantc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
  • Degenerate n1c2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
  • Degenerate n3c2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated

In the guides

Where it sits in the decision guides

  • Causal ML (uplift modeling) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcomenumeric / boolean · 1 column
The outcome the treatment may affect (a number, or yes/no).
Treatmentboolean / categorical · 1 column · 2–2 levels
Marks which rows received the treatment (yes/no, or a level that means treated).
Covariates (confounders and effect modifiers)numeric / categorical / boolean · 1–100 columns · 2–30 levels
Variables that may confound the effect or change its size (effect modifiers).

Choices you make

hypothesis

Treated groupdefault —

Default: the second stored level (true for yes/no columns).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Meta-learnerdefault dr

How individual effects are estimated. DR is the safest default; X suits unbalanced groups; T and S are simplest.

  • DR-learner (doubly robust; recommended)(default) — Combines outcome models and propensity weights, and stays consistent if either is right; the usual choice.
  • X-learner (good with unbalanced groups) — Imputes effects for each group and blends them by propensity; pick it when one group is much smaller.
  • T-learner (one model per group) — Fits separate models for treated and control; easy to explain, but noisy when one group is small.
  • S-learner (treatment as a feature) — Fits one model with treatment as a feature; easy to explain, but it can shrink the effect towards zero.
Base modeldefault lightgbm

Model used inside the meta-learner: gradient boosting (flexible) or linear regression (simple).

  • LightGBM (gradient boosting)(default) — Fits the inner models with gradient-boosted trees; pick it to catch nonlinear patterns when you have plenty of rows.
  • Linear regression — Fits the inner models with linear regression; pick it for small samples or roughly additive effects.
Cross-fitting folds (DR)default 5

Cross-fitting folds for the DR-learner's nuisance models; each fold is predicted by models fit on the others.

Clip propensity scores at (DR)default 0.01

Propensity scores are kept within [c, 1 − c] so near-zero scores don't blow up the DR weights.

model

Boosting roundsdefault 200

Number of trees (boosting rounds). More is steadier but slower; boosting can overfit if there are too many.

Learning ratedefault 0.05

How much each boosting round corrects the last. Smaller values learn slower but usually generalize better (add rounds).

Leaves per treedefault 15

Maximum leaves per tree. More leaves capture finer patterns but overfit sooner.

Minimum rows per leafdefault 20

Smallest number of rows allowed in a leaf. Larger values smooth predictions and reduce overfitting.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Overlap (positivity)

    Out-of-fold propensity scores near 0 or 1 mean some rows have no comparable treated or control rows, so their effects are extrapolated.

  • Few clipped propensity scores

    Many clipped scores mean the treated and controls barely overlap.

  • No unmeasured confounding

  • Effect heterogeneity

    Individual effect estimates are noisy; compare groups of rows and confirm heterogeneity on new data.

What it reports

estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
n
How many independent units the analysis used; it sets precision and power.
estimand
The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
effect_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
claim_level_max
How strong a causal statement the design supports, from association up to a causal effect.
cate_mean
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_sd
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_p10
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_p25
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_p50
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_p75
The average effect among units with given characteristics, used to ask for whom a treatment works.
cate_p90
The average effect among units with given characteristics, used to ask for whom a treatment works.
share_positive
The average effect among units with given characteristics, used to ask for whom a treatment works.
learner
Which meta-learner estimated the individual effects: s, t, x or dr (doubly robust).
base
The model fitted inside the meta-learner: lightgbm (gradient-boosted trees) or linear (linear regression).
treated_level
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
control_level
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
ps_min
Each unit's probability of treatment given its covariates; used to match or weight comparable groups.
ps_max
Each unit's probability of treatment given its covariates; used to match or weight comparable groups.
share_extreme_ps
Every kind of unit has some chance of being in each group; without it comparisons extrapolate.

Per group, level or term: group_cate[<quintile>], group_observed[…], n_clipped

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, lightgbm, codesplash; R uses stats, nanoparquet, lightgbm, codesplashr.

Default traps between the two languages

  • Both engines run the twins codesplash.causal.meta ↔ cs_causal_cate (EconML's SLearner/TLearner/XLearner/DRLearner are the classic Python equivalents; R has no standard package). LightGBM base models use the shared core in deterministic single-thread mode with identical parameters, so CATEs agree to rounding.
Python

The exact script CodeSplash ran for example “Dr lightgbm” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Meta-learners for heterogeneous effects (S, T, X, DR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.metalearner 1.1.1 · spec ef3ba7fe47a982e9
# 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 numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.causal import dr as csdr
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}"
kind = "dr"  # s | t | x | dr
base = "lightgbm"  # lightgbm | linear
k = int(5)
clip = 0.01
params = {
    "n_estimators": 80, "learning_rate": 0.05,
    "num_leaves": 15, "min_child_samples": 20,
}

# %% CATE (EconML's SLearner / TLearner / XLearner / DRLearner are the classic equivalents)
folds = csdr.fold_ids(n, k, seed)
fit = csmeta.cate(kind, "glm" if base == "linear" else base, X, t, y, params, seed, folds, clip)
tau = fit["cate"]
summ = csmeta.cate_summary(tau)
pseudo = fit.get("pseudo")
groups = csmeta.group_effects(tau, t, y, pseudo)
values = {}
zc = stats.norm.ppf(1 - (1 - conf) / 2)
if pseudo is not None:
    est = float(pseudo.mean())
    se = float(np.sqrt(np.mean((pseudo - est) ** 2) / n))
    ci_low, ci_high = est - zc * se, est + zc * se
    p_value = float(2 * stats.norm.sf(abs(est / se)))
    values["n_clipped"] = fit["n_clipped"]
else:
    est, se, ci_low, ci_high, p_value = float(tau.mean()), None, None, None, None
for g in groups:
    values[f"group_cate[{g['group']}]"] = g["cate_mean"]
    values[f"group_observed[{g['group']}]"] = g["observed"]

# %% Per-row effects (artifact)
out = cs_out_dir("target/academy-parity/run-953/causal.metalearner/dr-lightgbm/out-python")
frame = pd.DataFrame({"row": df.index.to_numpy(dtype=np.int64), "cate": tau})
if pseudo is not None:
    frame["dr_score"] = pseudo
frame.to_parquet(os.path.join(out, "cate.parquet"), index=False)

# %% Result
lname = {"s": "S", "t": "T", "x": "X", "dr": "DR"}[kind]
bname = "LightGBM" if base == "lightgbm" else "linear regression"
effect_label = f"Conditional effects of {contrast_text} on {outcome_text} ({lname}-learner, average)"
pct = f"{conf:.0%}"
interval = f" ({pct} CI [{cs.fmt_num(ci_low)}, {cs.fmt_num(ci_high)}], {cs.fmt_p(p_value)})" if se is not None else ""
summary = (
    f"The {lname}-learner with {bname} base models puts the average effect of {treated_level} vs {control_level} on {outcome_text} at "
    f"{cs.fmt_num(est)}{interval}. Individual effects range from {cs.fmt_num(summ['cate_p10'])} to {cs.fmt_num(summ['cate_p90'])} "
    f"(10th–90th percentile); {summ['share_positive']:.0%} are positive."
)
checks = [csw.no_confounding_check(),
          {"id": "heterogeneity", "label": "Effect heterogeneity", "status": "info",
           "detail": "Compare quintiles of predicted effect (with DR scores for the DR-learner) rather than single rows; confirm heterogeneity on new data."}]
if pseudo is not None:
    checks.insert(0, {"id": "clipping", "label": "Clipped propensity scores",
                      "status": "pass" if fit["n_clipped"] / n <= 0.02 else "concern" if fit["n_clipped"] / n <= 0.1 else "fail",
                      "detail": f"{fit['n_clipped']} of {n} out-of-fold propensity scores clipped to [{clip:g}, {1 - clip:g}]."})
# Positivity on out-of-fold propensity scores (same model family as the base learner); a failure caps the claim at L1.
e_oof = fit["e_oof"]
checks.insert(0, csw.overlap_check(e_oof, t))
values.update({
    "estimate": est, "se": se, "ci_low": ci_low, "ci_high": ci_high, "p_value": p_value, "n": n, "estimand": "CATE (average)",
    "effect_label": effect_label, "claim_level_max": "L2", **summ, "learner": kind, "base": base,
    "treated_level": treated_level, "control_level": control_level,
    "ps_min": float(e_oof.min()), "ps_max": float(e_oof.max()),
    "share_extreme_ps": float(np.mean((e_oof < 0.05) | (e_oof > 0.95))),
})
group_chart = []
if pseudo is not None:
    group_chart = [cs.chart(
        "groups", "forest", "Doubly robust effect by quintile of predicted effect",
        {"label": cs.col("Quintile", [f"Q{g['group']}" for g in groups], kind="categorical"),
         "estimate": cs.col("Effect", [g["observed"] for g in groups]),
         "low": cs.col("CI low", [g["observed"] - zc * g["observed_se"] for g in groups]),
         "high": cs.col("CI high", [g["observed"] + zc * g["observed_se"] for g in groups])},
        {"reference": 0},
    )]
cs.publish({
    "method": "causal.metalearner",
    "methodVersion": "1.1.1",
    "title": f"{lname}-learner ({bname})",
    "engine": cs.engine_info("numpy", "pandas", "scipy", *(["lightgbm"] if base == "lightgbm" else [])),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "estimate", "label": "Average effect", "value": est},
        *([{"key": "ci", "label": f"{pct} CI", "value": [ci_low, ci_high]}, {"key": "p_value", "label": "p", "value": p_value, "format": "p"}] if se is not None else []),
        {"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": "Doubly robust effect" if pseudo is not None else "Observed difference", "type": "number"},
            {"key": "observed_se", "label": "SE", "type": "number"}],
         "rows": groups,
         "note": "DR: mean doubly robust score per quintile (GATES-style check of the ranking)." if pseudo is not None else "Unadjusted differences in means per quintile."},
    ],
    "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": [f"Folds from seed {seed} (portable Wichmann–Hill stream)." if kind == "dr" else "Base models fitted on all rows (no cross-fitting)."],
    "charts": [cs.chart("cate", "histogram", "Distribution of individual effect estimates", {"x": cs.col("Estimated effect", tau)})] + group_chart + [cs.chart(
        "overlap", "overlap-density", "Out-of-fold propensity scores by group",
        {"score": cs.col("Propensity score", e_oof), "group": cs.col(treatment, np.where(t == 1, str(treated_level), str(control_level)), kind="categorical")},
    )],
    "values": values,
})
R

The exact script CodeSplash ran for example “Dr lightgbm” · R version 4.5.1 (2025-06-13)

# Meta-learners for heterogeneous effects (S, T, X, DR)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.metalearner 1.1.1 · spec ef3ba7fe47a982e9
# 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)

# %% 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)
kind <- "dr"  # s | t | x | dr
base <- "lightgbm"  # lightgbm | linear
k <- as.integer(5)
clip <- 0.01
params <- list(n_estimators = 80, learning_rate = 0.05,
               num_leaves = 15, min_child_samples = 20)

# %% CATE (twins of the Python meta-learners; EconML's S/T/X/DR learners are the classic equivalents)
folds <- cs_causal_folds(n, k, seed)
fit <- cs_causal_cate(kind, base, X, t, y, params, seed, folds, clip)
tau <- fit$cate
summ <- cs_causal_cate_summary(tau)
pseudo <- fit$pseudo
groups <- cs_causal_group_effects(tau, t, y, pseudo)
values <- list()
zc <- stats::qnorm(1 - (1 - conf) / 2)
if (!is.null(pseudo)) {
  est <- mean(pseudo)
  se <- sqrt(mean((pseudo - est)^2) / n)
  ci_low <- est - zc * se
  ci_high <- est + zc * se
  p_value <- 2 * stats::pnorm(abs(est / se), lower.tail = FALSE)
  values$n_clipped <- fit$n_clipped
} else {
  est <- mean(tau)
  se <- NULL
  ci_low <- NULL
  ci_high <- NULL
  p_value <- NULL
}
for (g in groups) {
  values[[sprintf("group_cate[%d]", g$group)]] <- g$cate_mean
  values[sprintf("group_observed[%d]", g$group)] <- list(g$observed)
}

# %% Per-row effects (artifact)
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.metalearner/dr-lightgbm/out-r")
frame <- data.frame(row = as.integer(rownames(df)) - 1L, cate = tau)
if (!is.null(pseudo)) frame$dr_score <- pseudo
nanoparquet::write_parquet(frame, file.path(out, "cate.parquet"))

# %% Result
lname <- switch(kind, s = "S", t = "T", x = "X", dr = "DR")
bname <- if (base == "lightgbm") "LightGBM" else "linear regression"
effect_label <- sprintf("Conditional effects of %s on %s (%s-learner, average)", contrast_text, outcome_text, lname)
pct <- sprintf("%.0f%%", conf * 100)
interval <- if (!is.null(se)) sprintf(" (%s CI [%s, %s], %s)", pct, cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p_value)) else ""
summary <- paste0(
  sprintf("The %s-learner with %s base models puts the average effect of %s vs %s on %s at %s%s. ", lname, bname, treated_level, control_level,
          outcome_text, cs_fmt_num(est), interval),
  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))
checks <- list(cs_causal_no_confounding_check(),
               list(id = "heterogeneity", label = "Effect heterogeneity", status = "info",
                    detail = "Compare quintiles of predicted effect (with DR scores for the DR-learner) rather than single rows; confirm heterogeneity on new data."))
if (!is.null(pseudo)) {
  sc <- fit$n_clipped / n
  checks <- c(list(list(id = "clipping", label = "Clipped propensity scores", status = if (sc <= 0.02) "pass" else if (sc <= 0.1) "concern" else "fail",
                        detail = sprintf("%d of %d out-of-fold propensity scores clipped to [%s, %s].", fit$n_clipped, n, sprintf("%g", clip), sprintf("%g", 1 - clip)))), checks)
}
# Positivity on out-of-fold propensity scores (same model family as the base learner); a failure caps the claim at L1.
e_oof <- fit$e_oof
checks <- c(list(cs_causal_overlap_check(e_oof, t)), checks)
values <- c(values, list(estimate = est), list(se = se, ci_low = ci_low, ci_high = ci_high, p_value = p_value),
            list(n = n, estimand = "CATE (average)", effect_label = effect_label, claim_level_max = "L2"), summ,
            list(learner = kind, base = base, treated_level = treated_level, control_level = control_level,
                 ps_min = min(e_oof), ps_max = max(e_oof), share_extreme_ps = mean(e_oof < 0.05 | e_oof > 0.95)))
charts <- list(cs_chart("cate", "histogram", "Distribution of individual effect estimates", list(x = cs_col("Estimated effect", tau))))
if (!is.null(pseudo)) {
  charts[[2]] <- cs_chart("groups", "forest", "Doubly robust effect by quintile of predicted effect", list(
    label = cs_col("Quintile", sprintf("Q%d", vapply(groups, `[[`, 0L, "group")), kind = "categorical"),
    estimate = cs_col("Effect", vapply(groups, `[[`, 0, "observed")),
    low = cs_col("CI low", vapply(groups, function(g) g$observed - zc * g$observed_se, numeric(1))),
    high = cs_col("CI high", vapply(groups, function(g) g$observed + zc * g$observed_se, numeric(1)))),
    controls = list(reference = 0))
}
charts[[length(charts) + 1L]] <- cs_chart("overlap", "overlap-density", "Out-of-fold propensity scores by group", list(
  score = cs_col("Propensity score", e_oof), group = cs_col(treatment, ifelse(t == 1, treated_level, control_level), kind = "categorical")))
stats_list <- list(list(key = "estimate", label = "Average effect", value = est))
if (!is.null(se)) {
  stats_list <- c(stats_list, list(list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
                                   list(key = "p_value", label = "p", value = p_value, format = "p")))
}
stats_list <- c(stats_list, list(list(key = "share_positive", label = "Share with a positive effect", value = summ$share_positive, format = "percent")))
cs_publish(list(
  method = "causal.metalearner",
  methodVersion = "1.1.1",
  title = sprintf("%s-learner (%s)", lname, bname),
  engine = do.call(cs_engine_info, as.list(c("stats", "nanoparquet", if (base == "lightgbm") "lightgbm"))),
  n = n,
  summary = summary,
  statistics = stats_list,
  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 = if (!is.null(pseudo)) "Doubly robust effect" else "Observed difference", type = "number"),
    list(key = "observed_se", label = "SE", type = "number")),
    rows = groups,
    note = if (!is.null(pseudo)) "DR: mean doubly robust score per quintile (GATES-style check of the ranking)." else "Unadjusted differences in means per quintile.")),
  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(if (kind == "dr") sprintf("Folds from seed %d (portable Wichmann–Hill stream).", seed) else "Base models fitted on all rows (no cross-fitting)."),
  charts = charts,
  values = values
))

Sources

  • Künzel, S. R., Sekhon, J. S., Bickel, P. J., & Yu, B. (2019). Metalearners for estimating heterogeneous treatment effects using machine learning. PNAS, 116, 4156–4165.
  • Kennedy, E. H. (2023). Towards optimal doubly robust estimation of heterogeneous causal effects. Electronic Journal of Statistics, 17, 3008–3049.

From the CodeSplash method registry · causal.metalearner v1.1.1.