CCausal inference · causal.doubly_robust
Doubly robust estimation (AIPW with cross-fitting)
What is the average effect of a treatment, combining an outcome model and a propensity model so either one may be wrong?
Augmented inverse-probability weighting (AIPW): out-of-fold outcome models under treatment and control plus a propensity model, combined into the efficient doubly robust estimator of the ATE or ATT with an influence-function standard error. Nuisance models are linear/logistic regressions or LightGBM, cross-fitted on folds drawn from a shared random stream so Python and R fit identical models. Reports potential-outcome means, nuisance quality (out-of-fold R² and propensity AUC), overlap and clipping checks, and saves the per-row scores.
A real result
Example “Ate glm”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
With linear/logistic regression nuisance models cross-fitted on 5 folds, the doubly robust ATE of true vs false on outcome is 1.90 (95% CI [1.75, 2.05], p < .001). Estimated mean outcome: 5.91 with and 4.01 without treatment.
- ATE (AIPW)
- 1.901
- 95% CI
- [1.755, 2.047]
- p
- < .001
- Propensity AUC
- 0.7271
Plots
View data
| treated | Propensity score |
|---|---|
| false | 0.3687 |
| true | 0.1969 |
| false | 0.1500 |
| true | 0.3333 |
| true | 0.4886 |
| false | 0.2505 |
| true | 0.7188 |
| false | 0.6236 |
| true | 0.8281 |
| true | 0.7649 |
| true | 0.5322 |
| false | 0.1686 |
| true | 0.5297 |
| false | 0.1807 |
| false | 0.2816 |
| false | 0.3086 |
| false | 0.3450 |
| false | 0.6475 |
| false | 0.5256 |
| true | 0.8318 |
| true | 0.5079 |
| true | 0.7949 |
| false | 0.3279 |
| true | 0.2440 |
| true | 0.4820 |
| true | 0.7046 |
| false | 0.1339 |
| false | 0.2998 |
| false | 0.3937 |
| true | 0.5131 |
| false | 0.3526 |
| false | 0.2450 |
| false | 0.4073 |
| false | 0.2706 |
| false | 0.2476 |
| false | 0.5816 |
| false | 0.4544 |
| false | 0.3147 |
| true | 0.5276 |
| false | 0.2756 |
| false | 0.1122 |
| false | 0.4321 |
| true | 0.4053 |
| true | 0.5059 |
| true | 0.5319 |
| false | 0.3013 |
| false | 0.3244 |
| false | 0.1273 |
| false | 0.1761 |
| true | 0.2869 |
| false | 0.2210 |
| false | 0.2416 |
| false | 0.4770 |
| false | 0.0957 |
| true | 0.3640 |
| false | 0.4559 |
| false | 0.2365 |
| true | 0.6534 |
| false | 0.2744 |
| true | 0.5373 |
First 60 of 1185 rows.
Assumptions
- Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.030, 0.930].
- Clipped propensity scores — 0 of 1185 out-of-fold propensity scores were 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.
Doubly robust estimate
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATE (true − false) | 1.901 | 0.0744 | 1.755 | 2.047 |
| Mean outcome, true | 5.909 | — | — | — |
| Mean outcome, false | 4.009 | — | — | — |
Influence-function standard error; nuisance predictions are out of fold (cross-fitting).
Nuisance models (out of fold)
| Model | Metric | Value |
|---|---|---|
| Outcome | true | R² | 0.8712 |
| Outcome | false | R² | 0.7617 |
| Propensity | AUC | 0.7271 |
- 15 of 1200 rows were left out because a value was missing.
- Estimand: average treatment effect. Folds from seed 42; propensities clipped to [0.01, 0.99].
With linear/logistic regression nuisance models cross-fitted on 5 folds, the doubly robust ATE of true vs false on outcome is 1.90 (95% CI [1.75, 2.05], p < .001). Estimated mean outcome: 5.91 with and 4.01 without treatment.
- ATE (AIPW)
- 1.901
- 95% CI
- [1.755, 2.047]
- p
- < .001
- Propensity AUC
- 0.7271
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Overlap (positivity) — 0.3% of rows have propensity scores below .05 or above .95; 0.3% lie outside the common support [0.030, 0.930].
- Clipped propensity scores — 0 of 1185 out-of-fold propensity scores were 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.
Doubly robust estimate
| Quantity | Estimate | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| ATE (true − false) | 1.901 | 0.0744 | 1.755 | 2.047 |
| Mean outcome, true | 5.909 | — | — | — |
| Mean outcome, false | 4.009 | — | — | — |
Influence-function standard error; nuisance predictions are out of fold (cross-fitting).
Nuisance models (out of fold)
| Model | Metric | Value |
|---|---|---|
| Outcome | true | R² | 0.8712 |
| Outcome | false | R² | 0.7617 |
| Propensity | AUC | 0.7271 |
- 15 of 1200 rows were left out because a value was missing.
- Estimand: average treatment effect. Folds from seed 42; propensities clipped to [0.01, 0.99].
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
- Ate glmc2_obs · covariates: x1, x2, segment, member, income (k) · outcome: outcome · treatment: treated
- Att lightgbmc2_lalonde · covariates: age, educ, race, married, nodegree, re74, re75 · outcome: earnings 1978 · treatment: treat
- Binary outcome glmc2_obs · covariates: x1, 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 inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?
- Causal ML (uplift modeling) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Outcomenumeric / boolean · 1 column
- Numeric, or yes/no (the effect is then a difference in proportions).
- Treatmentboolean / categorical · 1 column · 2–2 levels
- Marks which rows received the treatment (yes/no, or a level that means treated).
- Confounders (covariates)numeric / categorical / boolean · 1–60 columns · 2–30 levels
- Pre-treatment variables that affect both treatment and outcome.
Choices you make
hypothesis
- Treated groupdefault —
Default: the second stored level (true for yes/no columns).
- Estimanddefault ATE
Whose average effect you want: everyone (ATE), the treated (ATT), the controls (ATC) or the overlap population (ATO).
- ATE — everyone(default) — The average effect if everyone were treated versus no one; pick it when a policy could reach everyone.
- ATT — the treated — The average effect on those actually treated; pick it to judge a program for the people who got it.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Nuisance modelsdefault glm
Models for the outcome and the propensity score: linear/logistic regression or gradient boosting.
- Linear and logistic regression(default) — Fits linear and logistic models; transparent, and steady in small samples.
- LightGBM (gradient boosting) — Fits gradient-boosted trees; pick it for nonlinear confounding with plenty of rows.
- Cross-fitting foldsdefault 5
Rows are split into this many parts; each part's nuisance predictions come from models fit on the others (cross-fitting).
- Clip propensity scores atdefault 0.01
Scores are limited to [clip, 1 − clip] in the estimator.
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)
Few clipped propensity scores
Many clipped scores mean the treated and controls barely overlap.
No unmeasured confounding
What it reports
- Tests: Doubly robust treatment effect
- 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.
- n_treated
- How many independent units the analysis used; it sets precision and power.
- n_control
- How many independent units the analysis used; it sets precision and power.
- mu_treated
- What a unit's outcome would be under one treatment; you only ever see one of them per unit.
- mu_control
- What a unit's outcome would be under one treatment; you only ever see one of them per unit.
- 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.
- n_clipped
- How many independent units the analysis used; it sets precision and power.
- ps_auc
- The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
- 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.
- nuisance
- Models used for the outcome and the propensity score: glm (linear and logistic regression) or lightgbm (gradient boosting).
- folds
- Rotates which part of the data is held out, so every row is used for both training and validation.
- 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.
Per group, level or term: outcome_r2_treated, outcome_r2_control
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
- Folds come from the portable Wichmann–Hill stream; nuisances are the same Newton logistic / least-squares fits or the shared LightGBM core (deterministic, one thread, identical parameters), so out-of-fold predictions agree to rounding. EconML's LinearDRLearner / DoubleML's IRM are classic equivalents with their own random folds.
The exact script CodeSplash ran for example “Ate glm” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Doubly robust estimation (AIPW with cross-fitting)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.doubly_robust 1.0.1 · spec cd7f15630ccbe7b7
# 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
import codesplash as cs
from codesplash.causal import dr as csdr
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}"
estimand = "ATE" # ATE | ATT
nuisance = "glm" # glm | lightgbm
k = int(5)
clip = 0.01
params = {
"n_estimators": 200, "learning_rate": 0.05,
"num_leaves": 15, "min_child_samples": 20,
}
# %% Cross-fitted nuisance models (folds from the shared random stream: R uses the same folds)
folds = csdr.fold_ids(n, k, seed)
cf = csdr.crossfit(X, t, y, folds, nuisance, params, seed, binary_outcome=event_level is not None)
res = csdr.aipw(y, t, cf["mu1"], cf["mu0"], cf["e"], estimand, conf, clip)
e = cf["e"]
ps_auc = csdr.auc(t, e)
def r2(obs, pred):
return float(1 - np.sum((obs - pred) ** 2) / np.sum((obs - obs.mean()) ** 2))
values = {"outcome_r2_treated": r2(y[t == 1], cf["mu1"][t == 1]), "outcome_r2_control": r2(y[t == 0], cf["mu0"][t == 0])}
# %% Checks
checks = [csw.overlap_check(e, t)]
share_clipped = res["n_clipped"] / n
checks.append({"id": "clipping", "label": "Clipped propensity scores", "status": "pass" if share_clipped <= 0.02 else "concern" if share_clipped <= 0.1 else "fail",
"detail": f"{res['n_clipped']} of {n} out-of-fold propensity scores were clipped to [{clip:g}, {1 - clip:g}]."})
checks.append(csw.no_confounding_check())
# %% Per-row scores (artifact)
out = cs_out_dir("target/academy-parity/run-953/causal.doubly_robust/ate-glm/out-python")
ec = np.clip(e, clip, 1 - clip)
pseudo = cf["mu1"] - cf["mu0"] + t * (y - cf["mu1"]) / ec - (1 - t) * (y - cf["mu0"]) / (1 - ec)
pd.DataFrame({"row": df.index.to_numpy(dtype=np.int64), "fold": folds, "propensity": e, "mu_treated": cf["mu1"],
"mu_control": cf["mu0"], "aipw_score": pseudo}).to_parquet(os.path.join(out, "scores.parquet"), index=False)
# %% Result
est_text = csw.ESTIMAND_TEXT[estimand]
effect_label = f"{est_text[0].upper()}{est_text[1:]} of {contrast_text} on {outcome_text}"
pct = f"{conf:.0%}"
nname = "LightGBM" if nuisance == "lightgbm" else "linear/logistic regression"
summary = (
f"With {nname} nuisance models cross-fitted on {k} folds, the doubly robust {estimand} of {treated_level} vs {control_level} "
f"on {outcome_text} is {cs.fmt_num(res['estimate'])} ({pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], "
f"{cs.fmt_p(res['p_value'])}). Estimated mean outcome: {cs.fmt_num(res['mu_treated'])} with and {cs.fmt_num(res['mu_control'])} without treatment."
)
values.update({
"estimate": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"], "z": res["z"],
"p_value": res["p_value"], "n": n, "n_treated": n_treated, "n_control": n_control, "mu_treated": res["mu_treated"],
"mu_control": res["mu_control"], "estimand": estimand, "effect_label": effect_label, "claim_level_max": "L2",
"n_clipped": res["n_clipped"], "ps_auc": ps_auc, "ps_min": float(e.min()), "ps_max": float(e.max()), "nuisance": nuisance,
"folds": k, "treated_level": treated_level, "control_level": control_level,
})
cs.publish({
"method": "causal.doubly_robust",
"methodVersion": "1.0.1",
"title": f"Doubly robust estimate ({estimand}, AIPW)",
"engine": cs.engine_info("numpy", "pandas", "scipy", *(["lightgbm"] if nuisance == "lightgbm" else [])),
"n": n,
"summary": summary,
"statistics": [
{"key": "estimate", "label": f"{estimand} (AIPW)", "value": res["estimate"]},
{"key": "ci", "label": f"{pct} CI", "value": [res["ci_low"], res["ci_high"]]},
{"key": "p_value", "label": "p", "value": res["p_value"], "format": "p"},
{"key": "ps_auc", "label": "Propensity AUC", "value": ps_auc},
],
"tables": [
{"key": "effect", "title": "Doubly robust estimate", "columns": [
{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "ci_low", "label": f"{pct} CI low", "type": "number"},
{"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": [
{"quantity": f"{estimand} ({treated_level} − {control_level})", "value": res["estimate"], "se": res["se"], "ci_low": res["ci_low"], "ci_high": res["ci_high"]},
{"quantity": f"Mean outcome, {treated_level}", "value": res["mu_treated"], "se": None, "ci_low": None, "ci_high": None},
{"quantity": f"Mean outcome, {control_level}", "value": res["mu_control"], "se": None, "ci_low": None, "ci_high": None}],
"note": "Influence-function standard error; nuisance predictions are out of fold (cross-fitting)."},
{"key": "nuisance", "title": "Nuisance models (out of fold)", "columns": [
{"key": "model", "label": "Model", "type": "string"}, {"key": "metric", "label": "Metric", "type": "string"},
{"key": "value", "label": "Value", "type": "number"}],
"rows": [
{"model": f"Outcome | {treated_level}", "metric": "R²", "value": values["outcome_r2_treated"]},
{"model": f"Outcome | {control_level}", "metric": "R²", "value": values["outcome_r2_control"]},
{"model": "Propensity", "metric": "AUC", "value": ps_auc}]},
],
"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": "scores", "path": "scores.parquet", "format": "parquet", "title": "Out-of-fold propensity, outcome predictions and AIPW scores"}],
"warnings": warnings,
"notes": [f"Estimand: {est_text}. Folds from seed {seed}; propensities clipped to [{clip:g}, {1 - clip:g}]."],
"charts": [cs.chart(
"overlap", "overlap-density", "Out-of-fold propensity scores by group",
{"score": cs.col("Propensity score", e), "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 “Ate glm” · R version 4.5.1 (2025-06-13)
# Doubly robust estimation (AIPW with cross-fitting)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.doubly_robust 1.0.1 · spec cd7f15630ccbe7b7
# 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)
estimand <- "ATE" # ATE | ATT
nuisance <- "glm" # glm | lightgbm
k <- as.integer(5)
clip <- 0.01
params <- list(n_estimators = 200, learning_rate = 0.05,
num_leaves = 15, min_child_samples = 20)
# %% Cross-fitted nuisance models (folds from the shared random stream: Python uses the same folds)
folds <- cs_causal_folds(n, k, seed)
cf <- cs_causal_crossfit(X, t, y, folds, nuisance, params, seed, binary_outcome = !is.null(event_level))
res <- cs_causal_aipw(y, t, cf$mu1, cf$mu0, cf$e, estimand, conf, clip)
e <- cf$e
ps_auc <- cs_causal_auc(t, e)
r2 <- function(obs, pred) 1 - sum((obs - pred)^2) / sum((obs - mean(obs))^2)
values <- list(outcome_r2_treated = r2(y[t == 1], cf$mu1[t == 1]), outcome_r2_control = r2(y[t == 0], cf$mu0[t == 0]))
# %% Checks
share_clipped <- res$n_clipped / n
checks <- list(
cs_causal_overlap_check(e, t),
list(id = "clipping", label = "Clipped propensity scores", status = if (share_clipped <= 0.02) "pass" else if (share_clipped <= 0.1) "concern" else "fail",
detail = sprintf("%d of %d out-of-fold propensity scores were clipped to [%s, %s].", res$n_clipped, n, sprintf("%g", clip), sprintf("%g", 1 - clip))),
cs_causal_no_confounding_check())
# %% Per-row scores (artifact)
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.doubly_robust/ate-glm/out-r")
ec <- pmin(pmax(e, clip), 1 - clip)
pseudo <- cf$mu1 - cf$mu0 + t * (y - cf$mu1) / ec - (1 - t) * (y - cf$mu0) / (1 - ec)
nanoparquet::write_parquet(data.frame(row = as.integer(rownames(df)) - 1L, fold = folds, propensity = e, mu_treated = cf$mu1,
mu_control = cf$mu0, aipw_score = pseudo), file.path(out, "scores.parquet"))
# %% Result
est_text <- if (estimand == "ATT") "average treatment effect on the treated" else "average treatment effect"
effect_label <- sprintf("%s%s of %s on %s", toupper(substr(est_text, 1, 1)), substr(est_text, 2, nchar(est_text)), contrast_text, outcome_text)
pct <- sprintf("%.0f%%", conf * 100)
nname <- if (nuisance == "lightgbm") "LightGBM" else "linear/logistic regression"
summary <- paste0(
sprintf("With %s nuisance models cross-fitted on %d folds, the doubly robust %s of %s vs %s on %s is %s (%s CI [%s, %s], %s). ",
nname, k, estimand, treated_level, control_level, outcome_text, cs_fmt_num(res$estimate), pct, cs_fmt_num(res$ci_low),
cs_fmt_num(res$ci_high), cs_fmt_p(res$p_value)),
sprintf("Estimated mean outcome: %s with and %s without treatment.", cs_fmt_num(res$mu_treated), cs_fmt_num(res$mu_control)))
values <- c(values, list(
estimate = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high, z = res$z, p_value = res$p_value,
n = n, n_treated = n_treated, n_control = n_control, mu_treated = res$mu_treated, mu_control = res$mu_control,
estimand = estimand, effect_label = effect_label, claim_level_max = "L2", n_clipped = res$n_clipped, ps_auc = ps_auc,
ps_min = min(e), ps_max = max(e), nuisance = nuisance, folds = k, treated_level = treated_level, control_level = control_level))
cs_publish(list(
method = "causal.doubly_robust",
methodVersion = "1.0.1",
title = sprintf("Doubly robust estimate (%s, AIPW)", estimand),
engine = do.call(cs_engine_info, as.list(c("stats", "nanoparquet", if (nuisance == "lightgbm") "lightgbm"))),
n = n,
summary = summary,
statistics = list(
list(key = "estimate", label = sprintf("%s (AIPW)", estimand), value = res$estimate),
list(key = "ci", label = paste(pct, "CI"), value = c(res$ci_low, res$ci_high)),
list(key = "p_value", label = "p", value = res$p_value, format = "p"),
list(key = "ps_auc", label = "Propensity AUC", value = ps_auc)),
tables = list(
list(key = "effect", title = "Doubly robust estimate", columns = list(
list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "ci_low", label = paste(pct, "CI low"), type = "number"),
list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
rows = list(
list(quantity = sprintf("%s (%s − %s)", estimand, treated_level, control_level), value = res$estimate, se = res$se, ci_low = res$ci_low, ci_high = res$ci_high),
list(quantity = sprintf("Mean outcome, %s", treated_level), value = res$mu_treated, se = NULL, ci_low = NULL, ci_high = NULL),
list(quantity = sprintf("Mean outcome, %s", control_level), value = res$mu_control, se = NULL, ci_low = NULL, ci_high = NULL)),
note = "Influence-function standard error; nuisance predictions are out of fold (cross-fitting)."),
list(key = "nuisance", title = "Nuisance models (out of fold)", columns = list(
list(key = "model", label = "Model", type = "string"), list(key = "metric", label = "Metric", type = "string"),
list(key = "value", label = "Value", type = "number")),
rows = list(list(model = sprintf("Outcome | %s", treated_level), metric = "R²", value = values$outcome_r2_treated),
list(model = sprintf("Outcome | %s", control_level), metric = "R²", value = values$outcome_r2_control),
list(model = "Propensity", metric = "AUC", value = ps_auc)))),
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 = "scores", path = "scores.parquet", format = "parquet", title = "Out-of-fold propensity, outcome predictions and AIPW scores")),
warnings = warnings,
notes = list(sprintf("Estimand: %s. Folds from seed %d; propensities clipped to [%s, %s].", est_text, seed, sprintf("%g", clip), sprintf("%g", 1 - clip))),
charts = list(cs_chart("overlap", "overlap-density", "Out-of-fold propensity scores by group", list(
score = cs_col("Propensity score", e), group = cs_col(treatment, ifelse(t == 1, treated_level, control_level), kind = "categorical")))),
values = values
))
Sources
- Robins, J. M., Rotnitzky, A., & Zhao, L. P. (1994). Estimation of regression coefficients when some regressors are not always observed. JASA, 89, 846–866.
- Glynn, A. N., & Quinn, K. M. (2010). An introduction to the augmented inverse propensity weighted estimator. Political Analysis, 18, 36–56.
- Chernozhukov, V., et al. (2018). Double/debiased machine learning for treatment and structural parameters. The Econometrics Journal, 21, C1–C68.
From the CodeSplash method registry · causal.doubly_robust v1.0.1.