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

Propensity Scores: Matching, Weighting and Balance

On Day 22 you adjusted with an outcome model. Today you adjust with a model for the treatment: the probability that a person-trial starts Renavex given its covariates, the propensity score. Two people with the same score are comparable on everything in the model, so you can match on it or weight by it. You will see that matching and three kinds of weights answer three different questions, that balance matters more than the c-statistic, and that putting the strongest predictor of treatment in the model can make the answer worse.

▶
Video for Day 24 coming soon

By the end of today you can

  • fit a propensity score and look at overlap before estimating anything
  • judge the score by balance (SMDs), not by its c-statistic
  • say which estimand matching, ATE, ATT and overlap weights target, and compare each with its own truth
  • report effective sample sizes and the largest weights
  • keep instruments out of the propensity score

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:40
24.1 The propensity score model and overlap
0:40–1:15
24.2 Balance, not the c-statistic
1:15–1:30
Break
1:30–2:05
24.3 Matching
2:05–2:50
24.4 Weighting: three estimands
2:50–3:05
Break
3:05–3:30
24.5 Truth check
3:30–3:50
24.6 The best predictor of treatment
3:50–4:50
24.7 Mini-project: Table 1 for the protocol
4:50–5:00
24.8 Save your work
5:00–5:30
Bloc français

In this lesson

24.1 The propensity score model and overlap (40 min)

The propensity score is e(x) = P(start = 1 | x). Rosenbaum and Rubin showed that if x is enough to remove confounding, so is e(x): one number replaces ten covariates. The model is an ordinary logistic regression. eGFR enters as a natural spline because the doctor's response to a falling eGFR is not linear, and the trial month enters as a factor because Quebec only listed Renavex in February 2026.

PS_COVARIATES = ["egfr", "albuminuria", "sglt2", "age", "male", "qc", "nephrology_care", "heart_failure", "copd",
                 "prior_stays", "trial"]
PS_FORMULA = ("start ~ cr(egfr, df=4) + albuminuria + sglt2 + age10 + male + qc + nephrology_care + heart_failure"
              " + copd + prior_stays + C(trial)")

def fit_ps(t, formula=PS_FORMULA):
    """Logistic propensity score model; returns (model, scores)."""
    m = smf.logit(formula, t).fit(disp=0, method="newton", maxiter=50)
    return m, np.asarray(m.predict(t))
"""Day 24.1-24.2: the propensity score - who starts Renavex in a trial month - and its overlap."""

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 numpy as np  # noqa: E402

from corridor.db import ROOT  # noqa: E402
from corridor.ps import c_statistic, fit_ps  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
m, e = fit_ps(t)
print(f"{len(t):,} person-trials, {int(t.start.sum()):,} starts; c-statistic {c_statistic(t.start, e):.3f}")
print("odds ratios (eGFR enters as a spline, shown by its effect on the score below):")
print(np.exp(m.params.filter(regex="^(albuminuria|sglt2|age10|male|qc|nephrology_care|heart_failure|copd|prior_stays)$")).round(2).to_string())
for a, label in ((1, "starters"), (0, "non-starters")):
    q = np.quantile(e[t.start == a], [0.01, 0.25, 0.5, 0.75, 0.99])
    print(f"{label:<13} propensity score percentiles 1/25/50/75/99: " + " ".join(f"{x:.4f}" for x in q))
print(f"share of non-starters with a score below the lowest 1% of starters: {np.mean(e[t.start == 0] < np.quantile(e[t.start == 1], 0.01)):.1%}")
for egfr in (25, 35, 45, 55):
    d = t.assign(egfr=egfr, albuminuria=1, nephrology_care=1)
    print(f"eGFR {egfr}, albuminuria, nephrologist: mean score {np.asarray(m.predict(d)).mean():.4f}")

