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

Doubly Robust Estimation: AIPW and TMLE

You now have two ways to adjust: model the outcome (the g-formula, Day 22) or model the treatment (the propensity score, Day 24). Each is right only if its model is right. Doubly robust estimators combine the two so that the estimate is consistent if either model is right. Today you write the two standard ones by hand, AIPW and TMLE, with standard errors from the influence function, prove double robustness in a simulation, and see what it does not protect against.

▶
Video for Day 25 coming soon

By the end of today you can

  • write the AIPW estimator and say what each of its two terms does
  • compute standard errors from the influence function, summed within person
  • describe TMLE's targeting step and when it beats AIPW
  • know double robustness protects against model misspecification, not unmeasured confounding or poor overlap
  • test every new estimator on a simulation with a known answer

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:30
25.1 Two models, one estimate
0:30–1:20
25.2 AIPW by hand
1:20–1:35
Break
1:35–2:10
25.3 TMLE: the targeting step
2:10–2:55
25.4 Double robustness, demonstrated
2:55–3:10
Break
3:10–3:45
25.5 Truth check and effect modification
3:45–4:05
25.6 A copied line
4:05–4:50
25.7 Mini-project: every estimate on one page
4:50–5:00
25.8 Save your work
5:00–5:30
Bloc français

In this lesson

25.1 Two models, one estimate (30 min)

Write q1(x) and q0(x) for the outcome model's predicted risks with and without starting, and e(x) for the propensity score. The augmented IPW (AIPW) estimate of the risk if everyone started is

mean of q1(x) + A (Y − q1(x)) / e(x)

The first term is the g-formula. The second is an IPW-weighted average of the outcome model's errors among starters. If the outcome model is right, its errors average to zero and the correction does nothing. If the propensity score is right, the correction removes exactly the outcome model's bias. Either way the estimate is right. That is double robustness.

The same expression has a second benefit. Each row's term, minus the mean, is that row's influence function value: how much the estimate moves when the row is added. Its variance gives the standard error without a bootstrap. Because people appear in up to 12 trials, sum each person's values first, then compute the variance across people.


25.2 AIPW by hand (50 min)

OUTCOME_FORMULA = ("kf24 ~ start + cr(egfr, df=4) + albuminuria + sglt2 + age10 + male + qc + nephrology_care"
                   " + heart_failure + copd + prior_stays + C(trial)")

def outcome_model(t, formula=OUTCOME_FORMULA):
    """Logistic outcome model; returns everyone's predicted risk if they start (q1) and if they do not (q0)."""
    m = smf.logit(formula, t).fit(disp=0, method="newton", maxiter=50)
    return np.asarray(m.predict(t.assign(start=1))), np.asarray(m.predict(t.assign(start=0)))

def cluster_se(phi, groups=None):
    """SE of a mean from its influence function values; groups=None treats every row as independent."""
    phi = np.asarray(phi, float)
    if groups is not None:
        phi = pd.Series(phi).groupby(np.asarray(groups)).sum().to_numpy()
    return float(np.sqrt((phi ** 2).sum()) / len(np.asarray(groups) if groups is not None else phi))

def aipw(y, a, e, q1, q0, groups=None, estimand="ate"):
    """Augmented IPW risks under start / no start, risk ratio with a 95% CI (delta method on the log scale)."""
    y, a, e, q1, q0 = (np.asarray(v, float) for v in (y, a, e, q1, q0))
    if estimand == "ate":
        p1 = q1 + a * (y - q1) / e
        p0 = q0 + (1 - a) * (y - q0) / (1 - e)
        r1, r0 = p1.mean(), p0.mean()
        phi1, phi0 = p1 - r1, p0 - r0
    else:                                                        # att: the starters' risks
        pa = a.mean()
        r1 = y[a == 1].mean()
        p0 = a * q0 + (1 - a) * e / (1 - e) * (y - q0)
        r0 = p0.sum() / a.sum()
        phi1, phi0 = a * (y - r1) / pa, (p0 - a * r0) / pa
    se = cluster_se(phi1 / r1 - phi0 / r0, groups)
    rr = r1 / r0
    return {"r1": r1, "r0": r0, "rr": rr, "lo": rr * np.exp(-1.96 * se), "hi": rr * np.exp(1.96 * se), "se_log": se}

The risk ratio's confidence interval uses the delta method on the log scale: the influence function of log(r1/r0) is φ1/r1 − φ0/r0. For the ATT, the starters' own risk is simply observed, and only the no-start risk is modelled and corrected, with the odds e/(1 − e) as weights.

