Who benefits most?
Estimate how effects vary with causal forests and meta-learners, then test whether a targeting score finds the people who respond.
What runs in CodeSplash
- Causal forest (heterogeneous treatment effects) Verified in Python and R
- Meta-learners for heterogeneous effects (S, T, X, DR) Verified in Python and R
- Uplift evaluation (Qini, AUUC, RATE) Verified in Python and R
You will be able to
- Distinguish a predicted outcome from a predicted effect
- Choose among causal forests and S, T, X and DR meta-learners
- Read a Qini curve and a RATE as tests of targeting
Read first
An average hides things
ReadThe average effect may be small while some people gain a lot and others lose. A conditional average treatment effectConditional average treatment effectThe average effect among units with given characteristics, used to ask for whom a treatment works. asks for whom the treatment works.
That's a different question from who will have a good outcome. A customer likely to buy anyway has a high predicted outcome and no upliftUpliftHow much a treatment changes the outcome for a unit, compared with leaving it untreated..
Who should get the offer?
PredictPredict first
You have budget to send a discount offer to only part of your customers. Whom do you want to reach?
Reveal
Those whose buying the offer changes most. Across this randomized campaign, the average effect is close to zero: −0.005. In the top tenth of customers by an uplift score, the difference in conversion rate is 0.12. An average near zero can hide gains and losses that cancel out.
Causal forests
In the appA causal forestCausal forestA forest that estimates how the treatment effect varies across units, with honest splitting for valid inference. grows trees that split where effects differ, using separate data to pick splits and to estimate effects.
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
| Quintile | n | Mean predicted effect | Observed difference (treated − control) |
|---|---|---|---|
| 1 | 237 | 0.7691 | 0.7725 |
| 2 | 237 | 1.383 | 1.180 |
| 3 | 237 | 1.984 | 2.107 |
| 4 | 237 | 2.509 | 2.526 |
| 5 | 237 | 3.131 | 2.860 |
Observed differences are unadjusted; with confounding they are only a rough check of the ranking.
Variable importance
| Covariate | Importance |
|---|---|
| x1 | 0.7373 |
| x2 | 0.1110 |
| income (k) | 0.1086 |
| member: true | 0.0186 |
| segment: b | 0.0123 |
| segment: c | 0.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
))
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
| Quintile | n | Mean predicted effect | Observed difference (treated − control) |
|---|---|---|---|
| 1 | 237 | 0.7629 | 0.2943 |
| 2 | 237 | 1.505 | 1.206 |
| 3 | 237 | 1.990 | 1.993 |
| 4 | 237 | 2.455 | 2.451 |
| 5 | 237 | 3.060 | 3.526 |
Observed differences are unadjusted; with confounding they are only a rough check of the ranking.
Variable importance
| Covariate | Importance |
|---|---|
| x1 | 0.7485 |
| income (k) | 0.1010 |
| x2 | 0.0940 |
| member: true | 0.0272 |
| segment: c | 0.0235 |
| segment: b | 0.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.
The average is 1.93. Estimated effects spread from 0.765 at the 10th percentile to 3.11 at the 90th.
These data are observational, so all of this assumes you've measured the confounders. The app caps the claim at L2.
Meta-learners
ReadMeta-learners build effect estimates from ordinary prediction models:
| Learner | Idea | Watch for |
|---|---|---|
| S | One model, with treatment as a feature | May shrink effects toward zero |
| T | Separate models for treated and control | Noisy when one arm is small |
| X | T, plus imputed effects weighted by propensity | Helps with unbalanced arms |
| DR | Doubly robust scores, then a model of them | Needs good overlap |
Check the learners against the data
In the appSort units into five groups by predicted effect, then compare with the actual difference in each group. If high predictions go with high observed differences, the learner has found something.
The X-learner with linear regression base models puts the average effect of true vs false on outcome at 2.06. Individual effects range from 0.79 to 3.38 (10th–90th percentile); 97% are positive.
- Average effect
- 2.057
- Share with a positive effect
- 97.3%
Assumptions
- Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.033, 0.933].
- 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
| Quintile | n | Mean predicted effect | Observed difference | SE |
|---|---|---|---|---|
| 1 | 237 | 0.6021 | 0.6598 | — |
| 2 | 237 | 1.517 | 1.350 | — |
| 3 | 237 | 2.059 | 2.177 | — |
| 4 | 237 | 2.627 | 2.548 | — |
| 5 | 237 | 3.482 | 3.104 | — |
Unadjusted differences in means per quintile.
- 15 of 1200 rows were left out because a value was missing.
- Base models fitted on all rows (no cross-fitting).
The exact R script · R 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 d00bc25f4aba65f5
# 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")))
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")]), , 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")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment <- "treated"
outcome <- "outcome"
covariates <- c("x1", "x2", "segment", "member")
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 <- "x" # s | t | x | dr
base <- "linear" # lightgbm | linear
k <- as.integer(5)
clip <- 0.01
params <- list(n_estimators = 200, 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/x-linear/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
))
The X-learner with linear regression base models puts the average effect of true vs false on outcome at 2.06. Individual effects range from 0.79 to 3.38 (10th–90th percentile); 97% are positive.
- Average effect
- 2.057
- Share with a positive effect
- 97.3%
Assumptions
- Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.033, 0.933].
- 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
| Quintile | n | Mean predicted effect | Observed difference | SE |
|---|---|---|---|---|
| 1 | 237 | 0.6021 | 0.6598 | — |
| 2 | 237 | 1.517 | 1.350 | — |
| 3 | 237 | 2.059 | 2.177 | — |
| 4 | 237 | 2.627 | 2.548 | — |
| 5 | 237 | 3.482 | 3.104 | — |
Unadjusted differences in means per quintile.
- 15 of 1200 rows were left out because a value was missing.
- Base models fitted on all rows (no cross-fitting).
The exact Python script · Python 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 d00bc25f4aba65f5
# 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"])
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"]) # 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"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and covariates
treatment = "treated"
outcome = "outcome"
covariates = ["x1", "x2", "segment", "member"]
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 = "x" # s | t | x | dr
base = "linear" # lightgbm | linear
k = int(5)
clip = 0.01
params = {
"n_estimators": 200, "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/x-linear/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,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
Read the card's chart and table of effects by quintile of predicted effect. Do the effects rise from the first quintile to the fifth?
An estimate for one person can't be checked directly. Groups give you a check that's possible. Here, the X-learner's mean is 2.06, and 97.3% of estimated effects are positive.
Does the score find them?
PredictPredict first
Rank-weighted average treatment effect (RATE) asks: do high-score customers respond more than average? An informative score gets 0.0594 (p = .018). What would a random score get, on the Qini weighting?
Reveal
0.0025, with p = .704 and an interval across zero. The two use different weightings, so compare each with zero rather than with each other. A random score should find nothing, and it doesn't.
Read a Qini curve
In the appRanking by uplift_score, the AUTOC rank-weighted treatment effect is 0.06 (95% CI [0.01, 0.11], p = .018). The top 10% of the ranking shows an uplift of 0.12 against an average effect of −0.01; the Qini coefficient is 0.0074.
- RATE (AUTOC)
- 0.0594
- 95% CI
- [0.0102, 0.1085]
- p
- .018
- Qini coefficient
- 0.0074
- AUUC
- 0.0120
Assumptions
- Randomized treatment — Assumes treatment was randomized with probability 0.501; with confounded treatment use doubly robust scores instead.
- Score ranks effects — Targeting by the score beats random targeting (the RATE interval excludes 0).
Uplift in the top of the ranking
| Top share targeted | Uplift (treated − control) |
|---|---|
| 10% | 0.1200 |
| 20% | 0.0779 |
| 30% | 0.0416 |
| All (ATE) | −0.0053 |
- RATE standard error from 200 bootstrap resamples (seed 42); curves computed over tied scores as blocks.
The exact R script · R R version 4.5.1 (2025-06-13)
# Uplift evaluation (Qini, AUUC, RATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.uplift 1.0.2 · spec 76ee2df503c4fb8e
# Dataset: c2_uplift (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_uplift.parquet", col_select = c("converted", "offer", "uplift_score")))
n_input <- nrow(df)
df[["converted"]] <- factor(df[["converted"]], levels = c("false", "true")) # stored level order
df[["offer"]] <- factor(df[["offer"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("converted", "offer", "uplift_score")]), , 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("converted", "offer", "uplift_score")) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and score
treatment <- "offer"
outcome <- "converted"
score_col <- "uplift_score"
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same bootstrap 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
score <- as.numeric(df[[score_col]])
if (length(unique(score)) < 2) cs_error("CS_E_CONSTANT", column = score_col) # a constant score ranks nobody: every curve is the random line
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
p_opt <- NULL
p <- if (is.null(p_opt)) mean(t) else as.numeric(p_opt)
target <- "AUTOC" # AUTOC | QINI
B <- as.integer(200)
# %% Curves and RATE (point estimate = grf::rank_average_treatment_effect.fit(DR.scores = IPW scores, priorities = score)$estimate)
cur <- cs_causal_uplift_curves(y, t, score)
gamma <- cs_causal_ipw_scores(y, t, p)
rate <- cs_causal_rate(gamma, score, target)
boot <- cs_causal_rate_bootstrap(y, t, score, p_opt, target, B, seed)
boot <- boot[!is.na(boot)]
se <- stats::sd(boot)
zc <- stats::qnorm(1 - (1 - conf) / 2)
ci_low <- rate - zc * se
ci_high <- rate + zc * se
p_value <- if (se > 0) 2 * stats::pnorm(abs(rate / se), lower.tail = FALSE) else NaN
ate <- mean(y[t == 1]) - mean(y[t == 0])
tops <- lapply(c(10, 20, 30), function(q) cs_causal_uplift_at(y, t, score, q / 100))
# %% Checks
checks <- list(
list(id = "randomization", label = "Randomized treatment", status = "info",
detail = sprintf("Assumes treatment was randomized with probability %.3f; with confounded treatment use doubly robust scores instead.", p)),
list(id = "ranking", label = "Score ranks effects", status = if (ci_low > 0) "pass" else "concern",
detail = if (ci_low > 0) "Targeting by the score beats random targeting (the RATE interval excludes 0)."
else "The RATE interval includes 0: the score may not rank treatment effects better than chance."))
# %% Result
effect_label <- sprintf("Rank-weighted average treatment effect (%s) of targeting %s = %s by %s on %s", target, treatment, treated_level, score_col, outcome_text)
pct <- sprintf("%.0f%%", conf * 100)
summary <- paste0(
sprintf("Ranking by %s, the %s rank-weighted treatment effect is %s (%s CI [%s, %s], %s). ", score_col, target, cs_fmt_num(rate), pct,
cs_fmt_num(ci_low), cs_fmt_num(ci_high), cs_fmt_p(p_value)),
sprintf("The top 10%% of the ranking shows an uplift of %s against an average effect of %s; the Qini coefficient is %.4f.",
if (!is.null(tops[[1]])) cs_fmt_num(tops[[1]]) else "—", cs_fmt_num(ate), cur$qini_coefficient))
values <- list(estimate = rate, se = se, ci_low = ci_low, ci_high = ci_high, z = if (se > 0) rate / se else NULL, p_value = p_value,
n = n, n_treated = n_treated, n_control = n_control, propensity = p, ate = ate,
qini_coefficient = cur$qini_coefficient, auuc = cur$auuc, auuc_random = cur$auuc_random)
values["uplift_top_10"] <- list(tops[[1]])
values["uplift_top_20"] <- list(tops[[2]])
values["uplift_top_30"] <- list(tops[[3]])
values <- c(values, list(target = target, estimand = sprintf("RATE (%s)", target), effect_label = effect_label, claim_level_max = "L4",
treated_level = treated_level, control_level = control_level))
x <- cur$x
cs_publish(list(
method = "causal.uplift",
methodVersion = "1.0.2",
title = sprintf("Uplift evaluation of %s", score_col),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = sprintf("RATE (%s)", target), value = rate),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "p_value", label = "p", value = p_value, format = "p"),
list(key = "qini_coefficient", label = "Qini coefficient", value = cur$qini_coefficient),
list(key = "auuc", label = "AUUC", value = cur$auuc)),
tables = list(list(key = "top", title = "Uplift in the top of the ranking", columns = list(
list(key = "share", label = "Top share targeted", type = "string"), list(key = "uplift", label = "Uplift (treated − control)", type = "number")),
rows = c(lapply(1:3, function(i) list(share = sprintf("%d%%", c(10, 20, 30)[i]), uplift = tops[[i]])), list(list(share = "All (ATE)", uplift = ate))))),
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(sprintf("RATE standard error from %d bootstrap resamples (seed %d); curves computed over tied scores as blocks.", length(boot), seed)),
charts = list(cs_chart("qini", "qini-curve", "Qini curve", list(
fraction = cs_col("Share targeted", c(x, x)),
gain = cs_col("Incremental outcomes", c(cur$qini, cur$random_qini)),
curve = cs_col("Curve", c(rep("model", length(x)), rep("random", length(x))), kind = "categorical")))),
values = values
))
Ranking by uplift_score, the AUTOC rank-weighted treatment effect is 0.06 (95% CI [0.01, 0.11], p = .018). The top 10% of the ranking shows an uplift of 0.12 against an average effect of −0.01; the Qini coefficient is 0.0074.
- RATE (AUTOC)
- 0.0594
- 95% CI
- [0.0102, 0.1085]
- p
- .018
- Qini coefficient
- 0.0074
- AUUC
- 0.0120
Assumptions
- Randomized treatment — Assumes treatment was randomized with probability 0.501; with confounded treatment use doubly robust scores instead.
- Score ranks effects — Targeting by the score beats random targeting (the RATE interval excludes 0).
Uplift in the top of the ranking
| Top share targeted | Uplift (treated − control) |
|---|---|
| 10% | 0.1200 |
| 20% | 0.0779 |
| 30% | 0.0416 |
| All (ATE) | −0.0053 |
- RATE standard error from 200 bootstrap resamples (seed 42); curves computed over tied scores as blocks.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Uplift evaluation (Qini, AUUC, RATE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.uplift 1.0.2 · spec 76ee2df503c4fb8e
# Dataset: c2_uplift (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.causal import uplift as csu
from codesplash.causal import weighting as csw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c2_uplift.parquet", columns=["converted", "offer", "uplift_score"])
n_input = len(df)
df["converted"] = pd.Categorical(df["converted"], categories=["false", "true"]) # stored level order
df["offer"] = pd.Categorical(df["offer"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["converted", "offer", "uplift_score"]) # listwise deletion over the analysis columns
df["converted"] = df["converted"].cat.remove_unused_categories()
df["offer"] = df["offer"].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, ["converted", "offer", "uplift_score"]) # infinite values stop the run (registry/errors.yaml)
# %% Treatment, outcome and score
treatment = "offer"
outcome = "converted"
score_col = "uplift_score"
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same bootstrap resamples
t, treated_level, control_level = csw.treatment_indicator(df, treatment, None)
y, event_level = csw.outcome_vector(df, outcome)
score = df[score_col].to_numpy(dtype=float)
if np.unique(score).size < 2: # a constant score ranks nobody: every curve is the random line
cs.cs_error("CS_E_CONSTANT", column=score_col)
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
p_opt = None
p = float(t.mean()) if p_opt is None else float(p_opt)
target = "AUTOC" # AUTOC | QINI
B = int(200)
# %% Curves and RATE (sklift curve definitions; grf's RATE estimator with IPW scores)
cur = csu.curves(y, t, score)
gamma = csu.ipw_scores(y, t, p)
rate = csu.rate(gamma, score, target)
boot = csu.rate_bootstrap(y, t, score, p_opt, target, B, seed)
boot = boot[~np.isnan(boot)]
se = float(np.std(boot, ddof=1))
ci_low, ci_high, p_value = csu.normal_ci(rate, se, conf)
ate = float(y[t == 1].mean() - y[t == 0].mean())
tops = {q: csu.uplift_at(y, t, score, q / 100) for q in (10, 20, 30)}
# %% Checks
checks = [{"id": "randomization", "label": "Randomized treatment", "status": "info",
"detail": f"Assumes treatment was randomized with probability {p:.3f}; with confounded treatment use doubly robust scores instead."},
{"id": "ranking", "label": "Score ranks effects", "status": "pass" if ci_low > 0 else "concern",
"detail": ("Targeting by the score beats random targeting (the RATE interval excludes 0)." if ci_low > 0
else "The RATE interval includes 0: the score may not rank treatment effects better than chance.")}]
# %% Result
effect_label = f"Rank-weighted average treatment effect ({target}) of targeting {treatment} = {treated_level} by {score_col} on {outcome_text}"
pct = f"{conf:.0%}"
summary = (
f"Ranking by {score_col}, the {target} rank-weighted treatment effect is {cs.fmt_num(rate)} ({pct} CI [{cs.fmt_num(ci_low)}, "
f"{cs.fmt_num(ci_high)}], {cs.fmt_p(p_value)}). The top 10% of the ranking shows an uplift of "
f"{cs.fmt_num(tops[10]) if tops[10] is not None else '—'} against an average effect of {cs.fmt_num(ate)}; the Qini coefficient is "
f"{cur['qini_coefficient']:.4f}."
)
values = {
"estimate": rate, "se": se, "ci_low": ci_low, "ci_high": ci_high, "z": rate / se if se > 0 else None, "p_value": p_value,
"n": n, "n_treated": n_treated, "n_control": n_control, "propensity": p, "ate": ate,
"qini_coefficient": cur["qini_coefficient"], "auuc": cur["auuc"], "auuc_random": cur["auuc_random"],
"uplift_top_10": tops[10], "uplift_top_20": tops[20], "uplift_top_30": tops[30], "target": target,
"estimand": f"RATE ({target})", "effect_label": effect_label, "claim_level_max": "L4",
"treated_level": treated_level, "control_level": control_level,
}
x = list(cur["x"])
cs.publish({
"method": "causal.uplift",
"methodVersion": "1.0.2",
"title": f"Uplift evaluation of {score_col}",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": f"RATE ({target})", "value": rate},
{"key": "ci", "label": f"{pct} CI", "value": [ci_low, ci_high]},
{"key": "p_value", "label": "p", "value": p_value, "format": "p"},
{"key": "qini_coefficient", "label": "Qini coefficient", "value": cur["qini_coefficient"]},
{"key": "auuc", "label": "AUUC", "value": cur["auuc"]},
],
"tables": [{"key": "top", "title": "Uplift in the top of the ranking", "columns": [
{"key": "share", "label": "Top share targeted", "type": "string"}, {"key": "uplift", "label": "Uplift (treated − control)", "type": "number"}],
"rows": [{"share": f"{q}%", "uplift": tops[q]} for q in (10, 20, 30)] + [{"share": "All (ATE)", "uplift": ate}]}],
"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": [f"RATE standard error from {boot.size} bootstrap resamples (seed {seed}); curves computed over tied scores as blocks."],
"charts": [cs.chart(
"qini", "qini-curve", "Qini curve",
{"fraction": cs.col("Share targeted", x + x),
"gain": cs.col("Incremental outcomes", list(cur["qini"]) + list(cur["random_qini"])),
"curve": cs.col("Curve", ["model"] * len(x) + ["random"] * len(x), kind="categorical")},
)],
"values": values,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
The curve shows the extra conversions from treating the top share of customers by score. The diagonal is random targeting, and the area between them measures the score's value.
This uses randomized data, so it reaches L4. An uplift evaluation is only as trustworthy as the treatment assignment behind it.
Check your understanding
CheckpointCheck yourself
A model predicts purchase probability very well. Should you use it to choose who gets a coupon?
Show the answer
Answer: b
Sure buyers would buy anyway, so the coupon is wasted on them. Target by estimated effect, and validate it on randomized data.
Check yourself
You have many control units and few treated ones. Which learner is designed for that?
Show the answer
Answer: c
The X-learner borrows from the larger arm and weights by propensity, which suits unbalanced arms.
Check yourself
A causal forest shows much larger effects for one segment. What should you do next?
Show the answer
Answer: b
Forests search across many splits, so a striking subgroup is partly a product of that search. Confirm it before you act on it.
Try it
In the appIn the Causal studio's Design step, answer yes when asked whether you want to know how the effect varies across units. That adds causal forests and meta-learners to the estimators.
import pandas as pd
from econml.grf import CausalForest
df = pd.read_csv("observational.csv").dropna(subset=["x1", "x2", "outcome"])
X = df[["x1", "x2"]].to_numpy()
cf = CausalForest(n_estimators=2000, random_state=1).fit(
X, df["treated"].astype(int), df["outcome"]
)
effects = cf.predict(X).ravel()
print(pd.Series(effects).describe(percentiles=[0.1, 0.5, 0.9]))library(grf)
df <- na.omit(read.csv("observational.csv")[, c("treated", "x1", "x2", "outcome")])
X <- as.matrix(df[, c("x1", "x2")])
cf <- causal_forest(X, df$outcome, as.integer(as.logical(df$treated)), num.trees = 2000, seed = 1)
average_treatment_effect(cf)
quantile(predict(cf)$predictions, c(0.1, 0.5, 0.9))These scripts use each library's own forest, so their numbers differ from CodeSplash's.
Recap
Recap- Predicting an outcome isn't predicting an effect.
- Causal forests and meta-learners estimate how effects vary, under the same assumptions as the average effect.
- Validate in groups, since one person's effect is never seen.
- Qini and RATE test whether a score finds the people who respond, and they're most credible on randomized data.
Concepts in this lesson