fig, ax = plt.subplots(figsize=(6.4, 3.4))
bins = np.logspace(np.log10(e.min()), np.log10(e.max()), 50)
ax.hist(e[t.start == 0], bins=bins, color="#9aa6bf", alpha=0.8, density=True, label="did not start")
ax.hist(e[t.start == 1], bins=bins, color="#3ecf8e", alpha=0.7, density=True, label="started")
ax.set(xscale="log", xlabel="propensity score (log scale)", ylabel="density", title="Overlap of propensity scores")
ax.legend()
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day24_ps_overlap.png"), dpi=130)
88,890 person-trials, 1,041 starts; c-statistic 0.772
odds ratios (eGFR enters as a spline, shown by its effect on the score below):
albuminuria        1.78
sglt2              1.37
age10              0.79
male               1.03
qc                 0.92
nephrology_care    1.72
heart_failure      0.99
copd               1.09
prior_stays        0.99
starters      propensity score percentiles 1/25/50/75/99: 0.0021 0.0105 0.0219 0.0410 0.1080
non-starters  propensity score percentiles 1/25/50/75/99: 0.0012 0.0034 0.0061 0.0136 0.0698
share of non-starters with a score below the lowest 1% of starters: 7.5%
eGFR 25, albuminuria, nephrologist: mean score 0.0598
eGFR 35, albuminuria, nephrologist: mean score 0.0348
eGFR 45, albuminuria, nephrologist: mean score 0.0157
eGFR 55, albuminuria, nephrologist: mean score 0.0090

Propensity scores of starters and non-starters

Starting Renavex in any one month is rare (1,041 starts in 88,890 person-trials), so every score is small: the median starter has 2.2%, the median non-starter 0.6%. The distributions overlap: there are non-starters at every score where there are starters. The reverse is not true. 7.5% of non-starters have a score below almost every starter's: people with good kidney function and no albuminuria, whom nobody would start on Renavex. They matter for one estimand (everyone eligible, 24.4) and not for the others.

The c-statistic of 0.77 says the model discriminates fairly well. That is not its job. Its job is balance.


24.2 Balance, not the c-statistic (35 min)

A propensity score is good if, after matching or weighting, starters and non-starters look alike. The standard measure is the standardized mean difference (SMD): the difference in means divided by the pooled standard deviation, so that eGFR in mL/min and a 0/1 flag sit on one scale. |SMD| below 0.1 is the usual target.

def smd(x, treat, w=None):
    """Standardized mean difference: (weighted) mean difference / pooled SD of the UNWEIGHTED groups."""
    x, treat = np.asarray(x, float), np.asarray(treat)
    w = np.ones(len(x)) if w is None else np.asarray(w, float)
    m1 = np.average(x[treat == 1], weights=w[treat == 1])
    m0 = np.average(x[treat == 0], weights=w[treat == 0])
    sd = np.sqrt((x[treat == 1].var() + x[treat == 0].var()) / 2)
    return float((m1 - m0) / sd) if sd > 0 else 0.0

def balance_table(t, weights=None, covariates=PS_COVARIATES):
    """SMD of each covariate, unweighted and under each named weight vector."""
    weights = weights or {}
    out = pd.DataFrame({"unadjusted": [smd(t[c], t.start) for c in covariates]}, index=covariates)
    for name, w in weights.items():
        out[name] = [smd(t[c], t.start, w) for c in covariates]
    return out
"""Day 24.3: covariate balance before and after weighting - standardized mean differences and a love plot."""

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

from corridor.db import ROOT  # noqa: E402
from corridor.ps import balance_table, fit_ps, weights  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
w = {k: weights(e, t.start, k) for k in ("ate", "att", "overlap")}
b = balance_table(t, w)
print("standardized mean differences (starters minus non-starters); |SMD| < 0.1 is the usual target")
print((b.round(3) + 0.0).to_string())          # + 0.0 turns -0.0 into 0.0
print(f"\nlargest |SMD|: unadjusted {b.unadjusted.abs().max():.3f}, ATE {b.ate.abs().max():.3f}, "
      f"ATT {b.att.abs().max():.3f}, overlap {b.overlap.abs().max():.3f}")