"""Day 25.2-25.3: AIPW and TMLE by hand, next to the two single-model estimators they combine."""

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

t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
print(f"outcome model: mean predicted risk if everyone started {q1.mean():.4f}, if nobody did {q0.mean():.4f}")
print(f"propensity scores of starters: {e[t.start == 1].min():.4f} to {e[t.start == 1].max():.3f}\n")
r1, r0 = weighted_risks(t.kf24, t.start, weights(e, t.start, "ate"))
rows = [("outcome model only (g-formula)", q1.mean(), q0.mean(), None),
        ("propensity score only (IPW)", r1, r0, None)]
for label, f in (("AIPW", aipw), ("TMLE", tmle)):
    r = f(t.kf24, t.start, e, q1, q0, t.person_id)
    rows.append((label, r["r1"], r["r0"], f"{r['lo']:.2f}-{r['hi']:.2f}"))
print(f"{'ATE estimator':<32}{'risk if start':>14}{'if not':>9}{'ratio':>7}   95% CI")
for label, a, b, ci in rows:
    print(f"{label:<32}{a:>14.4f}{b:>9.4f}{a / b:>7.2f}   {ci or ''}")
r = tmle(t.kf24, t.start, e, q1, q0, t.person_id)
print(f"\nTMLE fluctuation: epsilon (start) {r['eps1']:.4f}, epsilon (no start) {r['eps0']:.4f}")
outcome model: mean predicted risk if everyone started 0.0139, if nobody did 0.0173
propensity scores of starters: 0.0014 to 0.206

ATE estimator                    risk if start   if not  ratio   95% CI
outcome model only (g-formula)          0.0139   0.0173   0.80   
propensity score only (IPW)             0.0113   0.0173   0.65   
AIPW                                    0.0108   0.0173   0.62   0.44-0.89
TMLE                                    0.0108   0.0173   0.62   0.44-0.88

TMLE fluctuation: epsilon (start) -0.0058, epsilon (no start) 0.0004

The outcome model alone says 0.80, the propensity score alone 0.65, AIPW 0.62. When the two single-model estimates disagree this much, at least one model is wrong for this estimand, and the doubly robust estimate follows whichever correction is larger. Here, it follows the weights. Remember that starters' scores go down to 0.0014: a starter with that score stands in for about 700 people. The ATE is the estimand with the least support in the data, and its interval (0.44 to 0.89) says so.


25.3 TMLE: the targeting step (35 min)

Targeted maximum likelihood estimation (TMLE) reaches the same place by another road. Instead of adding a correction to the estimate, it corrects the outcome model itself: one extra logistic regression of Y on the "clever covariates" A/e and (1 − A)/(1 − e), with the original predictions as an offset. The fitted coefficients (ε) nudge q1 and q0 just enough that the correction term averages to zero, and then the plug-in average of the updated predictions is the estimate.

def tmle(y, a, e, q1, q0, groups=None):
    """Targeted maximum likelihood (ATE): one logistic fluctuation of the outcome model along the 'clever
    covariates' a/e and (1-a)/(1-e), then plug in. Returns the same fields as aipw plus the two epsilons."""
    y, a, e, q1, q0 = (np.asarray(v, float) for v in (y, a, e, q1, q0))
    qa = np.where(a == 1, q1, q0)
    x = np.column_stack([a / e, (1 - a) / (1 - e)])
    eps = sm.GLM(y, x, family=sm.families.Binomial(), offset=logit(qa)).fit().params
    q1s, q0s = expit(logit(q1) + eps[0] / e), expit(logit(q0) + eps[1] / (1 - e))
    out = aipw(y, a, e, q1s, q0s, groups)                     # the correction terms now average to zero ...
    out.update(r1=q1s.mean(), r0=q0s.mean(), eps1=eps[0], eps0=eps[1])   # ... so plug-in = AIPW on q*
    return out

The output of 25.2 already shows TMLE: 0.62 (0.44 to 0.88), with tiny fluctuations (ε of −0.006 and 0.0004), because the outcome model was nearly unbiased on average. TMLE and AIPW have the same large-sample properties. TMLE's advantage shows when weights are extreme: its estimate is a mean of predicted probabilities, so it can never fall outside 0 to 1, while AIPW's corrections can push a risk below zero. Both are commonly paired with machine-learning outcome and treatment models ("super learner"); the logic is the same as here, with cross-fitting to stop the models overfitting the rows they correct.


