Applied Health Economics, RWE & HTA
Overview / Module 3 / Day 27
Module 3 · Causal inference for RWE · Day 27 of 100

Heterogeneity and Subgroups

Every HTA committee asks the same follow-up question: does it work better in some patients than others? Subgroups can find where a drug gives the most value. They can also find patterns that are only noise and present them as discoveries. Today you estimate subgroup effects on both scales, learn why the absolute scale is what payers need, test interactions, shrink noisy subgroups, estimate effects with machine learning (double machine learning and a causal forest), and catch the most common subgroup error: testing until something is significant.

▶
Video for Day 27 coming soon

By the end of today you can

  • report subgroup effects on both the relative and the absolute scale, with event counts
  • test interactions instead of comparing p-values between subgroups
  • start with risk-based subgroups and pre-specify the rest
  • cross-fit nuisance models by person and explain why
  • know the winner's curse and report every subgroup I tested

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:30
27.1 Two scales of heterogeneity
0:30–1:10
27.2 Pre-specified subgroups and interaction tests
1:10–1:25
Break
1:25–1:55
27.3 Risk-based subgroups
1:55–2:40
27.4 Double machine learning
2:40–2:55
Break
2:55–3:35
27.5 How the effect varies: DR-learner and causal forest
3:35–4:00
27.6 Truth check
4:00–4:20
27.7 Twenty-two subgroups
4:20–4:50
27.8 Mini-project: the subgroup slide
4:50–5:00
27.9 Save your work
5:00–5:30
Bloc français

In this lesson

27.1 Two scales of heterogeneity (30 min)

An effect can vary on the relative scale (the risk ratio differs between groups) or on the absolute scale (the risk difference differs). They are not the same question. Suppose Renavex lowers everyone's risk of kidney failure by 25%. A patient with a 20% baseline risk gains 5 percentage points; a patient with 0.4% gains 0.1. The ratio is the same, the benefit is fifty times larger.

Payers and economic models need the absolute scale: QALYs and costs follow from events avoided, not from ratios. Biology often looks more constant on the relative scale. So expect constant ratios and very different differences, and report both. The number needed to treat (NNT = 1 / risk difference) makes the absolute scale concrete.

Everything today uses the Day 24–25 tools: the propensity score, the outcome model, and AIPW for the effect in starters, within each subgroup.

FEATURES = ["egfr", "albuminuria", "sglt2", "age", "male", "qc", "nephrology_care", "heart_failure", "copd",
            "prior_stays", "trial"]
SUBGROUPS = {"eGFR < 30": "egfr < 30", "eGFR 30-44": "egfr >= 30 and egfr < 45", "eGFR >= 45": "egfr >= 45",
             "albuminuria": "albuminuria == 1", "no albuminuria": "albuminuria == 0",
             "Quebec": "qc == 1", "Ontario": "qc == 0", "age < 70": "age < 70", "age >= 70": "age >= 70"}

def subgroup_effects(t, e, q1, q0, subgroups=SUBGROUPS, estimand="att"):
    """AIPW within each subgroup (nuisance models fitted once, on everyone): risks, risk ratio with CI,
    risk difference, and the number of starters' events behind it."""
    rows = []
    for name, q in subgroups.items():
        g = t.eval(q).to_numpy()
        starters_events = int(t.kf24[g & (t.start == 1).to_numpy()].sum())
        with np.errstate(divide="ignore", invalid="ignore"):     # no events: the ratio is not estimable
            r = aipw(t.kf24[g], t.start[g], e[g], q1[g], q0[g], t.person_id[g], estimand)
        ok = starters_events > 0
        rows.append({"subgroup": name, "person_trials": int(g.sum()), "starts": int(t.start[g].sum()),
                     "events_in_starters": starters_events, "risk_start": r["r1"], "risk_no_start": r["r0"],
                     "rd": r["r1"] - r["r0"], "rr": r["rr"] if ok else np.nan, "lo": r["lo"] if ok else np.nan,
                     "hi": r["hi"] if ok else np.nan, "se_log": r["se_log"] if ok else np.nan})
    return pd.DataFrame(rows)

27.2 Pre-specified subgroups and interaction tests (40 min)

The protocol (Day 22) named four subgroup variables in advance: eGFR band, albuminuria, province and age. Here are the subgroup effects:

"""Day 27.2: subgroup effects (AIPW, effect in starters) on both scales, with interaction tests."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.dr import outcome_model  # noqa: E402
from corridor.hte import interaction_p, subgroup_effects  # noqa: E402
from corridor.ps import fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
s = subgroup_effects(t, e, q1, q0)
s.to_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "docs", "subgroups_att.csv"), index=False)
show = s.assign(risk_no_start=(100 * s.risk_no_start).round(2), rd=(100 * s.rd).round(2), rr=s.rr.round(2),
                ci=[f"{lo:.2f}-{hi:.2f}" if np.isfinite(lo) else "not estimable" for lo, hi in zip(s.lo, s.hi)])
print(show[["subgroup", "person_trials", "starts", "events_in_starters", "risk_no_start", "rd", "rr", "ci"]]
      .rename(columns={"risk_no_start": "risk if not (%)", "rd": "difference (% points)"}).to_string(index=False))
r = s.set_index("subgroup")
print("\ninteraction tests (do the risk ratios differ?):")
for a, b in (("eGFR < 30", "eGFR 30-44"), ("albuminuria", "no albuminuria"), ("Quebec", "Ontario"), ("age < 70", "age >= 70")):
    print(f"  {a} vs {b}: p = {interaction_p(r.loc[a], r.loc[b]):.2f}")
      subgroup  person_trials  starts  events_in_starters  risk if not (%)  difference (% points)   rr            ci
     eGFR < 30          10017     379                  38            12.13                  -2.10 0.83     0.61-1.12
    eGFR 30-44          29972     435                   4             1.51                  -0.59 0.61     0.23-1.58
    eGFR >= 45          48901     227                   0             0.06                  -0.06  NaN not estimable
   albuminuria          19738     409                  25             6.06                   0.05 1.01     0.69-1.47
no albuminuria          69152     632                  17             4.41                  -1.72 0.61     0.38-0.97
        Quebec          36402     409                  17             4.12                   0.04 1.01     0.64-1.60
       Ontario          52488     632                  25             5.67                  -1.71 0.70     0.48-1.01
      age < 70          35198     532                  20             5.65                  -1.89 0.67     0.44-1.01
     age >= 70          53692     509                  22             4.44                  -0.12 0.97     0.66-1.44

interaction tests (do the risk ratios differ?):
  eGFR < 30 vs eGFR 30-44: p = 0.55
  albuminuria vs no albuminuria: p = 0.10
  Quebec vs Ontario: p = 0.22
  age < 70 vs age >= 70: p = 0.19

Read the event counts before the ratios. The 1,041 starters had only 42 kidney failures, 38 of them in people with eGFR below 30. In eGFR 45 or more there were none: the ratio is not estimable, and the absolute benefit is close to zero anyway (baseline risk 0.06%). On the absolute scale, nearly all the benefit is in eGFR below 30 (−2.1 points, NNT about 48).

The ratios look different: 1.01 with albuminuria, 0.61 without; 1.01 in Quebec, 0.70 in Ontario. None of the four interaction tests is significant (p from 0.10 to 0.55). An interaction test asks whether two subgroups differ. Comparing "significant in one, not in the other" is the classic error: the 0.61 in people without albuminuria has an interval excluding 1, the 1.01 does not, and the test of the difference gives p = 0.10.

def interaction_p(a, b):
    """Two-sided p-value for 'the log risk ratio differs between subgroups a and b' (rows of subgroup_effects)."""
    z = (np.log(a["rr"]) - np.log(b["rr"])) / np.sqrt(a["se_log"] ** 2 + b["se_log"] ** 2)
    return float(2 * stats.norm.sf(abs(z)))

Why it matters at work: CDA-AMC and INESSS often restrict a reimbursement recommendation to a subgroup (for example, by eGFR or albuminuria). The sponsor's subgroup slide is read closely. Credible subgroup claims are pre-specified, few, supported by an interaction test, and biologically plausible. That is the logic of the ICEMAN criteria.

Where you'll meet this: CDA-AMC reimbursement conditions; the subgroup forest plot of every trial publication; cost-effectiveness by subgroup in Module 5


27.3 Risk-based subgroups (30 min)

The PATH statement (Predictive Approaches to Treatment effect Heterogeneity) recommends starting with risk-based subgroups: rank patients by their predicted risk without treatment, which combines all the prognostic variables into one score, then estimate the effect in each quarter. This uses one pre-specified variable instead of many, and it matches how absolute benefit behaves.

"""Day 27.3: risk-based subgroups (the PATH statement's first step) - quarters of predicted risk without treatment."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.dr import outcome_model  # noqa: E402
from corridor.hte import subgroup_effects  # noqa: E402
from corridor.ps import fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
st = t.start == 1
cuts = np.quantile(q0[st], [0.25, 0.5, 0.75])                    # quarters of the starters' baseline risk
t["risk_q"] = 1 + np.searchsorted(cuts, q0)
groups = {f"Q{k}": f"risk_q == {k}" for k in range(1, 5)}
s = subgroup_effects(t, e, q1, q0, groups)
s["baseline risk (%)"] = [100 * q0[(t.risk_q == k).to_numpy() & st.to_numpy()].mean() for k in range(1, 5)]
s["NNT"] = (-1 / s.rd).where(s.rd < 0).round(0)
print(f"cut points (predicted 24-month risk without Renavex, starters): {', '.join(f'{100 * c:.2f}%' for c in cuts)}")
print(pd.DataFrame({"quarter": s.subgroup, "starts": s.starts, "events": s.events_in_starters,
                    "baseline risk (%)": s["baseline risk (%)"].round(2), "difference (% points)": (100 * s.rd).round(2),
                    "risk ratio": s.rr.round(2), "NNT": s.NNT}).to_string(index=False))
cut points (predicted 24-month risk without Renavex, starters): 0.41%, 2.05%, 6.98%
quarter  starts  events  baseline risk (%)  difference (% points)  risk ratio    NNT
     Q1     261       0               0.12                  -0.08         NaN 1265.0
     Q2     260       2               1.15                  -0.40        0.66  252.0
     Q3     260      10               3.94                   0.49        1.15    NaN
     Q4     260      30              14.82                  -4.12        0.74   24.0

Baseline risk ranges from 0.12% to 14.8% across the starters' quarters. The highest-risk quarter has 30 of the 42 events and a risk difference of −4.1 points (NNT 24). The lowest quarter would need about 1,300 people treated for two years to prevent one kidney failure. The ratios (0.66, 1.15, 0.74) jump around because quarters 2 and 3 have 2 and 10 events.

That table is the start of a cost-effectiveness argument: at the same price, Renavex is far better value in the top risk quarter.

Try it (15 min). Subgroup ratios bounce around because each rests on few events. Shrink them towards the overall effect with empirical Bayes: estimate the between-subgroup variance τ² and pull each subgroup towards the mean by an amount set by its own precision. Compare raw and shrunken ratios with the truth.

Solution
def eb_shrink(log_rr, se):
    """Empirical Bayes: shrink subgroup log risk ratios towards their precision-weighted mean.
    tau^2 by the DerSimonian-Laird moment estimator. Returns (shrunken log RRs, tau^2)."""
    log_rr, se = np.asarray(log_rr, float), np.asarray(se, float)
    w = 1 / se ** 2
    mu = np.sum(w * log_rr) / w.sum()
    q = np.sum(w * (log_rr - mu) ** 2)
    tau2 = max(0.0, (q - (len(log_rr) - 1)) / (w.sum() - np.sum(w ** 2) / w.sum()))
    b = se ** 2 / (se ** 2 + tau2)                              # weight on the overall mean
    return b * mu + (1 - b) * log_rr, tau2
"""Day 27 try it: shrink the subgroup risk ratios towards the overall effect (empirical Bayes)."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402
import numpy as np  # noqa: E402

from corridor.dr import outcome_model  # noqa: E402
from corridor.hte import SUBGROUPS, eb_shrink, subgroup_effects  # noqa: E402
from corridor.ps import fit_ps  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
s = subgroup_effects(t, e, q1, q0).dropna(subset=["rr"])         # as in 27.2; eGFR >= 45 has no events
shrunk, tau2 = eb_shrink(np.log(s.rr), s.se_log)
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int)).merge(tr, on=["person_id", "trial"]).query("start == 1")
true = [d.query(SUBGROUPS[n]).kf24_start.mean() / d.query(SUBGROUPS[n]).kf24_no_start.mean() for n in s.subgroup]
print(f"between-subgroup variance of log ratios (tau^2): {tau2:.4f}")
print(f"{'subgroup':<16}{'raw':>7}{'shrunk':>8}{'truth':>7}")
for n, r, sh, tv in zip(s.subgroup, s.rr, np.exp(shrunk), true):
    print(f"{n:<16}{r:>7.2f}{sh:>8.2f}{tv:>7.2f}")
err = lambda v: np.sqrt(np.mean((np.log(v) - np.log(true)) ** 2))  # noqa: E731
print(f"\nroot mean squared error (log scale): raw {err(s.rr):.3f}, shrunk {err(np.exp(shrunk)):.3f}")
between-subgroup variance of log ratios (tau^2): 0.0000
subgroup            raw  shrunk  truth
eGFR < 30          0.83    0.81   0.77
eGFR 30-44         0.61    0.81   0.80
albuminuria        1.01    0.81   0.75
no albuminuria     0.61    0.81   0.81
Quebec             1.01    0.81   0.74
Ontario            0.70    0.81   0.80
age < 70           0.67    0.81   0.80
age >= 70          0.97    0.81   0.75

root mean squared error (log scale): raw 0.241, shrunk 0.055

The estimated τ² is zero: the subgroups vary no more than chance alone would make them vary, so every subgroup shrinks all the way to the pooled 0.81. The truth agrees that the ratio barely varies (0.74 to 0.81), and the error falls from 0.24 to 0.06 on the log scale. When heterogeneity is real, τ² is larger and the shrinkage is partial. Shrinkage estimates are what Bayesian subgroup analyses report.


27.4 Double machine learning (45 min)

AIPW needs two nuisance models. On Day 25 they were logistic regressions that you specified. Double machine learning (DML) replaces them with flexible learners, here gradient boosting, and adds cross-fitting: split people into five folds, fit both models on four folds, predict on the fifth, and rotate. Every row's predictions come from models that never saw that person, which stops an overfitted model from fitting each row's own noise. AIPW's correction term then protects the estimate from the learners' bias.

def crossfit(t, folds=5, seed=2026, features=FEATURES):
    """Cross-fitted propensity score and outcome predictions with gradient boosting, folds by person:
    every row's predictions come from models that never saw that person. Returns (e, q1, q0)."""
    from sklearn.ensemble import HistGradientBoostingClassifier
    rng = np.random.default_rng(seed)
    people = t.person_id.unique()
    fold_of = dict(zip(people, rng.integers(0, folds, len(people))))
    f = t.person_id.map(fold_of).to_numpy()
    x = t[features].to_numpy(float)
    xs = np.column_stack([x, t.start.to_numpy(float)])
    e, q1, q0 = np.zeros(len(t)), np.zeros(len(t)), np.zeros(len(t))
    for k in range(folds):
        tr, te = f != k, f == k
        kw = dict(max_iter=200, learning_rate=0.05, max_leaf_nodes=15, min_samples_leaf=200, random_state=seed)
        ps = HistGradientBoostingClassifier(**kw).fit(x[tr], t.start.to_numpy()[tr])
        e[te] = ps.predict_proba(x[te])[:, 1]
        om = HistGradientBoostingClassifier(**kw).fit(xs[tr], t.kf24.to_numpy()[tr])
        q1[te] = om.predict_proba(np.column_stack([x[te], np.ones(te.sum())]))[:, 1]
        q0[te] = om.predict_proba(np.column_stack([x[te], np.zeros(te.sum())]))[:, 1]
    return np.clip(e, 0.001, 0.999), q1, q0
"""Day 27.4: double machine learning - cross-fitted gradient boosting for both nuisance models, then AIPW."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.dr import aipw, outcome_model  # noqa: E402
from corridor.hte import crossfit  # noqa: E402
from corridor.ps import c_statistic, fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e_glm = fit_ps(t)
q1g, q0g = outcome_model(t)
e, q1, q0 = crossfit(t)
print(f"propensity score c-statistic: logistic {c_statistic(t.start, e_glm):.3f} (in-sample), boosting {c_statistic(t.start, e):.3f} (cross-fitted)")
print(f"\n{'nuisance models':<34}{'estimand':>9}{'ratio':>7}   95% CI      difference")
for label, args in (("logistic (Day 25)", (e_glm, q1g, q0g)), ("boosting, 5-fold cross-fitted", (e, q1, q0))):
    for est in ("ate", "att"):
        r = aipw(t.kf24, t.start, *args, t.person_id, est)
        print(f"{label:<34}{est.upper():>9}{r['rr']:>7.2f}   {r['lo']:.2f}-{r['hi']:.2f}   {100 * (r['r1'] - r['r0']):+.2f} pts")
propensity score c-statistic: logistic 0.772 (in-sample), boosting 0.762 (cross-fitted)

nuisance models                    estimand  ratio   95% CI      difference
logistic (Day 25)                       ATE   0.62   0.44-0.89   -0.65 pts
logistic (Day 25)                       ATT   0.80   0.60-1.06   -1.03 pts
boosting, 5-fold cross-fitted           ATE   0.67   0.46-0.96   -0.58 pts
boosting, 5-fold cross-fitted           ATT   0.79   0.58-1.06   -1.10 pts

Boosting finds no structure the logistic model missed (c-statistics 0.76 vs 0.77), and the estimates agree: 0.79 vs 0.80 in starters, 0.67 vs 0.62 for everyone eligible. That agreement is the useful result. With ten covariates and good clinical knowledge of their form, a well-specified parametric model is hard to beat. DML earns its keep with hundreds of covariates (all drug classes, all diagnoses), where no one can write the model by hand. Folds are by person: with folds by row, a person's other person-trials would sit in the training data.


27.5 How the effect varies: DR-learner and causal forest (40 min)

Subgroups ask about one variable at a time. To describe how the effect varies with several at once, regress the AIPW pseudo-outcome on covariates. This is the DR-learner. Each row's pseudo-outcome is a noisy, unbiased estimate of its own risk difference. Their average is the AIPW ATE, and their regression on covariates is the best linear projection (BLP) of the effect.

def dr_pseudo(y, a, e, q1, q0):
    """DR-learner pseudo-outcome: its average is the AIPW ATE risk difference, and its regression on
    covariates estimates how the risk difference varies with them."""
    y, a = np.asarray(y, float), np.asarray(a, float)
    return q1 - q0 + a * (y - q1) / e - (1 - a) * (y - q0) / (1 - e)

def blp(target, x, groups):
    """Best linear projection of a (pseudo-)outcome on covariates, SEs clustered by person."""
    import statsmodels.api as sm
    m = sm.OLS(np.asarray(target, float), sm.add_constant(x)).fit(cov_type="cluster",
                                                               cov_kwds={"groups": pd.factorize(groups)[0]})
    return m
"""Day 27.5: how does the risk difference vary with covariates? DR-learner pseudo-outcomes and their best
linear projection (BLP), with person-clustered SEs."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.hte import blp, crossfit, dr_pseudo  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
e, q1, q0 = crossfit(t)
phi = dr_pseudo(t.kf24, t.start, e, q1, q0)
print(f"pseudo-outcome: mean {100 * phi.mean():+.2f} points (the ATE), SD {phi.std():.2f} - each one is very noisy")
x = t[["egfr10", "albuminuria", "age10", "qc"]]
m = blp(phi, x, t.person_id)
print("\nBLP of the risk difference (percentage points; egfr10 = per 10 mL/min LOWER eGFR):")
for k in m.params.index:
    lo, hi = m.conf_int().loc[k]
    print(f"  {k:<12}{100 * m.params[k]:>+7.2f}   ({100 * lo:+.2f} to {100 * hi:+.2f})")
print(f"\njoint test that nothing modifies the difference: p = {m.f_test(np.eye(5)[1:]).pvalue:.3f}")
pseudo-outcome: mean -0.58 points (the ATE), SD 0.66 - each one is very noisy

BLP of the risk difference (percentage points; egfr10 = per 10 mL/min LOWER eGFR):
  const         -1.11   (-1.70 to -0.51)
  egfr10        -0.85   (-1.63 to -0.08)
  albuminuria   +1.15   (-0.10 to +2.41)
  age10         +0.12   (-0.16 to +0.40)
  qc            +0.73   (-0.15 to +1.62)

joint test that nothing modifies the difference: p = 0.028

Each 10 mL/min lower eGFR adds 0.85 points of benefit (95% CI 0.08 to 1.63), the one modifier the data support. The pseudo-outcome's SD (0.66, against a mean of −0.006) shows why per-person estimates are useless one at a time and only their averages can be interpreted.

A causal forest (grf in R) does the same job with trees: it splits people where the treatment effect, not the outcome, differs. It reports the effect in starters, a calibration test and a BLP:

# Day 27: a causal forest (grf) on the sequential trials - clustered by person, effect in starters,
# calibration test and best linear projection.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(grf) })
con <- dbConnect(duckdb(shared_home = FALSE))
t <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/trials.parquet')")
dbDisconnect(con, shutdown = TRUE)
x <- as.matrix(t[, c("egfr", "albuminuria", "sglt2", "age", "male", "qc", "nephrology_care", "heart_failure",
                     "copd", "prior_stays", "trial")])
cf <- causal_forest(x, t$kf24, t$start, clusters = factor(t$person_id), num.trees = 1000, seed = 2026)
for (s in c("all", "treated")) {
  a <- average_treatment_effect(cf, target.sample = s)
  cat(sprintf("risk difference (%s): %+.2f points (%+.2f to %+.2f)\n", s, 100 * a[1], 100 * (a[1] - 1.96 * a[2]),
              100 * (a[1] + 1.96 * a[2])))
}
print(round(test_calibration(cf)[, c(1, 2, 4)], 3))
z <- data.frame(egfr10 = (45 - t$egfr) / 10, albuminuria = t$albuminuria, age10 = (t$age - 70) / 10, qc = t$qc)
b <- best_linear_projection(cf, z)
print(round(100 * b[, 1:2], 2))
risk difference (all): -0.58 points (-0.96 to -0.20)
risk difference (treated): -0.94 points (-2.17 to +0.28)
                               Estimate Std. Error Pr(>t)
mean.forest.prediction            2.898      1.348  0.016
differential.forest.prediction   -0.345      0.595  0.719
            Estimate Std. Error
(Intercept)    -0.89       0.27
egfr10         -0.81       0.33
albuminuria     0.86       0.56
age10           0.06       0.13
qc              0.36       0.39

The forest's effect in starters (−0.94 points) and its BLP (−0.81 per 10 mL/min lower eGFR) agree with the DR-learner. The calibration test asks two questions. Does the mean forest prediction carry signal? Yes (p 0.016; a perfectly calibrated forest has a coefficient of 1, here 2.9 with a wide standard error). Do the forest's predicted differences between people line up with real differences? There is no evidence of that (coefficient −0.35, p 0.72). The forest cannot rank individuals reliably with 42 events. grf also prints a warning that propensity scores go down to 0.002, the overlap problem of Day 24 found on its own.


27.6 Truth check (25 min)

The generator multiplies the hazard of kidney failure by 0.75 in everyone on Renavex: no heterogeneity on the relative scale, and a lot on the absolute scale.

"""Day 27 truth check: subgroup effects in starters, on both scales, and the true BLP of the risk difference."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.db import ROOT  # noqa: E402
from corridor.hte import SUBGROUPS, blp  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int)).merge(tr, on=["person_id", "trial"])
est = pd.read_csv(os.path.join(ROOT, "docs", "subgroups_att.csv")).set_index("subgroup")
print(f"{'subgroup':<16}{'est. ratio':>11}{'true ratio':>11}{'est. diff':>11}{'true diff':>11}   (differences in % points)")
for name, q in SUBGROUPS.items():
    s = d.query(q)
    s = s[s.start == 1]
    t1, t0 = s.kf24_start.mean(), s.kf24_no_start.mean()
    true_rr = f"{t1 / t0:>11.2f}" if t0 > 0 else f"{'-':>11}"
    print(f"{name:<16}{est.rr[name]:>11.2f}{true_rr}{100 * est.rd[name]:>+11.2f}{100 * (t1 - t0):>+11.2f}")
for q in ("prior_stays > 0", "prior_stays == 0"):                    # the 'winner' of the bug of the day
    s = d.query(q)
    s = s[s.start == 1]
    print(f"{q:<16}{'':>11}{s.kf24_start.mean() / s.kf24_no_start.mean():>11.2f}{'':>11}"
          f"{100 * (s.kf24_start.mean() - s.kf24_no_start.mean()):>+11.2f}")
ite = d.kf24_start - d.kf24_no_start
m = blp(ite, d[["egfr10", "albuminuria", "age10", "qc"]], d.person_id)
print("\ntrue BLP of the risk difference (all eligible person-trials, % points):")
print("  " + "   ".join(f"{k} {100 * v:+.2f}" for k, v in m.params.items()))
subgroup         est. ratio true ratio  est. diff  true diff   (differences in % points)
eGFR < 30              0.83       0.77      -2.10      -2.93
eGFR 30-44             0.61       0.80      -0.59      -0.23
eGFR >= 45              nan          -      -0.06      +0.00
albuminuria            1.01       0.75      +0.05      -1.97
no albuminuria         0.61       0.81      -1.72      -0.63
Quebec                 1.01       0.74      +0.04      -1.47
Ontario                0.70       0.80      -1.71      -0.96
age < 70               0.67       0.80      -1.89      -0.94
age >= 70              0.97       0.75      -0.12      -1.38
prior_stays > 0                   0.83                 -1.69
prior_stays == 0                  0.70                 -0.94

true BLP of the risk difference (all eligible person-trials, % points):
  const -0.35   egfr10 -0.76   albuminuria -0.28   age10 +0.01   qc -0.03

The true ratios sit between 0.74 and 0.81 in every subgroup. The estimated ratios ranged from 0.61 to 1.01, so all of the apparent heterogeneity on the ratio scale was noise. The absolute scale is where the truth varies: −2.9 points below eGFR 30, −0.2 at 30–44, 0 at 45 and above. The true BLP (−0.76 points per 10 mL/min) matches the DR-learner (−0.85) and the forest (−0.81). Albuminuria's estimated +1.15 points (less benefit) has the wrong sign; the truth is −0.28. That estimate rested on 25 events and its interval included zero.


27.7 Twenty-two subgroups (20 min)

Bug of the day. A committee member asks whether the drug works in patients with heart failure; then COPD; then men. An analyst tests every split in the data, including twelve meaningless ones (birth month, simulated), and reports the most significant:

"""Day 27 bug of the day: test enough subgroups and one will 'show' that Renavex does not work in it."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.dr import outcome_model  # noqa: E402
from corridor.hte import interaction_p, subgroup_effects  # noqa: E402
from corridor.ps import fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
rng = np.random.default_rng(27)
t["birth_month"] = t.person_id.map(dict(zip(t.person_id.unique(), rng.integers(1, 13, t.person_id.nunique()))))
splits = {"heart failure": "heart_failure == 1", "COPD": "copd == 1", "nephrology care": "nephrology_care == 1",
          "SGLT2 inhibitor": "sglt2 == 1", "male": "male == 1", "hospital stay last year": "prior_stays > 0",
          "trial month 0-5": "trial < 6", "Quebec": "qc == 1", "albuminuria": "albuminuria == 1", "age >= 70": "age >= 70"}
splits.update({f"born in month {m}": f"birth_month == {m}" for m in range(1, 13)})
rows = []
for name, q in splits.items():
    s = subgroup_effects(t, e, q1, q0, {"in": q, "out": f"not ({q})"}).set_index("subgroup")
    if s.events_in_starters.min() == 0:
        continue
    rows.append((name, s.rr["in"], s.rr["out"], interaction_p(s.loc["in"], s.loc["out"])))
rows.sort(key=lambda r: r[3])
print(f"{len(rows)} subgroup splits tested; the five 'most significant':")
for name, a, b, p in rows[:5]:
    print(f"  {name:<26} ratio {a:.2f} in vs {b:.2f} out   p = {p:.3f}")
k = sum(p < 0.05 for *_, p in rows)
print(f"\n{k} of {len(rows)} below 0.05; below 0.05/{len(rows)} (Bonferroni): {sum(p < 0.05 / len(rows) for *_, p in rows)}")
22 subgroup splits tested; the five 'most significant':
  hospital stay last year    ratio 1.30 in vs 0.49 out   p = 0.001
  albuminuria                ratio 1.01 in vs 0.61 out   p = 0.096
  born in month 4            ratio 0.17 in vs 0.88 out   p = 0.103
  born in month 5            ratio 1.32 in vs 0.73 out   p = 0.109
  born in month 8            ratio 1.41 in vs 0.74 out   p = 0.117

1 of 22 below 0.05; below 0.05/22 (Bonferroni): 1

No birth month reaches p < 0.05 this time, but they produce ratios from 0.17 to 1.41 out of pure noise. One split does survive Bonferroni: a hospital stay in the previous year (1.30 vs 0.49, p = 0.001). The truth check (27.6) shows its true ratios are 0.83 vs 0.70. The direction is right, but the size is grossly exaggerated. That is the winner's curse: the most significant of many tests also overstates its effect, because it was selected for being extreme. Prior hospital stays mark frail people, the same people Day 28 finds under-represented among starters.

The rules: pre-specify a few subgroups with a reason, test interactions, correct for multiplicity, shrink, and report all subgroups tested, not only the interesting ones.


27.8 Mini-project: the subgroup slide (30 min)

Draw the subgroup slide for a committee: pre-specified subgroups and risk quarters, with starts and events on every row, ratios with confidence intervals on a log scale, and risk differences alongside.

"""Day 27 mini-project: the subgroup slide for an HTA committee - a forest plot on both scales,
pre-specified subgroups and risk quarters, with event counts."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib  # noqa: E402

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import matplotlib.ticker  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.db import ROOT  # noqa: E402
from corridor.dr import aipw, outcome_model  # noqa: E402
from corridor.hte import SUBGROUPS, subgroup_effects  # noqa: E402
from corridor.ps import fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
cuts = np.quantile(q0[t.start == 1], [0.25, 0.5, 0.75])
t["risk_q"] = 1 + np.searchsorted(cuts, q0)
groups = dict(SUBGROUPS)
groups.update({f"risk quarter {k}": f"risk_q == {k}" for k in range(1, 5)})
s = subgroup_effects(t, e, q1, q0, groups)
overall = aipw(t.kf24, t.start, e, q1, q0, t.person_id, "att")
s = pd.concat([pd.DataFrame([{"subgroup": "All starters", "starts": int(t.start.sum()),
                              "events_in_starters": int(t.kf24[t.start == 1].sum()), "rd": overall["r1"] - overall["r0"],
                              "rr": overall["rr"], "lo": overall["lo"], "hi": overall["hi"]}]), s], ignore_index=True)
y = np.arange(len(s))[::-1]
fig, (a1, a2) = plt.subplots(1, 2, figsize=(10, 6.2), sharey=True, gridspec_kw={"width_ratios": [1.3, 1]})
ok = s.rr.notna()
a1.errorbar(s.rr[ok], y[ok], xerr=[s.rr[ok] - s.lo[ok], s.hi[ok] - s.rr[ok]], fmt="s", color="#3ecf8e", ecolor="#8b8d98", ms=5)
a1.axvline(1, color="black", lw=0.8)
a1.axvline(overall["rr"], color="#3ecf8e", lw=0.8, ls="--")
a1.set_xscale("log")
a1.set_xticks([0.25, 0.5, 1, 2])
a1.set_xticklabels(["0.25", "0.5", "1", "2"])
a1.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
a1.set_xlabel("risk ratio (95% CI), log scale")
a1.set_yticks(y)
a1.set_yticklabels([f"{n}  ({st} starts, {ev} events)" for n, st, ev in zip(s.subgroup, s.starts, s.events_in_starters)], fontsize=8.5)
a2.barh(y, 100 * s.rd, color=["#3ecf8e" if v < 0 else "#e5484d" for v in s.rd], height=0.6)
a2.axvline(0, color="black", lw=0.8)
a2.set_xlabel("risk difference, % points\n(negative = fewer kidney failures)")
for ax in (a1, a2):
    ax.spines[["top", "right"]].set_visible(False)
fig.suptitle("Starting Renavex vs not, 24-month kidney failure, effect in starters (AIPW)", fontsize=10)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day27_forest.png"), dpi=150)
print("wrote figures/day27_forest.png")
print(s[["subgroup", "starts", "events_in_starters"]].assign(rr=s.rr.round(2), rd=(100 * s.rd).round(2)).to_string(index=False))
wrote figures/day27_forest.png
      subgroup  starts  events_in_starters   rr    rd
  All starters    1041                  42 0.80 -1.03
     eGFR < 30     379                  38 0.83 -2.10
    eGFR 30-44     435                   4 0.61 -0.59
    eGFR >= 45     227                   0  NaN -0.06
   albuminuria     409                  25 1.01  0.05
no albuminuria     632                  17 0.61 -1.72
        Quebec     409                  17 1.01  0.04
       Ontario     632                  25 0.70 -1.71
      age < 70     532                  20 0.67 -1.89
     age >= 70     509                  22 0.97 -0.12
risk quarter 1     261                   0  NaN -0.08
risk quarter 2     260                   2 0.66 -0.40
risk quarter 3     260                  10 1.15  0.49
risk quarter 4     260                  30 0.74 -4.12

Subgroup forest plot

Under the figure, write three sentences for the committee: no evidence that the relative effect differs between subgroups; the absolute benefit is concentrated in eGFR below 30 and the top risk quarter; subgroups with fewer than about 10 events should not be interpreted.

27.9 Save your work

python -m pytest -q
git add .
git commit -m "Day 27: subgroups, risk-based heterogeneity, DML and causal forests"

Day 27 checklist

  • I report subgroup effects on both the relative and the absolute scale, with event counts
  • I test interactions instead of comparing p-values between subgroups
  • I start with risk-based subgroups and pre-specify the rest
  • I can cross-fit nuisance models by person and explain why
  • I know the winner's curse and report every subgroup I tested