fig, ax = plt.subplots(figsize=(6, 3.8))
y = range(len(b))
for col, mk, colour in (("unadjusted", "o", "#e5484d"), ("ate", "s", "#f5a524"), ("att", "^", "#4f9cf9"),
                        ("overlap", "D", "#3ecf8e")):
    ax.scatter(b[col].abs(), y, marker=mk, color=colour, label=col, zorder=3)
ax.axvline(0.1, color="#888", ls="--", lw=1)
ax.set(yticks=list(y), yticklabels=b.index, xlabel="|standardized mean difference|", title="Balance (love plot)")
ax.legend(fontsize=8, loc="lower right")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day24_love_plot.png"), dpi=130)
standardized mean differences (starters minus non-starters); |SMD| < 0.1 is the usual target
                 unadjusted    ate    att  overlap
egfr                 -0.888 -0.013  0.001      0.0
albuminuria           0.382  0.001 -0.001      0.0
sglt2                 0.082  0.045  0.000      0.0
age                  -0.280 -0.001  0.001      0.0
male                  0.030 -0.048  0.000      0.0
qc                   -0.034 -0.050  0.000      0.0
nephrology_care       0.605  0.012 -0.001      0.0
heart_failure        -0.035 -0.020  0.001      0.0
copd                 -0.013 -0.031  0.000      0.0
prior_stays           0.113  0.042 -0.002      0.0
trial                 0.104  0.053 -0.002      0.0

largest |SMD|: unadjusted 0.888, ATE 0.053, ATT 0.002, overlap 0.000

Love plot: SMDs before and after weighting

Unadjusted, starters' eGFR is 0.89 standard deviations lower and they are much more often under a nephrologist (SMD 0.61). All three weightings bring every covariate under 0.1. Overlap weights balance the means exactly: with a logistic propensity score, overlap weights reproduce the score equations, so every covariate in the model has an SMD of zero. That is a property of the method, not a sign the job is done: balance on measured covariates says nothing about frailty.

Why it matters at work: reviewers of observational evidence (CDA-AMC, NICE, journal referees) look for the balance table first. A table of SMDs before and after adjustment is in nearly every RWE report; a c-statistic alone is not accepted as evidence of adjustment.

Where you'll meet this: RWE reports for reimbursement reassessments; "Table 1" of observational studies; cobalt love plots in R


24.3 Matching (35 min)

Matching pairs each starter with the non-starter whose score is closest, within the same trial month, and only if the difference is under a caliper (here 0.2 standard deviations of the logit of the score). Without replacement, each non-starter is used at most once.

def match(t, logit_ps, caliper_sd=0.2, seed=2026):
    """1:1 nearest-neighbour matching on the logit of the propensity score, within the same trial, without
    replacement, caliper 0.2 SD of the logit (Austin). Returns (treated index, control index) arrays."""
    rng = np.random.default_rng(seed)
    lp = pd.Series(np.asarray(logit_ps), index=t.index)
    caliper = caliper_sd * lp.std()
    pairs_t, pairs_c = [], []
    for _, g in t.groupby("trial"):
        treated = g.index[g.start == 1].to_numpy()
        controls = g.index[g.start == 0].to_numpy()
        c_lp = lp[controls].to_numpy()
        order = np.argsort(c_lp)
        c_sorted, c_ids = c_lp[order], controls[order]
        used = np.zeros(len(c_ids), bool)
        for i in rng.permutation(treated):          # random order: no starter gets first pick by design
            pos = np.searchsorted(c_sorted, lp[i])
            best, best_d = None, caliper
            for j in range(max(0, pos - 50), min(len(c_ids), pos + 50)):
                d = abs(c_sorted[j] - lp[i])
                if not used[j] and d <= best_d:
                    best, best_d = j, d
            if best is not None:
                used[best] = True
                pairs_t.append(i)
                pairs_c.append(c_ids[best])
    return np.array(pairs_t), np.array(pairs_c)