25.4 Double robustness, demonstrated (45 min)

Part A simulates a world where every model can be exactly right: z affects both treatment and outcome through z², and the "wrong" models use z instead. Part B runs the same grid on the sequential trials, with "wrong" meaning eGFR is left out.

"""Day 25.4: double robustness - right or wrong propensity score x right or wrong outcome model.

Part A is a simulation where every model can be exactly right, so the truth is known and nothing is
unmeasured. Part B repeats the grid on the sequential trials (ATT), with 'wrong' meaning eGFR left out.
"""

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
import statsmodels.formula.api as smf  # noqa: E402
from scipy.special import expit  # noqa: E402

from corridor.dr import OUTCOME_FORMULA, aipw, outcome_model  # noqa: E402
from corridor.ps import PS_FORMULA, fit_ps, weighted_risks, weights  # noqa: E402
from corridor.tte import load  # noqa: E402

# Part A: z enters both treatment and outcome through z squared; the 'wrong' models use z only.
rng = np.random.default_rng(25)
n = 200_000
z = rng.normal(size=n)
a = rng.binomial(1, expit(-1.5 + 0.5 * z + 0.8 * z ** 2))
p1, p0 = expit(-2.5 + 0.9 * z ** 2 - 0.5), expit(-2.5 + 0.9 * z ** 2)
y = rng.binomial(1, np.where(a == 1, p1, p0))
s = pd.DataFrame({"y": y, "a": a, "z": z})
truth = p1.mean() / p0.mean()
PS = {"right": "a ~ z + I(z**2)", "wrong": "a ~ z"}
OM = {"right": "y ~ a + I(z**2)", "wrong": "y ~ a + z"}
print(f"Part A - simulation, n = {n:,}: true risk ratio (everyone) {truth:.3f}")
print(f"{'propensity score':<18}{'outcome model':<15}{'IPW':>7}{'g-formula':>11}{'AIPW':>7}")
for ps in PS:
    e = np.asarray(smf.logit(PS[ps], s).fit(disp=0).predict(s))
    for om in OM:
        m = smf.logit(OM[om], s).fit(disp=0)
        q1, q0 = np.asarray(m.predict(s.assign(a=1))), np.asarray(m.predict(s.assign(a=0)))
        r1, r0 = weighted_risks(s.y, s.a, weights(e, s.a, "ate"))
        print(f"{ps:<18}{om:<15}{r1 / r0:>7.3f}{q1.mean() / q0.mean():>11.3f}{aipw(s.y, s.a, e, q1, q0)['rr']:>7.3f}")

# Part B: the corridor's sequential trials, ATT (truth 0.77 from day24/truth_check.py).
t = load()
NO_EGFR = {"ps": PS_FORMULA.replace("cr(egfr, df=4) + ", ""), "om": OUTCOME_FORMULA.replace("cr(egfr, df=4) + ", "")}
print("\nPart B - sequential trials, effect in starters (ATT); 'wrong' = eGFR left out; truth 0.77")
print(f"{'propensity score':<18}{'outcome model':<15}{'IPW':>7}{'g-formula':>11}{'AIPW':>7}")
st = t.start == 1
for ps, pf in (("right", PS_FORMULA), ("wrong", NO_EGFR["ps"])):
    _, e = fit_ps(t, pf)
    for om, of in (("right", OUTCOME_FORMULA), ("wrong", NO_EGFR["om"])):
        q1, q0 = outcome_model(t, of)
        r1, r0 = weighted_risks(t.kf24, t.start, weights(e, t.start, "att"))
        r = aipw(t.kf24, t.start, e, q1, q0, estimand="att")
        print(f"{ps:<18}{om:<15}{r1 / r0:>7.2f}{q1[st].mean() / q0[st].mean():>11.2f}{r['rr']:>7.2f}")
Part A - simulation, n = 200,000: true risk ratio (everyone) 0.740
propensity score  outcome model      IPW  g-formula   AIPW
right             right            0.741      0.748  0.747
right             wrong            0.741      1.826  0.741
wrong             right            1.969      0.748  0.748
wrong             wrong            1.969      1.826  1.944

Part B - sequential trials, effect in starters (ATT); 'wrong' = eGFR left out; truth 0.77
propensity score  outcome model      IPW  g-formula   AIPW
right             right             0.81       0.81   0.80
right             wrong             0.81       1.54   0.81
wrong             right             1.53       0.81   0.81
wrong             wrong             1.53       1.54   1.52

