Survival I: Kaplan–Meier and Cox
Time to death and time to first hospital admission are core outcomes in HTA: survival curves feed a model's health states, and hazard ratios often carry the treatment effect. Today you estimate survival curves with censored data (Kaplan–Meier, by hand and with statsmodels), compare groups with the log-rank test, fit Cox models, and check the proportional hazards assumption. A truth check fits Cox to the whole population with the generator's own covariates and recovers its death model.
By the end of today you can
- build every survival dataset with a time column and a status column where 1 = event
- compute a Kaplan–Meier curve by hand with censoring, and explain why it differs from a simple proportion
- compare groups with the log-rank test and quantify differences with a Cox model
- report HRs with CIs, the ties method and the number of events, and I check proportional hazards
- explain why a cohort HR can miss the true value by two standard errors
Today's 5.5-hour plan
In this lesson
13.1 Time-to-event data (30 min)
Every survival analysis needs two columns per person:
| Column | In m2/analysis.parquet | Meaning |
|---|---|---|
| time | t_end (death), t_admit or t_end (admission) | days from the index date to the event or to the end of observation (index date = day 1) |
| status | died, or "has a t_admit" | 1 = the event happened at that time, 0 = censored: still event-free when observation stopped |
Censoring is information, not missing data. A person who reached 31 December 2025 alive tells you they survived at least 365 days. Two shortcuts throw that away:
- "Proportion who died" counts censored people as survivors for the whole period. It is right only if everyone is followed for the same length of time. In this cohort they are (everyone starts on 1 January 2025), which is why it matches Kaplan–Meier for death. In a cohort with staggered entry, it does not.
- Mean time to event among people who had it ignores everyone who did not have it yet.
For time to first admission, death censors: a person who died on day 100 without an admission was at risk for 100 days. This answers "how fast are people admitted, while alive?". Day 15 asks the different question "what share of people are admitted before they die?", which needs competing-risks methods.
def admission_outcome(df):
"""Time to first hospital admission; death or the end of follow-up censors."""
event = df["t_admit"].notna().astype(int)
time = np.where(event == 1, df["t_admit"], df["t_end"]).astype(int)
return time, event.to_numpy()
13.2 Kaplan–Meier by hand (40 min)
At each time $t_j$ when someone has the event, with $n_j$ people still at risk and $d_j$ events,
Censored people stay in the risk set up to their censoring time, then leave. Greenwood's formula gives the standard error.
def km(time, event):
"""Kaplan-Meier product-limit estimate, one row per distinct event time.
At each time t: S(t) = S(t-) x (1 - d / n), where n = people still at risk just before t
(not yet failed or censored) and d = events at t. Censored people leave the risk set after t.
Greenwood's formula gives the standard error.
"""
t, e = np.asarray(time), np.asarray(event).astype(int)
rows, s, gw = [], 1.0, 0.0
for u in np.unique(t[e == 1]):
n = int((t >= u).sum())
d = int(((t == u) & (e == 1)).sum())
s *= 1 - d / n
gw += d / (n * (n - d)) if n > d else 0.0
rows.append((u, n, d, s, s * np.sqrt(gw)))
return pd.DataFrame(rows, columns=["time", "at_risk", "events", "surv", "se"])
def surv_at(table, t):
"""S(t) from a km() table (a step function: the last value at or before t)."""
before = table[table["time"] <= t]
return 1.0 if before.empty else float(before["surv"].iloc[-1])
"""Day 13.2: Kaplan-Meier by hand on eight people, then on the cohort."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from statsmodels.duration.survfunc import SurvfuncRight # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import km, surv_at # noqa: E402
# eight people: days followed, and whether follow-up ended with the event (1) or censoring (0)
time = [30, 45, 45, 90, 120, 200, 300, 365]
event = [1, 1, 0, 1, 0, 1, 0, 0]
print("Eight people:", list(zip(time, event)))
print(km(time, event).round(3).to_string(index=False))
print(f"naive 'share without the event': {1 - sum(event) / len(event):.3f} KM at day 365: {surv_at(km(time, event), 365):.3f}")
df = load()
tab = km(df.t_end, df.died)
sf = SurvfuncRight(df.t_end, df.died)
print(f"\nCohort, time to death: {len(df):,} people, {df.died.sum()} deaths")
for day in (90, 180, 365):
print(f" S({day}) = {surv_at(tab, day):.4f} (statsmodels: {sf.surv_prob[sf.surv_times <= day][-1]:.4f})")
Eight people: [(30, 1), (45, 1), (45, 0), (90, 1), (120, 0), (200, 1), (300, 0), (365, 0)]
time at_risk events surv se
30 8 1 0.875 0.117
45 7 1 0.750 0.153
90 5 1 0.600 0.182
200 3 1 0.400 0.203
naive 'share without the event': 0.500 KM at day 365: 0.400
Cohort, time to death: 6,224 people, 432 deaths
S(90) = 0.9833 (statsmodels: 0.9833)
S(180) = 0.9647 (statsmodels: 0.9647)
S(365) = 0.9306 (statsmodels: 0.9306)
Work the eight-person table on paper. At day 45 one person has the event and one is censored: the risk set at day 90 is 5, not 6. Kaplan–Meier gives 0.40 at day 365. The naive "4 of 8 had no event" gives 0.50, because it counts the people censored at days 45, 120 and 300 as if they were followed to day 365. In the cohort, one-year survival is 93.1%, and the hand-written function matches statsmodels to four decimals.
13.3 Curves by group and the log-rank test (35 min)
"""Day 13.3: survival curves by heart failure, and the log-rank test."""
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 statsmodels.duration.survfunc import survdiff # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import admission_outcome, km, surv_at # noqa: E402
df = load()
df["t_adm"], df["admitted"] = admission_outcome(df)
fig, ax = plt.subplots(1, 2, figsize=(9.5, 3.6))
for i, (t, e, title) in enumerate((("t_end", "died", "Alive"), ("t_adm", "admitted", "Not yet admitted"))):
print(f"--- {title}")
for hf, colour in ((0, "#4f9cf9"), (1, "#e5484d")):
g = df[df.heart_failure == hf]
tab = km(g[t], g[e])
print(f" HF={hf}: {len(g):>5,} people, {g[e].sum():>5,} events, S(365) = {surv_at(tab, 365):.3f}")
ax[i].step([0] + list(tab.time), [1] + list(tab.surv), where="post", color=colour,
label="heart failure" if hf else "no heart failure")
chi2, p = survdiff(df[t], df[e], df.heart_failure)
print(f" log-rank chi2 = {chi2:.1f}, p " + (f"= {p:.1e}" if p > 0 else "< 1e-15"))
ax[i].set(title=title, xlabel="days since 1 January 2025", ylim=(0.4 if i else 0.8, 1.0), xlim=(0, 365))
ax[0].set_ylabel("Kaplan-Meier estimate")
ax[0].legend(loc="lower left")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day13_km.png"), dpi=130)
--- Alive
HF=0: 5,273 people, 299 events, S(365) = 0.943
HF=1: 951 people, 133 events, S(365) = 0.860
log-rank chi2 = 88.6, p < 1e-15
--- Not yet admitted
HF=0: 5,273 people, 1,372 events, S(365) = 0.737
HF=1: 951 people, 502 events, S(365) = 0.456
log-rank chi2 = 337.7, p < 1e-15

One-year survival is 86.0% with heart failure and 94.3% without. Admission-free at one year: 45.6% against 73.7%. The log-rank test compares the observed events in each group with those expected if the curves were the same, at every event time. It is a test, not an effect size: it says the curves differ, not by how much. For that you need a model.
Try it (15 min). Is first admission faster in one province? Compare Ontario and Quebec with Kaplan–Meier, the log-rank test, and a Cox model with only province, then adjusted.
Solution
"""Day 13 try it: is first admission faster in one province? Kaplan-Meier, log-rank and Cox."""
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 statsmodels.duration.hazard_regression import PHReg # noqa: E402
from statsmodels.duration.survfunc import survdiff # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import admission_outcome, km, surv_at # noqa: E402
df = load()
df["t_adm"], df["admitted"] = admission_outcome(df)
for prov, g in df.groupby("province"):
print(f"{prov}: {len(g):,} people, admission-free at one year {surv_at(km(g.t_adm, g.admitted), 365):.3f}")
chi2, p = survdiff(df.t_adm, df.admitted, df.province)
print(f"log-rank chi2 {chi2:.2f}, p {p:.3f}")
for x in ("qc", COVARIATES):
m = PHReg.from_formula(f"t_adm ~ {x}", df, status=df.admitted, ties="efron").fit()
j = m.model.exog_names.index("qc")
print(f"Cox HR for QC vs ON, {'unadjusted' if x == 'qc' else 'adjusted'}: {np.exp(m.params[j]):.3f} "
f"(95% CI {np.exp(m.params[j] - 1.96 * m.bse[j]):.3f} to {np.exp(m.params[j] + 1.96 * m.bse[j]):.3f})")
ON: 3,956 people, admission-free at one year 0.687
QC: 2,268 people, admission-free at one year 0.708
log-rank chi2 2.53, p 0.111
Cox HR for QC vs ON, unadjusted: 0.926 (95% CI 0.842 to 1.018)
Cox HR for QC vs ON, adjusted: 0.936 (95% CI 0.851 to 1.030)
68.7% of Ontarians and 70.8% of Quebecers are admission-free at one year. The log-rank p is 0.11, and the hazard ratio is 0.93 (95% CI 0.84 to 1.02) before and after adjustment. There is no clear provincial difference in how fast people are admitted. This matches Day 12: Quebec's lower hospital cost came mostly from slightly fewer admissions, with a wide interval.
13.4 The Cox model (40 min)
The Cox proportional hazards model says each person's hazard is a common baseline hazard, of any shape, multiplied by a factor that depends on their covariates:
$e^{\beta_k}$ is a hazard ratio (HR): the ratio of instantaneous event rates, assumed the same at every time. The baseline $h_0(t)$ is never estimated in the fit. The partial likelihood compares, at each event time, the person who had the event with everyone at risk.
"""Day 13.4: the Cox proportional hazards model for death."""
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 statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.m2 import load # noqa: E402
df = load()
fits = {ties: PHReg.from_formula(f"t_end ~ {COVARIATES}", df, status=df.died, ties=ties).fit()
for ties in ("breslow", "efron")}
m = fits["efron"]
ci = m.conf_int()
t = pd.DataFrame({"HR": np.exp(m.params), "95% CI low": np.exp(ci[:, 0]), "95% CI high": np.exp(ci[:, 1]),
"p": m.pvalues, "log HR (Breslow ties)": fits["breslow"].params}, index=m.model.exog_names)
t["log HR (Efron ties)"] = m.params
print(f"Cox model for death: {len(df):,} people, {df.died.sum()} deaths")
print(t.round(3).to_string())
Cox model for death: 6,224 people, 432 deaths
HR 95% CI low 95% CI high p log HR (Breslow ties) log HR (Efron ties)
age10 2.442 2.180 2.735 0.000 0.893 0.893
male 1.102 0.912 1.332 0.312 0.097 0.098
qc 1.149 0.947 1.395 0.160 0.139 0.139
heart_failure 1.549 1.234 1.944 0.000 0.437 0.437
copd 1.384 1.022 1.875 0.036 0.325 0.325
hypertension 0.863 0.686 1.084 0.205 -0.148 -0.148
nephrology_visit 1.216 1.005 1.472 0.044 0.196 0.196
insulin 1.053 0.847 1.308 0.643 0.051 0.051
log_base 1.002 0.917 1.094 0.970 0.002 0.002
Each decade of age multiplies the hazard of death by 2.44. Heart failure multiplies it by 1.55 (95% CI 1.23 to 1.94), COPD by 1.38. Quebec's HR of 1.15 has a wide interval that includes 1.
Ties. When several people have the event on the same day, the partial likelihood needs a rule. Breslow's is the simpler approximation; Efron's is more accurate, and it is R's default. statsmodels defaults to Breslow. With death dates spread over the year, the two agree to the third decimal here. With weekly or monthly time they can differ, so state which you used and use the same one in every language.
Check it in R (survival::coxph, Efron ties):
# Day 13: Kaplan-Meier, log-rank and Cox in R with the survival package, plus R's PH test (cox.zph).
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(survival) })
con <- dbConnect(duckdb(shared_home = FALSE))
df <- dbGetQuery(con, "SELECT * FROM read_parquet('m2/analysis.parquet')")
dbDisconnect(con, shutdown = TRUE)
df <- transform(df, age10 = (age - 75) / 10, male = as.integer(sex == "M"), qc = as.integer(province == "QC"),
log_base = log(base_cost + 100))
km <- survfit(Surv(t_end, died) ~ heart_failure, data = df)
s <- summary(km, times = 365)
cat(sprintf("S(365): no HF %.3f, HF %.3f\n", s$surv[1], s$surv[2]))
lr <- survdiff(Surv(t_end, died) ~ heart_failure, data = df)
cat(sprintf("log-rank chi2 %.1f\n", lr$chisq))
fit <- coxph(Surv(t_end, died) ~ age10 + male + qc + heart_failure + copd + hypertension + nephrology_visit +
insulin + log_base, data = df) # R's default ties method is Efron
cat("\nCox model for death (Efron ties): log HR and HR\n")
for (k in names(coef(fit))) cat(sprintf(" %-22s %7.3f %7.3f\n", k, coef(fit)[k], exp(coef(fit)[k])))
cat("\nProportional hazards test, cox.zph (rank of time):\n")
z <- cox.zph(fit, transform = "rank")
print(round(z$table, 3))
S(365): no HF 0.943, HF 0.860
log-rank chi2 88.6
Cox model for death (Efron ties): log HR and HR
age10 0.893 2.442
male 0.098 1.102
qc 0.139 1.149
heart_failureTRUE 0.437 1.549
copdTRUE 0.325 1.384
hypertensionTRUE -0.148 0.863
nephrology_visitTRUE 0.196 1.216
insulinTRUE 0.051 1.053
log_base 0.002 1.002
Proportional hazards test, cox.zph (rank of time):
chisq df p
age10 0.950 1 0.330
male 0.532 1 0.466
qc 0.606 1 0.436
heart_failure 0.346 1 0.556
copd 5.704 1 0.017
hypertension 1.032 1 0.310
nephrology_visit 0.449 1 0.503
insulin 0.219 1 0.640
log_base 0.030 1 0.863
GLOBAL 9.647 9 0.380
The Kaplan–Meier values, the log-rank statistic and every coefficient match Python. The proportional hazards table at the end is for 13.5.
13.5 Checking proportional hazards (35 min)
The Cox model assumes each HR is constant over time. Schoenfeld residuals test it. At each event, compare the person who had the event with the risk-weighted average of everyone at risk. Scaled, the residuals estimate $\beta(t)$, the log HR at time $t$. If the hazards are proportional, $\beta(t)$ is flat.
def schoenfeld(time, event, X, beta):
"""Schoenfeld residuals: for each event, the person's covariates minus the risk-weighted mean
covariates of everyone still at risk at that time (Breslow handling of ties).
Returns (event times, residual matrix with one row per event). Under proportional hazards the
residuals have no trend over time."""
t, e = np.asarray(time), np.asarray(event).astype(bool)
X = np.asarray(X, dtype=float)
w = np.exp(X @ np.asarray(beta))
order = np.argsort(-t, kind="stable") # latest first: cumulative sums give risk sets
ts = t[order]
cw = np.cumsum(w[order])
cwx = np.cumsum(w[order, None] * X[order], axis=0)
last = np.searchsorted(-ts, -t, side="right") - 1 # last row (in sorted order) with time >= t_i
mean_x = cwx[last] / cw[last, None]
return t[e], X[e] - mean_x[e]
"""Day 13.5: do the hazards stay proportional? Scaled Schoenfeld residuals against time."""
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 statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import admission_outcome, ph_test # noqa: E402
df = load()
df["t_adm"], df["admitted"] = admission_outcome(df)
fig, ax = plt.subplots(1, 2, figsize=(9.5, 3.4))
for i, (t, e, label) in enumerate((("t_end", "died", "death"), ("t_adm", "admitted", "first admission"))):
m = PHReg.from_formula(f"{t} ~ {COVARIATES}", df, status=df[e], ties="breslow").fit()
times, scaled, tests = ph_test(m, df[t], df[e])
print(f"--- {label} ({len(times):,} events): correlation of scaled Schoenfeld residuals with rank of time")
for name, rho, p in tests:
print(f" {name:<17} rho {rho:+.3f} p {p:.3f}" + (" <- look at the plot" if p < 0.01 else ""))
j = m.model.exog_names.index("heart_failure")
order = np.argsort(times)
k = 51 if i == 0 else 151
smooth = np.convolve(scaled[order, j], np.ones(k) / k, mode="valid")
ax[i].plot(times[order][k // 2: -(k // 2)], smooth, color="#e5484d", lw=2, label="moving average")
ax[i].axhline(m.params[j], color="#4f9cf9", lw=1.5, ls="--", label=f"Cox log HR {m.params[j]:.2f}")
ax[i].set(title=f"Heart failure: beta(t), {label}", xlabel="day of event", xlim=(0, 365))
ax[i].legend(loc="upper right", fontsize=8)
ax[0].set_ylabel("scaled Schoenfeld residual")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day13_schoenfeld.png"), dpi=130)
--- death (432 events): correlation of scaled Schoenfeld residuals with rank of time
age10 rho +0.002 p 0.963
male rho -0.019 p 0.692
qc rho -0.066 p 0.171
heart_failure rho +0.032 p 0.506
copd rho +0.138 p 0.004 <- look at the plot
hypertension rho +0.006 p 0.909
nephrology_visit rho +0.114 p 0.017
insulin rho +0.030 p 0.532
log_base rho -0.011 p 0.817
--- first admission (1,874 events): correlation of scaled Schoenfeld residuals with rank of time
age10 rho -0.009 p 0.682
male rho +0.030 p 0.197
qc rho -0.029 p 0.214
heart_failure rho +0.031 p 0.180
copd rho +0.038 p 0.099
hypertension rho +0.033 p 0.158
nephrology_visit rho +0.023 p 0.322
insulin rho -0.019 p 0.422
log_base rho +0.002 p 0.938

For heart failure, the moving average wanders around the Cox estimate with no trend, for death and for admission. Two death covariates have small p-values in this quick check: COPD (0.004) and nephrology visit (0.017). R's cox.zph (13.4) is the proper Grambsch–Therneau test, with the full variance. It gives 0.017 for COPD, 0.50 for nephrology, and a global p of 0.38. Read a PH check in three steps:
- Use the formal test from a tested implementation (
cox.zphin R,PROC PHREGwithASSESS PHin SAS). The quick Python version is for plots and screening. - Correct for the number of tests. Nine covariates at 0.05 will flag one by chance about a third of the time.
- Look at the plot. A real violation (a treatment effect that fades, a surgical risk that is early) shows as a clear trend. If it's there, Day 14's parametric and time-varying models handle it.
13.6 Truth check: does Cox recover the generator? (30 min)
The generator decides each 2025 death with a logistic model: log odds of death rise 0.09 per year of age, 0.6 with heart failure, 0.5 with CKD stage 4–5, 0.3 with COPD, 0.25 with diabetes and 0.2 per unit of log frailty. Death dates are spread evenly over the year. For a rare event, log odds ratios and log hazard ratios are close. So a Cox model with the true covariates, in everyone alive on 1 January 2025, should land near those numbers.
"""Day 13.6 (truth check): does Cox recover the generator's death model?
The generator draws each person's 2025 death from a logistic model in age, heart failure, CKD stage 4-5,
COPD, diabetes and log(frailty), and a date uniform over the year. For a rare event the log odds ratios
are close to log hazard ratios. With the TRUE covariates, Cox should land near the generator's numbers.
"""
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 statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.db import DATA # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.truth import TRUTH # noqa: E402
GENERATOR = {"age10": 0.9, "hf": 0.6, "ckd45": 0.5, "copd": 0.3, "dm": 0.25, "log_frailty": 0.2}
data = DATA.replace("\\", "/")
pop = duckdb.sql(f"""
SELECT p.person_id, (2025 - year(p.birth_date) - 1 - 75) / 10 AS age10,
t.heart_failure AS hf, coalesce(t.ckd_stage IN ('4', '5'), false)::INT AS ckd45, t.copd,
t.diabetes AS dm, ln(t.frailty + 0.01) AS log_frailty,
(u.death_date IS NOT NULL)::INT AS died,
coalesce(date_diff('day', DATE '2025-01-01', u.death_date) + 1, 365) AS t_end
FROM read_csv('{data}/persons.csv') p
JOIN read_csv('{TRUTH}/persons_truth.csv') t USING (person_id)
LEFT JOIN read_csv('{data}/registry_updates_2025.csv') u USING (person_id)
WHERE p.death_date IS NULL -- alive on 1 January 2025
ORDER BY p.person_id""").df()
x = " + ".join(GENERATOR)
# Newton's method (the default) overshoots from its zero start on 250,000 rows and returns NaN;
# BFGS gets close, and Newton finishes. Always check convergence on a big fit: the score (gradient) must be about 0.
model = PHReg.from_formula(f"t_end ~ {x}", pop, status=pop.died, ties="breslow")
start = model.fit(method="bfgs").params # BFGS gets close ...
m = model.fit(start_params=start) # ... then Newton finishes from there
grad = np.abs(m.model.score(m.params)).max()
assert grad < 0.1, f"not converged (largest gradient {grad:.3g})"
t = pd.DataFrame({"generator": GENERATOR.values(), "Cox log HR": np.asarray(m.params), "SE": np.asarray(m.bse)}, index=list(GENERATOR))
t["z vs generator"] = (t["Cox log HR"] - t["generator"]) / t["SE"]
print(f"Whole population alive on 1 January 2025: {len(pop):,} people, {pop.died.sum():,} deaths in 2025")
print(t.round(3).to_string())
c = load().merge(pop[["person_id", "hf", "ckd45", "copd", "log_frailty"]].rename(columns={"copd": "copd_t"}),
on="person_id")
c = c.drop(columns="age10")
c["age10"] = (c["age"] - 75) / 10
mc = PHReg.from_formula("t_end ~ age10 + hf + ckd45 + copd_t + log_frailty", c, status=c.died, ties="efron").fit()
hf = list(mc.model.exog_names).index("hf")
lo, hi = mc.params[hf] - 1.96 * mc.bse[hf], mc.params[hf] + 1.96 * mc.bse[hf]
print(f"\nSame model in the 6,224-person cohort ({c.died.sum()} deaths): log HR for true heart failure "
f"{mc.params[hf]:.3f} (95% CI {lo:.3f} to {hi:.3f}); generator 0.6")
Whole population alive on 1 January 2025: 247,521 people, 2,495 deaths in 2025
generator Cox log HR SE z vs generator
age10 0.90 0.879 0.016 -1.332
hf 0.60 0.504 0.059 -1.632
ckd45 0.50 0.423 0.079 -0.977
copd 0.30 0.351 0.070 0.723
dm 0.25 0.286 0.045 0.799
log_frailty 0.20 0.224 0.045 0.538
Same model in the 6,224-person cohort (432 deaths): log HR for true heart failure 0.366 (95% CI 0.150 to 0.581); generator 0.6
In the whole population (2,495 deaths), every estimate is within 1.7 standard errors of the generator's value. In the 6,224-person cohort, with 432 deaths, the same model gives 0.37 for heart failure, with an interval (0.15 to 0.58) that just misses 0.6. With a few hundred events, an estimate two standard errors from the truth is not rare: about one in twenty of them is that far off. One cohort's hazard ratio is one draw from a sampling distribution. Report the interval, not only the point.
Two practical notes from the big fit. statsmodels' default Newton method returns NaN on 250,000 rows from its zero starting point, so the script starts it from a BFGS solution and checks that the gradient is close to zero. Silent non-convergence is a real risk in large fits: always check.
Why it matters at work: Hazard ratios from RWE and trials become the treatment effects in CDA-AMC and INESSS models. Reviewers ask about the PH assumption, the ties method and the number of events behind each estimate, and they discount HRs with wide intervals.
Where you'll meet this: survival inputs for partitioned survival and Markov models (Module 6) · indirect comparisons of hazard ratios (Module 7) · RWE studies of mortality and hospitalization (Module 3)
13.7 The status column (15 min)
Bug of the day. An analyst who learned SAS writes time*censored(1) in PROC LIFETEST, where the value in brackets names the censoring code. In Python they pass the same censored column as status:
"""Day 13 bug of the day: the status column means the opposite of what the function expects."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from statsmodels.duration.survfunc import SurvfuncRight # noqa: E402
from corridor.m2 import load # noqa: E402
df = load()
df["censored"] = 1 - df["died"] # SAS habit: PROC LIFETEST ... time*censored(1)
wrong = SurvfuncRight(df.t_end, df.censored) # the bug: statsmodels wants 1 = EVENT
right = SurvfuncRight(df.t_end, df.died)
print(f"one-year survival, status = censored: {wrong.surv_prob[-1]:.3f}")
print(f"one-year survival, status = died: {right.surv_prob[-1]:.3f}")
print(f"share who died: {df.died.mean():.3f}")
one-year survival, status = censored: 0.001
one-year survival, status = died: 0.931
share who died: 0.069
One-year "survival" comes out at 0.1%: the curve now estimates time to censoring. statsmodels' status, R's Surv(time, event) and lifelines' event_observed all expect 1 = event. SAS asks for the censoring value. Name the column for what 1 means (died, admitted), and sanity-check every curve against the simple proportion.
13.8 Mini-project: what predicts a first admission? (35 min)
Fit a Cox model for time to first admission, with death censoring. Compare its hazard ratios with odds ratios from a logistic regression of "admitted in 2025, yes or no", which ignores timing.
"""Day 13 mini-project: what predicts a first hospital admission? Cox against logistic regression."""
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 statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import admission_outcome # noqa: E402
df = load()
df["t_adm"], df["admitted"] = admission_outcome(df)
print(f"{len(df):,} people, {df.admitted.sum():,} first admissions, "
f"{((df.died == 1) & (df.admitted == 0)).sum()} deaths without an admission (censored)")
print(f"median days to first admission among the admitted: {df.t_adm[df.admitted == 1].median():.0f}")
cox = PHReg.from_formula(f"t_adm ~ {COVARIATES}", df, status=df.admitted, ties="efron").fit()
logit = smf.logit(f"admitted ~ {COVARIATES}", df).fit(disp=0)
ci = cox.conf_int()
t = pd.DataFrame({"Cox HR": np.exp(cox.params), "HR 95% CI": [f"{np.exp(a):.2f}-{np.exp(b):.2f}" for a, b in ci],
"logistic OR": np.exp(logit.params.drop("Intercept").to_numpy())},
index=cox.model.exog_names)
print("\nFirst admission in 2025: hazard ratios (Cox) and odds ratios (logistic, ignores timing)")
print(t.round(3).to_string())
6,224 people, 1,874 first admissions, 165 deaths without an admission (censored)
median days to first admission among the admitted: 158
First admission in 2025: hazard ratios (Cox) and odds ratios (logistic, ignores timing)
Cox HR HR 95% CI logistic OR
age10 1.074 1.02-1.14 1.063
male 0.999 0.91-1.09 1.003
qc 0.936 0.85-1.03 0.902
heart_failure 2.296 2.05-2.57 2.931
copd 1.490 1.27-1.75 1.781
hypertension 1.022 0.92-1.14 1.041
nephrology_visit 1.414 1.29-1.55 1.525
insulin 1.052 0.95-1.17 1.075
log_base 1.047 1.00-1.09 1.050
Heart failure more than doubles the admission hazard (HR 2.30), and the logistic OR is larger (2.93). The two aren't estimating the same thing. With 30% of people admitted, the outcome is not rare, so odds ratios are further from 1 than risk ratios or hazard ratios. The logistic model also treats the 165 people who died before any admission as "not admitted", as if they had been at risk all year. When follow-up time varies or the event is common, use the hazard ratio.
Write three sentences for the burden-of-illness report: which characteristics predict a first admission, by how much, and what the HRs do and do not tell a payer (they give relative speed, not the number of admissions; Day 12 gives that).
13.9 Save your work
python -m pytest -q
git add .
git commit -m "Day 13: Kaplan-Meier, log-rank, Cox, PH checks, truth check"
Day 13 checklist
- I build every survival dataset with a time column and a status column where 1 = event
- I can compute a Kaplan–Meier curve by hand with censoring, and explain why it differs from a simple proportion
- I compare groups with the log-rank test and quantify differences with a Cox model
- I report HRs with CIs, the ties method and the number of events, and I check proportional hazards
- I can explain why a cohort HR can miss the true value by two standard errors
Bloc français (30 min)
Thème : l'analyse de survie.
Dans une analyse de survie, chaque personne a une durée de suivi et un indicateur d'événement. Une personne encore vivante à la fin de l'étude est censurée : on sait seulement qu'elle a survécu au moins jusqu'à cette date. L'estimateur de Kaplan-Meier tient compte de la censure. Le modèle de Cox estime des rapports de risques instantanés, en supposant que ces rapports restent constants dans le temps.
| Français | English |
|---|---|
| l'analyse de survie | survival analysis |
| la durée de suivi | the follow-up time |
| l'indicateur d'événement | the event indicator (status) |
| une observation censurée | a censored observation |
| l'estimateur de Kaplan-Meier | the Kaplan–Meier estimator |
| la courbe de survie | the survival curve |
| le test du log-rank | the log-rank test |
| le modèle à risques proportionnels de Cox | the Cox proportional hazards model |
| le rapport de risques instantanés (RRI) | the hazard ratio (HR) |
| le risque de base | the baseline hazard |
| les résidus de Schoenfeld | Schoenfeld residuals |
| le premier séjour hospitalier | the first hospital admission |
Exercices
- Translate: "A person who died without an admission is censored at the date of death."
- Translate: « L'insuffisance cardiaque multiplie le risque instantané de décès par 1,55. »
- In three French sentences, explain why Kaplan–Meier is better than the proportion of people without the event.
Réponses
- Une personne décédée sans hospitalisation est censurée à la date du décès.
- "Heart failure multiplies the hazard of death by 1.55."
- Example: La simple proportion considère que les personnes censurées ont été suivies jusqu'à la fin. Kaplan-Meier les garde dans le groupe à risque seulement jusqu'à leur date de censure. Il utilise donc toute l'information disponible sans la surestimer.