"""Day 24.4: 1:1 nearest-neighbour matching on the propensity score, within each trial month."""

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.ps import balance_table, fit_ps, match  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
ti, ci = match(t, np.log(e / (1 - e)))
print(f"matched {len(ti):,} of {int(t.start.sum()):,} starters to {len(ci):,} different non-starters (caliper 0.2 SD of logit)")
m = t.loc[np.concatenate([ti, ci])]
print("\nbalance in the matched sample (SMD):")
print((balance_table(m).round(3) + 0.0).T.to_string())
r1, r0 = t.loc[ti].kf24.mean(), t.loc[ci].kf24.mean()
print(f"\n24-month risk of kidney failure: matched starters {r1:.4f}, matched non-starters {r0:.4f}, ratio {r1 / r0:.2f}")
print(f"kidney failures behind those risks: {int(t.loc[ti].kf24.sum())} and {int(t.loc[ci].kf24.sum())}")
matched 1,040 of 1,041 starters to 1,040 different non-starters (caliper 0.2 SD of logit)

balance in the matched sample (SMD):
             egfr  albuminuria  sglt2    age   male     qc  nephrology_care  heart_failure   copd  prior_stays  trial
unadjusted -0.029       -0.026 -0.008  0.006  0.025 -0.037           -0.037         -0.028  0.015       -0.017    0.0

24-month risk of kidney failure: matched starters 0.0404, matched non-starters 0.0471, ratio 0.86
kidney failures behind those risks: 42 and 49

All but one starter found a partner, and the matched sample is balanced (every |SMD| under 0.04). The estimate, 0.86, compares the starters with people like them who did not start: it estimates the ATT, the effect in those treated. It rests on 42 and 49 kidney failures.

Matching discards 86,800 non-starters. That is its strength (the comparison is transparent: you can print the pairs) and its cost (the information in the discarded people is lost). It has a second cost: the bootstrap does not work for nearest-neighbour matching without replacement (Abadie and Imbens showed its variance estimate is not valid), so this course does not bootstrap matched estimates. Use a robust variance from the matched pairs, or weight instead.

Try it (15 min). Rerun the matching with calipers of 0.01, 0.05, 0.2, 1 and 10 standard deviations. How many starters are matched, and what happens to balance and the estimate?

Solution
"""Day 24 try it: how does the caliper change who is matched, the balance and the estimate?"""

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.ps import fit_ps, match, smd  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
lp = np.log(e / (1 - e))
print(f"{'caliper (SD of logit)':>22}{'matched':>9}{'SMD eGFR':>10}{'SMD nephrology':>16}{'ratio':>7}")
for cal in (0.01, 0.05, 0.2, 1.0, 10.0):
    ti, ci = match(t, lp, caliper_sd=cal)
    m = t.loc[np.concatenate([ti, ci])]
    print(f"{cal:>22}{len(ti):>9,}{smd(m.egfr, m.start):>10.3f}{smd(m.nephrology_care, m.start):>16.3f}"
          f"{t.loc[ti].kf24.mean() / t.loc[ci].kf24.mean():>7.2f}")
 caliper (SD of logit)  matched  SMD eGFR  SMD nephrology  ratio
                  0.01    1,028    -0.030          -0.038   0.88
                  0.05    1,038    -0.029          -0.038   0.86
                   0.2    1,040    -0.029          -0.037   0.86
                   1.0    1,041    -0.029          -0.037   0.86
                  10.0    1,041    -0.029          -0.037   0.86

Almost nothing changes. With 84 non-starters for every starter, every starter has a close neighbour, so the caliper rarely binds. The caliper matters when controls are scarce: then a tight caliper drops starters, and the estimate stops being about all starters. Report how many were dropped and how they differ from the matched starters.


24.4 Weighting: three estimands (45 min)