Read the rows of Part A. When the propensity score is right, IPW and AIPW are right (0.741 against 0.740) whatever the outcome model. When the outcome model is right, the g-formula and AIPW are right whatever the propensity score. AIPW fails only in the last row, when both are wrong. In Part B, leaving eGFR out of one model barely moves AIPW (0.80 or 0.81). Leaving it out of both gives 1.52, close to the crude comparison.

Two chances to be right is not a guarantee. Double robustness protects against misspecified models of measured covariates. It does nothing for an unmeasured confounder (frailty is in neither model), nothing for poor overlap, and nothing for a wrong estimand.

Why it matters at work: doubly robust estimators are increasingly expected in RWE submissions, and TMLE with super learner is common in pharmacoepidemiology. Knowing that "doubly robust" does not mean "unconfounded" saves you from overclaiming in front of a reviewer who knows it too.

Where you'll meet this: the AIPW, tmle and tmle3 R packages; DoubleML and econml in Python; FDA- and EMA-funded RWE demonstration projects


25.5 Truth check and effect modification (35 min)

"""Day 25 truth check: AIPW and TMLE against the generator's counterfactual risks - and whether the CIs cover them."""

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 aipw, outcome_model, tmle  # 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)
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"])
truth = {"ATE": d.kf24_start.mean() / d.kf24_no_start.mean(),
         "ATT": d.kf24_start[d.start == 1].mean() / d.kf24_no_start[d.start == 1].mean()}
res = {("ATE", "AIPW"): aipw(t.kf24, t.start, e, q1, q0, t.person_id),
       ("ATE", "TMLE"): tmle(t.kf24, t.start, e, q1, q0, t.person_id),
       ("ATT", "AIPW"): aipw(t.kf24, t.start, e, q1, q0, t.person_id, "att")}
print(f"{'estimand':<10}{'method':<8}{'estimate':>9}{'95% CI':>13}{'truth':>8}  covers?")
for (k, m), r in res.items():
    cov = "yes" if r["lo"] <= truth[k] <= r["hi"] else "NO"
    print(f"{k:<10}{m:<8}{r['rr']:>9.2f}{r['lo']:>7.2f}-{r['hi']:<5.2f}{truth[k]:>8.2f}  {cov}")
print(f"\nwidth of the CI on the log scale: ATE {2 * 1.96 * res[('ATE', 'AIPW')]['se_log']:.2f}, "
      f"ATT {2 * 1.96 * res[('ATT', 'AIPW')]['se_log']:.2f}")
estimand  method   estimate       95% CI   truth  covers?
ATE       AIPW         0.62   0.44-0.89     0.73  yes
ATE       TMLE         0.62   0.44-0.88     0.73  yes
ATT       AIPW         0.80   0.60-1.06     0.77  yes

width of the CI on the log scale: ATE 0.70, ATT 0.57

Every interval covers its own truth. The ATT estimate (0.80 against 0.77) is the more precise of the two, and the ATE's interval is about 25% wider on the log scale, for the reasons of 25.2.

Try it (20 min). The outcome model has one coefficient for start, so it assumes Renavex lowers the odds of kidney failure by the same factor in everyone. Let the effect vary with eGFR, albuminuria and nephrology care. What happens to the g-formula and AIPW estimates of the ATE and the ATT?

Solution
"""Day 25 try it: let the outcome model's start effect vary with eGFR, albuminuria and nephrology care."""

import os
import sys

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

t = load()
_, e = fit_ps(t)
s = t.start == 1
INTERACT = OUTCOME_FORMULA.replace("start +", "start * (egfr10 + albuminuria + nephrology_care) +")
print(f"{'outcome model':<26}{'g-formula ATE':>14}{'AIPW ATE':>10}{'g-formula ATT':>15}{'AIPW ATT':>10}")
for label, f in (("one start coefficient", OUTCOME_FORMULA), ("start x 3 modifiers", INTERACT)):
    q1, q0 = outcome_model(t, f)
    print(f"{label:<26}{q1.mean() / q0.mean():>14.2f}{aipw(t.kf24, t.start, e, q1, q0)['rr']:>10.2f}"
          f"{q1[s].mean() / q0[s].mean():>15.2f}{aipw(t.kf24, t.start, e, q1, q0, estimand='att')['rr']:>10.2f}")
print("truths: ATE 0.73, ATT 0.77")
outcome model              g-formula ATE  AIPW ATE  g-formula ATT  AIPW ATT
one start coefficient               0.80      0.62           0.81      0.80
start x 3 modifiers                 0.71      0.63           0.81      0.80
truths: ATE 0.73, ATT 0.77

