CCausal inference · causal.forest
Causal forest (heterogeneous treatment effects)
For whom does the treatment work better or worse — how do effects vary with the covariates?
Generalized random forests for conditional average treatment effects (CATE): honest causal forests that split on effect heterogeneity after orthogonalizing outcome and treatment (R grf::causal_forest, Python EconML's CausalForestDML with the same honesty, subsampling and leaf size). Reports the doubly robust average treatment effect with its standard error, the distribution of individual effect estimates (quantiles, share positive), effects by quintile of predicted benefit, variable importance, and saves every row's CATE.
A real result
Example “Obs heterogeneous”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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 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).
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
- Obs heterogeneousc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
- Obs binary smallc2_obs · covariates: x1, segment, member · outcome: outcome · treatment: treated
- Binary outcomec2_obs · covariates: x1, x2, segment, member · outcome: converted · treatment: treated
- 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.
model
- Treesdefault 2000
Rounded up to a multiple of 4 (EconML grows trees in groups of four).
- Minimum rows per leafdefault 5
Smallest number of rows allowed in a leaf. Larger values smooth predictions and reduce overfitting.
- Subsample per treedefault 0.5
Share of rows each tree is grown on (honest splitting uses part of it to estimate effects).
- Honest splittingdefault on
Half of each subsample chooses splits, the other half estimates effects (needed for valid intervals).
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.
No unmeasured confounding
Effect heterogeneity
Individual effect estimates are noisy; compare groups of rows and confirm heterogeneity on new data.
What it reports
- Tests: Average treatment effect (causal forest)
- 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.
- z
- An estimate in standard-error units, compared with the standard normal distribution.
- 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.
- n_trees
- How many independent units the analysis used; it sets precision and power.
- 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.
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-9). Python uses pandas, numpy, scipy, econml, scikit-learn, codesplash; R uses grf, nanoparquet, codesplashr.
Default traps between the two languages
- Same estimand, different implementations: grf's causal forest (R) and EconML's CausalForestDML (Python) differ in nuisance models, splitting rules and random streams. On the fixture the ATEs agree within 1% and the CATE vectors have Spearman rank correlation 0.99 (both correlate ≥ 0.96 with the true effects); spreads and standard errors differ more (within 40%), the tails of the CATE distribution most (10th percentile within 70% when it is near zero), and p-values far below .001 are not compared. The Python average effect uses grf's doubly robust score on EconML's out-of-fold residuals so both engines use the same estimator.
- The overlap check uses each library's own out-of-sample propensity scores (EconML's 5-fold cross-fitted random-forest classifier in Python, grf's out-of-bag W.hat in R): on the fixtures their ranges agree within 20% and the share of extreme scores within 5 points, so the overlap verdict normally agrees.
- Variable importance is each library's own measure (split-frequency depth weighting in grf, impurity reduction in EconML) and is not compared.
The exact script CodeSplash ran for example “Obs heterogeneous” · 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,
})
The exact script CodeSplash ran for example “Obs heterogeneous” · 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
))
Sources
- Wager, S., & Athey, S. (2018). Estimation and inference of heterogeneous treatment effects using random forests. JASA, 113, 1228–1242.
- Athey, S., Tibshirani, J., & Wager, S. (2019). Generalized random forests. Annals of Statistics, 47, 1148–1178.
- Battocchi, K., et al. (2019). EconML: A Python package for ML-based heterogeneous treatment effects estimation.
From the CodeSplash method registry · causal.forest v1.1.1.