Instead of discarding people, weight them. Each set of weights creates a pseudo-population in which treatment is unrelated to the covariates, and each answers a different question:

WeightsStarterNon-starterEstimand: the effect in ...
ATE (stabilized)P(start) / eP(no start) / (1 − e)everyone eligible
ATT1e / (1 − e)the people who started
Overlap (ATO)1 − eethe people for whom the decision could have gone either way
def weights(e, treat, kind):
    """ATE: 1/e and 1/(1-e), stabilized by the marginal share; ATT: 1 and e/(1-e); overlap: 1-e and e."""
    e, a = np.asarray(e), np.asarray(treat)
    if kind == "ate":
        p = a.mean()
        return np.where(a == 1, p / e, (1 - p) / (1 - e))
    if kind == "att":
        return np.where(a == 1, 1.0, e / (1 - e))
    if kind == "overlap":
        return np.where(a == 1, 1 - e, e)
    raise ValueError(kind)

def weighted_risks(y, treat, w):
    y, a, w = np.asarray(y, float), np.asarray(treat), np.asarray(w, float)
    r1 = np.average(y[a == 1], weights=w[a == 1])
    r0 = np.average(y[a == 0], weights=w[a == 0])
    return float(r1), float(r0)

def ess(w):
    """Kish effective sample size: how many unweighted people the weights are worth."""
    w = np.asarray(w, float)
    return float(w.sum() ** 2 / (w ** 2).sum())
"""Day 24.5: inverse probability weighting - three estimands, effective sample sizes and bootstrap CIs."""

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.ps import ess, fit_ps, weighted_risks, weights  # noqa: E402
from corridor.tte import cluster_bootstrap, load  # noqa: E402

KINDS = {"ate": "everyone eligible (ATE)", "att": "the starters (ATT)", "overlap": "the overlap population (ATO)"}

def estimates(d):
    _, e = fit_ps(d)
    out = {}
    for k in KINDS:
        r1, r0 = weighted_risks(d.kf24, d.start, weights(e, d.start, k))
        out[f"{k}_r1"], out[f"{k}_r0"] = r1, r0
    return out

t = load()
_, e = fit_ps(t)
point = estimates(t)
boot = cluster_bootstrap(t, estimates, reps=100)
rows = []
for k, label in KINDS.items():
    w = weights(e, t.start, k)
    rr = boot[f"{k}_r1"] / boot[f"{k}_r0"]
    rows.append({"weights for": label, "risk if start": round(point[f"{k}_r1"], 4), "risk if not": round(point[f"{k}_r0"], 4),
                 "ratio": round(point[f"{k}_r1"] / point[f"{k}_r0"], 2),
                 "95% CI": f"{np.quantile(rr, 0.025):.2f}-{np.quantile(rr, 0.975):.2f}",
                 "ESS starters": round(ess(w[t.start == 1])), "ESS others": round(ess(w[t.start == 0])),
                 "largest weight": round(w.max(), 1)})
print(pd.DataFrame(rows).to_string(index=False))
print("\n(95% CIs from 100 bootstraps of people, refitting the propensity score each time)")
                 weights for  risk if start  risk if not  ratio    95% CI  ESS starters  ESS others  largest weight
     everyone eligible (ATE)         0.0113       0.0173   0.65 0.40-0.88           439       87830             8.5
          the starters (ATT)         0.0403       0.0498   0.81 0.52-1.01          1041       33651             1.0
the overlap population (ATO)         0.0392       0.0488   0.80 0.51-1.00          1040       35344             1.0

(95% CIs from 100 bootstraps of people, refitting the propensity score each time)

The three answers differ because the questions differ. The ATE weights up the few starters who look like the typical non-starter (high eGFR, low score) to stand in for all 88,000 non-starters: the largest stabilized weight is 8.5, and the 1,041 starters count as an effective sample size of 439, which is why the ATE's interval is the widest. The ATT and overlap weights barely touch the starters and agree (0.81, 0.80). The confidence intervals come from 100 bootstraps of people that refit the propensity score each time, because the score is estimated too.