The g-formula ATE moves from 0.80 to 0.71, close to the truth (0.73): with interactions, the model no longer forces the starters' effect onto the low-risk non-starters. AIPW barely moves (0.62 to 0.63), because its correction was already doing that work, and the ATT does not move, because starters need no extrapolation. A g-formula estimate that shifts when you add interactions is a sign that the estimand needs extrapolation.


25.6 A copied line (20 min)

Bug of the day. The AIPW code was written line by line: first the start term, then the no-start term, copied from the line above and edited. One edit was missed:

"""Day 25 bug of the day: the no-start term copied from the start term, so it divides by e instead of 1 - e.

Part 2 checks a second suspect - an SE that ignores people appearing in up to 12 trials.
"""

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 aipw, outcome_model  # 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)
y, a = t.kf24.to_numpy(), t.start.to_numpy()
p1 = q1 + a * (y - q1) / e
bad0 = q0 + (1 - a) * (y - q0) / e                        # copied from the line above
good0 = q0 + (1 - a) * (y - q0) / (1 - e)
print(f"no-start risk, buggy: {bad0.mean():.4f}   fixed: {good0.mean():.4f}")
print(f"ratio, buggy: {p1.mean() / bad0.mean():.2f}   fixed: {p1.mean() / good0.mean():.2f}")
print(f"largest single contribution to the no-start mean, buggy: {np.abs(bad0).max():.1f}   fixed: {np.abs(good0).max():.2f}")
print("\nPart 2 - does clustering by person change the CI here?")
print(f"{t.person_id.nunique():,} people in {len(t):,} person-trials")
for label, g in (("rows treated as independent", None), ("summed within person first", t.person_id)):
    r = aipw(t.kf24, t.start, e, q1, q0, g, "att")
    print(f"  {label:<30} ATT {r['rr']:.2f}  95% CI {r['lo']:.2f}-{r['hi']:.2f}  SE(log) {r['se_log']:.4f}")
no-start risk, buggy: 0.0933   fixed: 0.0173
ratio, buggy: 0.12   fixed: 0.62
largest single contribution to the no-start mean, buggy: 999.1   fixed: 1.12

Part 2 - does clustering by person change the CI here?
8,660 people in 88,890 person-trials
  rows treated as independent    ATT 0.80  95% CI 0.59-1.07  SE(log) 0.1502
  summed within person first     ATT 0.80  95% CI 0.60-1.06  SE(log) 0.1466

Dividing by e instead of 1 − e gives non-starters weights of up to 1,000 instead of about 1, and the no-start risk is 9.3% instead of 1.7%. The result (risk ratio 0.12) is implausible, but the code ran and nothing else warned. Two habits catch this: write the two terms as one function called with a and 1 − a, and test the estimator on a simulation with a known answer (tests/test_days_24_26.py does).

Part 2 checks a second suspect. Here, clustering by person barely changes the interval (0.59 to 1.07 against 0.60 to 1.06): few people contribute a kidney failure to several trials. Check, do not assume, and report the clustered version.


25.7 Mini-project: every estimate on one page (45 min)

The payer's question has now been answered ten ways. Put them on one page, each with its estimand and its truth, in docs/m3_estimates.csv:

"""Day 25 mini-project: every Module 3 estimate of 'start Renavex vs not' on one page, with its estimand and truth."""

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.dr import aipw, outcome_model, tmle  # noqa: E402
from corridor.ps import fit_ps, match, weighted_risks, weights  # 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 = t.start == 1
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"])
truth = {"ATE": d.kf24_start.mean() / d.kf24_no_start.mean(),
         "ATT": d.kf24_start[d.start == 1].mean() / d.kf24_no_start[d.start == 1].mean(),
         "ATO": np.average(d.kf24_start, weights=d.e * (1 - d.e)) / np.average(d.kf24_no_start, weights=d.e * (1 - d.e)),
         "none": np.nan}
ti, ci = match(t, np.log(e / (1 - e)))

def ipw(kind):
    r1, r0 = weighted_risks(t.kf24, t.start, weights(e, t.start, kind))
    return r1 / r0