Which estimand does a payer want? Usually the ATT or the ATO. The policy question is "for the patients doctors actually prescribe it to, does it work?", not "what if every CKD patient, including those with an eGFR of 58, got it?". Write the estimand down before you choose the weights.

Check it in R with WeightIt, cobalt and MatchIt. R's ns() places spline knots differently from cr(), so the estimates agree to two decimals:

# Day 24: the same propensity score analyses with WeightIt, cobalt and MatchIt.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(WeightIt); library(cobalt); library(MatchIt)
  library(splines) })
con <- dbConnect(duckdb(shared_home = FALSE))
t <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/trials.parquet')")
dbDisconnect(con, shutdown = TRUE)
t$age10 <- (t$age - 70) / 10
f <- start ~ ns(egfr, df = 4) + albuminuria + sglt2 + age10 + male + qc + nephrology_care + heart_failure + copd +
  prior_stays + factor(trial)
for (est in c("ATE", "ATT", "ATO")) {
  w <- weightit(f, data = t, method = "glm", estimand = est)
  r1 <- weighted.mean(t$kf24[t$start == 1], w$weights[t$start == 1])
  r0 <- weighted.mean(t$kf24[t$start == 0], w$weights[t$start == 0])
  cat(sprintf("%s: %.4f vs %.4f, ratio %.2f\n", est, r1, r0, r1 / r0))
}
w <- weightit(f, data = t, method = "glm", estimand = "ATO")
b <- bal.tab(w, un = TRUE, binary = "std", s.d.denom = "pooled")
print(round(b$Balance[c("albuminuria", "nephrology_care", "age10"), c("Diff.Un", "Diff.Adj")], 3))
m <- matchit(f, data = t, method = "nearest", distance = "glm", link = "linear.logit", caliper = 0.2, exact = ~trial)
md <- match.data(m)
cat(sprintf("MatchIt: %d starters matched; risk ratio %.2f\n", sum(md$start), mean(md$kf24[md$start == 1]) / mean(md$kf24[md$start == 0])))
ATE: 0.0113 vs 0.0173, ratio 0.65
ATT: 0.0403 vs 0.0499, ratio 0.81
ATO: 0.0392 vs 0.0489, ratio 0.80
                Diff.Un Diff.Adj
albuminuria       0.382        0
nephrology_care   0.605        0
age10            -0.280        0
MatchIt: 1040 starters matched; risk ratio 0.86

24.5 Truth check (25 min)

Each estimand has its own truth. The generator ran every eligible person-trial both ways, so the true ATE averages the paired outcomes over everyone, the ATT over the starters, and the ATO weights each person-trial by e(1 − e).

"""Day 24.6 (truth check): matching and weighting against the generator's counterfactual risks.

Each estimand has its own truth: the average of the generator's paired outcomes (start / no start) over
everyone (ATE), over the starters (ATT), or weighted by e(1 - e), the overlap weights' target (ATO).
"""

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.ps import fit_ps, match, weighted_risks, weights  # noqa: E402
from corridor.tte import load  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402

t = load()
_, e = fit_ps(t)
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int), e=e).merge(tr, on=["person_id", "trial"])
h = {"ATE": np.ones(len(d)), "ATT": d.start.to_numpy(), "ATO": (d.e * (1 - d.e)).to_numpy()}
ti, ci = match(t, np.log(e / (1 - e)))
est = {"ATE": weighted_risks(t.kf24, t.start, weights(e, t.start, "ate")),
       "ATT": weighted_risks(t.kf24, t.start, weights(e, t.start, "att")),
       "ATO": weighted_risks(t.kf24, t.start, weights(e, t.start, "overlap"))}
print(f"{'estimand':<10}{'method':<22}{'estimate':>9}{'truth':>8}")
for k in ("ATE", "ATT", "ATO"):
    true = np.average(d.kf24_start, weights=h[k]) / np.average(d.kf24_no_start, weights=h[k])
    r1, r0 = est[k]
    print(f"{k:<10}{'weighting':<22}{r1 / r0:>9.2f}{true:>8.2f}")
    if k == "ATT":
        print(f"{k:<10}{'1:1 matching':<22}{t.loc[ti].kf24.mean() / t.loc[ci].kf24.mean():>9.2f}{true:>8.2f}")
estimand  method                 estimate   truth
ATE       weighting                  0.65    0.73
ATT       weighting                  0.81    0.77
ATT       1:1 matching               0.86    0.77
ATO       weighting                  0.80    0.73

All three weighted estimates land within about 0.1 of their own truth, and every bootstrap interval covers it. They are not exact, for two reasons you can name. Frailty is unmeasured: frail people are started less often and have worse outcomes, and no propensity score can balance what it does not contain. And the ATE leans on a few heavily weighted starters, so its estimate moves a lot from sample to sample. Matching (0.86) is the furthest off: it is the noisiest of the four, with 91 events in total.

Comparing an estimate with the wrong truth is a common error: the ATE estimate (0.65) is "too strong" next to the ATT truth (0.77), and fine next to its own (0.73).


24.6 The best predictor of treatment (20 min)

Bug of the day. "The propensity score should predict treatment as well as possible, so add everything that predicts it." The strongest predictor of starting Renavex is the usual prescriber: some doctors start almost everyone eligible, some almost no one. Add it:

"""Day 24 bug of the day: 'the propensity score should predict treatment as well as possible'."""

import os
import sys

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

import duckdb  # noqa: E402

from corridor.ps import PS_FORMULA, c_statistic, ess, fit_ps, weighted_risks, weights  # noqa: E402
from corridor.rwe import D  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load().merge(duckdb.sql(f"SELECT person_id, usual_prescriber FROM read_csv('{D}/rwe_persons.csv')").df(), on="person_id")
for label, f in (("confounders only", PS_FORMULA),
                 ("+ usual prescriber (275)", PS_FORMULA + " + C(usual_prescriber)")):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        _, e = fit_ps(t, f)
    w = weights(e, t.start, "overlap")
    r1, r0 = weighted_risks(t.kf24, t.start, w)
    wa = weights(e, t.start, "ate")
    print(f"{label:<26} c-statistic {c_statistic(t.start, e):.3f}   overlap-weighted ratio {r1 / r0:.2f}   "
          f"ATE weights: ESS of starters {ess(wa[t.start == 1]):.0f}, largest {wa.max():.1f}")
print("truth (ATO, from day24/truth_check.py): 0.73")
confounders only           c-statistic 0.772   overlap-weighted ratio 0.80   ATE weights: ESS of starters 439, largest 8.5
+ usual prescriber (275)   c-statistic 0.846   overlap-weighted ratio 0.91   ATE weights: ESS of starters 207, largest 25.8
truth (ATO, from day24/truth_check.py): 0.73

The c-statistic rises from 0.77 to 0.85, and the estimate gets worse (0.91 against a truth of 0.73). The prescriber affects who starts but has no effect of its own on kidney failure: it is an instrument. Adjusting for an instrument removes the "good" variation in treatment (the part due to the doctor's habits, unrelated to the patient's prognosis) and leaves the "bad" variation (the part due to things the doctor saw and the data did not, such as frailty). Any remaining confounding is amplified, and the weights become more extreme: the ESS of starters falls from 439 to 207.

The rule: put confounders and predictors of the outcome in the propensity score, not predictors of treatment alone. The DAG decides (21.4), not the c-statistic. Day 36 (Module 4) uses the prescriber the right way, as an instrument.


24.7 Mini-project: Table 1 for the protocol (60 min)

Build the protocol's Table 1: characteristics of starters and non-starters, before and after overlap weighting, with SMDs. Write it to docs/table1_overlap_weighted.csv.