rows = [("Day 22", "crude (starters vs non-starters)", "none", t.kf24[s].mean() / t.kf24[~s].mean()),
        ("Day 22", "g-formula (outcome model)", "ATE", q1.mean() / q0.mean()),
        ("Day 22", "g-formula (outcome model)", "ATT", q1[s].mean() / q0[s].mean()),
        ("Day 24", "IPW, stabilized", "ATE", ipw("ate")),
        ("Day 24", "IPW (ATT weights)", "ATT", ipw("att")),
        ("Day 24", "1:1 matching, caliper 0.2", "ATT", t.loc[ti].kf24.mean() / t.loc[ci].kf24.mean()),
        ("Day 24", "overlap weights", "ATO", ipw("overlap")),
        ("Day 25", "AIPW", "ATE", aipw(t.kf24, t.start, e, q1, q0)["rr"]),
        ("Day 25", "AIPW", "ATT", aipw(t.kf24, t.start, e, q1, q0, estimand="att")["rr"]),
        ("Day 25", "TMLE", "ATE", tmle(t.kf24, t.start, e, q1, q0)["rr"])]
tab = pd.DataFrame(rows, columns=["day", "method", "estimand", "risk ratio"])
tab["truth"] = tab.estimand.map(truth)
tab[["risk ratio", "truth"]] = tab[["risk ratio", "truth"]].round(2)
tab.to_csv(os.path.join(ROOT, "docs", "m3_estimates.csv"), index=False)
print(tab.to_string(index=False))
   day                           method estimand  risk ratio  truth
Day 22 crude (starters vs non-starters)     none        2.38    NaN
Day 22        g-formula (outcome model)      ATE        0.80   0.73
Day 22        g-formula (outcome model)      ATT        0.81   0.77
Day 24                  IPW, stabilized      ATE        0.65   0.73
Day 24                IPW (ATT weights)      ATT        0.81   0.77
Day 24        1:1 matching, caliper 0.2      ATT        0.86   0.77
Day 24                  overlap weights      ATO        0.80   0.73
Day 25                             AIPW      ATE        0.62   0.73
Day 25                             AIPW      ATT        0.80   0.77
Day 25                             TMLE      ATE        0.62   0.73

Read the table by column, not by row. Estimates of the same estimand agree with one another (ATT: 0.81, 0.81, 0.86, 0.80) and sit near their truth (0.77). The differences between rows are mostly differences between estimands, and between how much each leans on extrapolation. The crude 2.38 is the only number on the wrong side of 1. Write one paragraph for the payer: the estimand you recommend, its estimate with a confidence interval, and the one sentence they need about unmeasured frailty (Day 28 puts a number on it).

Check it in R by hand with two glm() fits:

# Day 25: AIPW by hand in R with two glm() fits, CI from the influence function clustered by person.
suppressPackageStartupMessages({ library(DBI); library(duckdb); 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
x <- "ns(egfr, df = 4) + albuminuria + sglt2 + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays + factor(trial)"
e <- fitted(glm(as.formula(paste("start ~", x)), binomial, data = t))
om <- glm(as.formula(paste("kf24 ~ start +", x)), binomial, data = t)
q1 <- predict(om, transform(t, start = 1), type = "response")
q0 <- predict(om, transform(t, start = 0), type = "response")
a <- t$start; y <- t$kf24
p1 <- q1 + a * (y - q1) / e; p0 <- q0 + (1 - a) * (y - q0) / (1 - e)
r1 <- mean(p1); r0 <- mean(p0)
phi <- rowsum((p1 - r1) / r1 - (p0 - r0) / r0, t$person_id)
se <- sqrt(sum(phi^2)) / nrow(t)
cat(sprintf("AIPW ATE: %.4f vs %.4f, ratio %.2f (95%% CI %.2f-%.2f)\n", r1, r0, r1 / r0,
            r1 / r0 * exp(-1.96 * se), r1 / r0 * exp(1.96 * se)))
r0t <- sum(a * q0 + (1 - a) * e / (1 - e) * (y - q0)) / sum(a)
cat(sprintf("AIPW ATT: %.4f vs %.4f, ratio %.2f\n", mean(y[a == 1]), r0t, mean(y[a == 1]) / r0t))
AIPW ATE: 0.0108 vs 0.0173, ratio 0.62 (95% CI 0.44-0.88)
AIPW ATT: 0.0403 vs 0.0506, ratio 0.80

25.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 25: AIPW and TMLE by hand, double robustness"

Day 25 checklist

  • I can write the AIPW estimator and say what each of its two terms does
  • I compute standard errors from the influence function, summed within person
  • I can describe TMLE's targeting step and when it beats AIPW
  • I know double robustness protects against model misspecification, not unmeasured confounding or poor overlap
  • I test every new estimator on a simulation with a known answer