"""Day 24 mini-project: Table 1 for the protocol - starters vs non-starters, before and after overlap weighting."""

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.db import ROOT  # noqa: E402
from corridor.ps import fit_ps, smd, weights  # noqa: E402
from corridor.tte import load  # noqa: E402

t = load()
_, e = fit_ps(t)
w = weights(e, t.start, "overlap")
LABELS = {"egfr": "eGFR, mean", "albuminuria": "Albuminuria (UACR >= 30), %", "sglt2": "SGLT2 inhibitor, %",
          "age": "Age, mean", "male": "Male, %", "qc": "Quebec, %", "nephrology_care": "Nephrology care, %",
          "heart_failure": "Heart failure, %", "copd": "COPD, %", "prior_stays": "Hospital stays in prior year, mean"}
rows = []
for c, label in LABELS.items():
    pct = "%" in label
    f = (lambda x: f"{100 * x:.1f}") if pct else (lambda x: f"{x:.1f}")
    s, n = t.start == 1, t.start == 0
    rows.append({"characteristic": label, "starters": f(t[c][s].mean()), "non-starters": f(t[c][n].mean()),
                 "SMD": round(smd(t[c], t.start), 3),
                 "starters (weighted)": f(np.average(t[c][s], weights=w[s])),
                 "non-starters (weighted)": f(np.average(t[c][n], weights=w[n])),
                 "SMD (weighted)": round(smd(t[c], t.start, w), 3) + 0.0})
tab = pd.DataFrame(rows)
head = pd.DataFrame([{"characteristic": "Person-trials", "starters": f"{int(t.start.sum()):,}",
                      "non-starters": f"{int((t.start == 0).sum()):,}", "SMD": "",
                      "starters (weighted)": f"{w[t.start == 1].sum():,.0f}", "non-starters (weighted)": f"{w[t.start == 0].sum():,.0f}",
                      "SMD (weighted)": ""}])
tab = pd.concat([head, tab], ignore_index=True)
tab.to_csv(os.path.join(ROOT, "docs", "table1_overlap_weighted.csv"), index=False)
print(tab.to_string(index=False))
                    characteristic starters non-starters    SMD starters (weighted) non-starters (weighted) SMD (weighted)
                     Person-trials    1,041       87,849                      1,011                   1,011               
                        eGFR, mean     35.4         44.5 -0.888                35.6                    35.6            0.0
       Albuminuria (UACR >= 30), %     39.3         22.0  0.382                38.8                    38.8            0.0
                SGLT2 inhibitor, %     38.8         34.9  0.082                38.7                    38.7            0.0
                         Age, mean     68.0         72.2  -0.28                68.1                    68.1            0.0
                           Male, %     52.8         51.4   0.03                52.8                    52.8            0.0
                         Quebec, %     39.3         41.0 -0.034                39.3                    39.3            0.0
                Nephrology care, %     60.3         31.5  0.605                59.7                    59.7            0.0
                  Heart failure, %      8.1          9.0 -0.035                 8.1                     8.1            0.0
                           COPD, %      4.0          4.3 -0.013                 4.0                     4.0            0.0
Hospital stays in prior year, mean      0.3          0.3  0.113                 0.3                     0.3            0.0

The weighted columns describe the overlap population: people around eGFR 36, 39% with albuminuria and 60% under a nephrologist. This is the population the estimate of 24.4 applies to, so the table belongs next to it. Under the table, write two sentences: who this population is, and why it was chosen over everyone eligible.

24.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 24: propensity scores, balance, matching and three weighting estimands"

Day 24 checklist

  • I fit a propensity score and look at overlap before estimating anything
  • I judge the score by balance (SMDs), not by its c-statistic
  • I can say which estimand matching, ATE, ATT and overlap weights target, and compare each with its own truth
  • I report effective sample sizes and the largest weights
  • I keep instruments out of the propensity score