The Cox model and hazard ratios
Adjust for covariates without assuming a baseline hazard, read hazard ratios correctly, and check how well the model ranks people.
What runs in CodeSplash
- Cox proportional hazards regression Verified in Python and R
You will be able to
- Interpret a hazard ratio and its confidence interval
- Explain what the Cox model assumes and what it leaves unspecified
- Read Harrell's concordance and events per variable on a Cox card
Read first
A model without a baseline
ReadThe Cox modelCox modelModels how predictors multiply the hazard, while leaving the baseline hazard unspecified. says each person's hazard is a shared baseline, scaled up or down by their covariates:
The clever part is that is never estimated or assumed. You get hazard ratiosHazard ratioThe ratio of instantaneous event rates between groups; 0.7 means a 30% lower rate at any moment., , without saying what shape the baseline has.
The price is an assumption: the ratio between any two people's hazards stays constant over time. You will test it in the next lesson.
Read a hazard ratio
PredictPredict first
In the Veterans' lung cancer trial, the Cox model compares cell types with squamous as the reference, adjusting for age. The hazard ratio for small-cell comes out a little under 3.
Which reading is right?
Reveal
The second. Small-cell versus squamous: HR = 2.70 (95% interval 1.64 to 4.44). It compares rates among those still event-free, not survival times, and not the eventual share who die.
Read the card
In the appFind the hazard ratios, the overall likelihood-ratio test, the concordanceConcordance indexThe share of usable pairs where the person with the higher predicted risk has the event first. 0.5 is chance. and the events-per-variable figure.
HR = 1.02, 95% CI [1.00, 1.04], p = .065
- Likelihood-ratio χ²
- 14.123
- df
- 2
- p
- < .001
- Concordance (C, apparent)
- 0.6029
- AIC
- 1489.70
Effect size
- Hazard ratio (age) 1.017 95% CI [0.9990, 1.036]
Plots
View data
| Hazard ratio | upper | Term | lower |
|---|---|---|---|
| 1.017 | 1.036 | age | 0.9990 |
| 0.5986 | 0.8311 | sex: female | 0.4311 |
View data
| β(t) | Term | time |
|---|---|---|
| 0.0404 | age | 5 |
| 0.1537 | age | 11 |
| 0.2519 | age | 11 |
| 0.0554 | age | 11 |
| 0.1555 | age | 12 |
| 0.1848 | age | 13 |
| 0.0304 | age | 13 |
| 0.0874 | age | 15 |
| 0.1440 | age | 26 |
| 0.1308 | age | 30 |
| 0.2719 | age | 31 |
| −0.0209 | age | 53 |
| 0.0773 | age | 53 |
| 0.1336 | age | 54 |
| 0.1484 | age | 59 |
| 0.0511 | age | 60 |
| 0.0230 | age | 60 |
| −0.0751 | age | 61 |
| 0.0509 | age | 62 |
| −0.0050 | age | 65 |
| 0.0792 | age | 65 |
| −0.0329 | age | 71 |
| 0.0370 | age | 79 |
| −0.1738 | age | 81 |
| −0.1457 | age | 81 |
| −0.0766 | age | 88 |
| 0.0497 | age | 88 |
| −0.1751 | age | 92 |
| 0.1609 | age | 93 |
| 0.2041 | age | 95 |
| −0.1047 | age | 95 |
| −0.0063 | age | 105 |
| −0.0197 | age | 107 |
| 0.0084 | age | 107 |
| 0.0223 | age | 110 |
| 0.1907 | age | 116 |
| 0.1079 | age | 118 |
| 0.0103 | age | 122 |
| −0.1722 | age | 131 |
| −0.0754 | age | 132 |
| −0.3141 | age | 132 |
| −0.0348 | age | 135 |
| 0.0070 | age | 142 |
| 0.0630 | age | 144 |
| −0.0210 | age | 145 |
| −0.1193 | age | 145 |
| −0.0215 | age | 147 |
| 0.1608 | age | 153 |
| 0.0490 | age | 156 |
| −0.1054 | age | 156 |
| 0.0910 | age | 163 |
| 0.1331 | age | 163 |
| −0.1196 | age | 163 |
| −0.0208 | age | 166 |
| 0.1196 | age | 166 |
| −0.2452 | age | 167 |
| −0.0776 | age | 170 |
| 0.1464 | age | 175 |
| 0.1472 | age | 176 |
| −0.0481 | age | 177 |
First 60 of 330 rows.
View data
| Martingale residual | Predictor | Predictor value |
|---|---|---|
| 0.0044 | age | 74 |
| −0.5058 | age | 68 |
| −3.130 | age | 56 |
| 0.5328 | age | 57 |
| −2.351 | age | 60 |
| −4.254 | age | 74 |
| 0.4475 | age | 68 |
| 0.2900 | age | 71 |
| 0.5483 | age | 53 |
| 0.6806 | age | 61 |
| 0.6856 | age | 57 |
| −0.4190 | age | 68 |
| −0.7272 | age | 68 |
| 0.8848 | age | 60 |
| −0.6192 | age | 57 |
| 0.7233 | age | 67 |
| −1.185 | age | 70 |
| −1.558 | age | 63 |
| 0.9479 | age | 56 |
| 0.8665 | age | 57 |
| 0.1622 | age | 67 |
| 0.9359 | age | 49 |
| −0.5980 | age | 50 |
| −0.0266 | age | 58 |
| −0.3860 | age | 72 |
| −0.0548 | age | 70 |
| −0.7475 | age | 60 |
| 0.7603 | age | 70 |
| 0.0150 | age | 53 |
| 0.9685 | age | 74 |
| 0.0266 | age | 69 |
| 0.9435 | age | 73 |
| −0.2934 | age | 48 |
| 0.8916 | age | 60 |
| 0.9353 | age | 61 |
| 0.8710 | age | 62 |
| −2.367 | age | 65 |
| −2.222 | age | 66 |
| 0.8035 | age | 74 |
| −0.6731 | age | 64 |
| −0.6209 | age | 70 |
| 0.7975 | age | 73 |
| 0.2836 | age | 59 |
| 0.8473 | age | 60 |
| −1.055 | age | 68 |
| 0.8715 | age | 76 |
| 0.0392 | age | 74 |
| −0.5306 | age | 63 |
| −1.548 | age | 74 |
| −0.4247 | age | 50 |
| −0.9904 | age | 72 |
| 0.5596 | age | 63 |
| 0.9271 | age | 68 |
| 0.4257 | age | 58 |
| −1.235 | age | 59 |
| 0.8894 | age | 62 |
| 0.9968 | age | 65 |
| 0.7875 | age | 57 |
| −0.2735 | age | 58 |
| 0.4314 | age | 64 |
First 60 of 228 rows.
View data
| Event | Series | Unit exponential F(r) | Cox–Snell residual |
|---|---|---|---|
| 1 | data | — | 0.9956 |
| 1 | data | — | 1.506 |
| 0 | data | — | 3.130 |
| 1 | data | — | 0.4672 |
| 1 | data | — | 3.351 |
| 0 | data | — | 4.254 |
| 1 | data | — | 0.5525 |
| 1 | data | — | 0.7100 |
| 1 | data | — | 0.4517 |
| 1 | data | — | 0.3194 |
| 1 | data | — | 0.3144 |
| 1 | data | — | 1.419 |
| 1 | data | — | 1.727 |
| 1 | data | — | 0.1152 |
| 1 | data | — | 1.619 |
| 1 | data | — | 0.2767 |
| 1 | data | — | 2.185 |
| 1 | data | — | 2.558 |
| 1 | data | — | 0.0521 |
| 1 | data | — | 0.1335 |
| 1 | data | — | 0.8378 |
| 1 | data | — | 0.0641 |
| 1 | data | — | 1.598 |
| 1 | data | — | 1.027 |
| 1 | data | — | 1.386 |
| 1 | data | — | 1.055 |
| 1 | data | — | 1.748 |
| 1 | data | — | 0.2397 |
| 1 | data | — | 0.9850 |
| 1 | data | — | 0.0315 |
| 1 | data | — | 0.9734 |
| 1 | data | — | 0.0565 |
| 1 | data | — | 1.293 |
| 1 | data | — | 0.1084 |
| 1 | data | — | 0.0647 |
| 1 | data | — | 0.1290 |
| 1 | data | — | 3.367 |
| 0 | data | — | 2.222 |
| 1 | data | — | 0.1965 |
| 1 | data | — | 1.673 |
| 1 | data | — | 1.621 |
| 1 | data | — | 0.2025 |
| 1 | data | — | 0.7164 |
| 1 | data | — | 0.1527 |
| 1 | data | — | 2.055 |
| 1 | data | — | 0.1285 |
| 1 | data | — | 0.9608 |
| 1 | data | — | 1.531 |
| 1 | data | — | 2.548 |
| 1 | data | — | 1.425 |
| 1 | data | — | 1.990 |
| 1 | data | — | 0.4404 |
| 1 | data | — | 0.0729 |
| 1 | data | — | 0.5743 |
| 1 | data | — | 2.235 |
| 1 | data | — | 0.1106 |
| 1 | data | — | 0.0032 |
| 1 | data | — | 0.2125 |
| 1 | data | — | 1.273 |
| 1 | data | — | 0.5686 |
First 60 of 288 rows.
Assumptions
- Proportional hazards — Global Grambsch–Therneau χ²(2) = 2.77, p = .250; no evidence that hazard ratios change over time.
- Events per variable — 82.5 events per coefficient.
- Non-informative censoring — 63 of 228 observations are censored.
- Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
- Influential observations — Largest |DFBETAS| = 0.42; 18 of 228 subjects above 2/√n = 0.13.
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0170 | 0.0092 | 1.017 | 0.9990 | 1.036 | 1.848 | .065 |
| sex: female | −0.5132 | 0.1675 | 0.5986 | 0.4311 | 0.8311 | −3.065 | .002 |
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 14.123 | 2 | < .001 |
| Wald | 13.473 | 2 | .001 |
| Score (log-rank) | 13.722 | 2 | .001 |
Proportional-hazards test (Grambsch–Therneau)
| Term | χ² | df | p |
|---|---|---|---|
| age | 0.2092 | 1 | .647 |
| sex | 2.608 | 1 | .106 |
| Global | 2.771 | 2 | .250 |
Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6029 | 0.5529 | 0.6528 | Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife). |
| AIC | 1489.70 | — | — | −2 log partial likelihood + 2k. |
| BIC | 1495.91 | — | — | −2 log partial likelihood + k·log(events), events = 165. |
The apparent C is optimistic for new data; the bootstrap option estimates by how much.
Most influential subjects
| Row | Term most affected | DFBETA | DFBETAS | Martingale residual |
|---|---|---|---|---|
| 6 | age | −0.0039 | −0.4236 | −4.254 |
| 85 | age | 0.0036 | 0.3922 | −2.239 |
| 38 | sex: female | −0.0436 | −0.2604 | −2.222 |
| 68 | sex: female | −0.0379 | −0.2265 | −1.981 |
| 3 | age | 0.0019 | 0.2079 | −3.130 |
| 89 | age | 0.0019 | 0.2061 | −1.235 |
| 74 | age | −0.0017 | −0.1827 | 0.8410 |
| 71 | sex: female | 0.0292 | 0.1746 | −3.254 |
| 129 | age | −0.0016 | −0.1712 | −1.298 |
| 149 | age | 0.0014 | 0.1541 | 0.9190 |
Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.
- Event: dead = true. Ties: efron.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec be108a13077d2af0
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "dead", "age", "sex")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead", "age", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "dead", "age", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "dead"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
event_level <- "true" # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Predictors (treatment contrasts against the first stored level)
preds <- c("age", "sex")
dd <- data.frame(.t = tt, .e = ev)
labels <- character(0)
for (pname in preds) {
x <- df[[pname]]
if (is.factor(x)) {
if (nlevels(x) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pname, min = 2, k = nlevels(x)) # a factor needs two levels with data
labels <- c(labels, paste0(pname, ": ", levels(x)[-1]))
} else {
labels <- c(labels, pname)
}
dd[[pname]] <- x
}
rhs <- paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ")
# %% Cox model
conf <- 0.95
ties <- "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname <- NULL
fit <- coxph(stats::as.formula(paste("Surv(.t, .e) ~", rhs)), data = dd, ties = ties,
control = coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60))
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(vcov(fit))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
q <- stats::qnorm(1 - (1 - conf) / 2)
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
lr_p <- stats::pchisq(lr, k, lower.tail = FALSE)
wald <- drop(beta %*% solve(V, beta))
score <- unname(fit$score)
cc <- concordance(fit) # var: infinitesimal-jackknife variance of C
conc <- unname(cc$concordance)
one_time <- length(unique(tt[ev])) < 2 # with every event at one time the proportional-hazards test is undefined
if (one_time) {
warnings <- c(warnings, cs_warning("CS_W_TIES", column = tcol, consequence = "every event happened at the same time, so the proportional-hazards test is not computed."))
zph <- NULL
zt <- matrix(NA_real_, length(preds) + 1, 3)
} else {
zph <- cox.zph(fit, transform = "km")
zt <- unname(zph$table)
}
ph_chisq <- zt[nrow(zt), 1]
ph_p <- zt[nrow(zt), 3]
# %% Fit measures and the apparent concordance
aic <- -2 * fit$loglik[2] + 2 * k
bic <- -2 * fit$loglik[2] + k * log(sum(ev)) # n = the number of events, as BIC() for coxph
c_se <- sqrt(unname(cc$var))
ci_ok <- is.finite(conc) && is.finite(c_se)
c_lo <- if (ci_ok) max(0, conc - q * c_se) else NA_real_
c_hi <- if (ci_ok) min(1, conc + q * c_se) else NA_real_
# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
mart <- unname(residuals(fit, type = "martingale"))
cox_snell <- ev - mart
dfb <- unname(as.matrix(residuals(fit, type = "dfbeta"))) # one-step change in each coefficient when the row is left out
dfbs <- sweep(dfb, 2, se, "/")
abs_dfbs <- abs(dfbs)
infl_cut <- 2 / sqrt(length(tt))
n_infl <- sum(apply(abs_dfbs, 1, max) > infl_cut)
max_dfbs <- max(abs_dfbs)
num_preds <- preds[vapply(preds, function(p) is.numeric(df[[p]]) && length(unique(df[[p]])) > 2, logical(1))]
optimism <- NA_real_
c_corrected <- NA_real_
boot_used <- 0
values <- list(
n = length(tt), events = sum(ev), n_coef = k, loglik = fit$loglik[2], loglik0 = fit$loglik[1],
lr_chisq = lr, lr_df = k, lr_p = lr_p,
wald_chisq = wald, wald_p = stats::pchisq(wald, k, lower.tail = FALSE),
score_chisq = score, score_p = stats::pchisq(score, k, lower.tail = FALSE),
concordance = conc, ph_chisq = ph_chisq, ph_p = ph_p,
coef_1_label = labels[1], hr_1 = hr[1], hr_1_low = hr_lo[1], hr_1_high = hr_hi[1], p_1 = pv[1],
epv = sum(ev) / k, event_label = event_label,
aic = aic, bic = bic, concordance_se = c_se, concordance_low = c_lo, concordance_high = c_hi,
max_abs_dfbetas = max_dfbs, n_influential = n_infl, martingale_min = min(mart), martingale_max = max(mart),
optimism = optimism, concordance_corrected = c_corrected, boot_used = boot_used
)
coef_rows <- list()
for (i in seq_along(labels)) {
lab <- labels[i]
vals <- list(coef = beta[i], se = se[i], hr = hr[i], hr_low = hr_lo[i], hr_high = hr_hi[i], z = z[i], p = pv[i])
for (key in names(vals)) values[[sprintf("%s[%s]", key, lab)]] <- vals[[key]]
values[[sprintf("dfbetas_max[%s]", lab)]] <- max(abs_dfbs[, i])
coef_rows[[i]] <- c(list(term = lab), vals)
}
ph_rows <- list()
for (i in seq_along(preds)) {
values[[sprintf("ph_chisq[%s]", preds[i])]] <- zt[i, 1]
values[[sprintf("ph_p[%s]", preds[i])]] <- zt[i, 3]
ph_rows[[i]] <- list(term = preds[i], chisq = zt[i, 1], df = zt[i, 2], p = zt[i, 3])
}
ph_rows[[length(ph_rows) + 1]] <- list(term = "Global", chisq = ph_chisq, df = k, p = ph_p)
# %% Assumptions
bad <- preds[which(zt[seq_along(preds), 3] < 0.05)]
ph_check <- if (one_time) {
list(key = "proportional_hazards", label = "Proportional hazards", status = "info", detail = "Not tested: every event happened at the same time.")
} else {
list(key = "proportional_hazards", label = "Proportional hazards", status = if (ph_p < 0.05 || length(bad)) "warn" else "pass",
statistic = ph_chisq, p = ph_p,
detail = paste0(sprintf("Global Grambsch–Therneau χ²(%d) = %.2f, %s", k, ph_chisq, cs_fmt_p(ph_p)),
if (length(bad)) sprintf(paste0("; time-varying effect for %s. Consider stratifying by %s, a time-varying",
" effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."),
paste(bad, collapse = ", "), if (length(bad) == 1) "it" else "them")
else "; no evidence that hazard ratios change over time."))
}
assumptions <- list(
ph_check,
list(key = "events_per_variable", label = "Events per variable", status = if (values$epv < 10) "warn" else "pass",
detail = paste0(sprintf("%.1f events per coefficient", values$epv),
if (values$epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev))),
list(key = "functional_form", label = "Functional form", status = "info",
detail = if (length(num_preds)) sprintf(paste0("Not tested: look at the martingale residuals against %s. A smooth that bends away from zero",
" suggests a transformation or a spline."), paste(num_preds, collapse = ", "))
else "No numeric predictor with more than two values to check."),
list(key = "influence", label = "Influential observations", status = if (max_dfbs > 1) "warn" else "pass", statistic = max_dfbs,
detail = paste0(sprintf("Largest |DFBETAS| = %.2f; %d of %d subjects above 2/√n = %.2f", max_dfbs, n_infl, length(tt), infl_cut),
if (max_dfbs > 1) ". At least one subject moves a coefficient by more than one standard error." else "."))
)
# %% Charts: hazard ratios and scaled Schoenfeld residuals
sch <- if (one_time) matrix(numeric(0), 0, k) else as.matrix(zph$y)
sch_times <- if (one_time) numeric(0) else zph$time
rows_sch <- seq_len(nrow(sch))
if (length(rows_sch) * k > 5000) rows_sch <- unique(round(seq(1, nrow(sch), length.out = max(5000 %/% k, 2))))
sch_time <- rep(sch_times[rows_sch], k)
sch_res <- as.vector(sch[rows_sch, , drop = FALSE])
sch_term <- rep(labels, each = length(rows_sch))
# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x <- numeric(0)
mart_r <- numeric(0)
mart_term <- character(0)
if (length(num_preds)) {
rows_m <- seq_along(tt)
if (length(rows_m) * length(num_preds) > 5000) rows_m <- unique(round(seq(1, length(tt), length.out = max(5000 %/% length(num_preds), 2))))
for (pname in num_preds) {
mart_x <- c(mart_x, as.numeric(df[[pname]])[rows_m])
mart_r <- c(mart_r, mart[rows_m])
mart_term <- c(mart_term, rep(pname, length(rows_m)))
}
}
rows_cs <- seq_along(tt)
if (length(rows_cs) > 5000) rows_cs <- unique(round(seq(1, length(tt), length.out = 5000)))
cs_fit <- if (max(cox_snell) > 0) seq(0, max(cox_snell), length.out = 61)[-1] else numeric(0)
# %% Influence: the subjects with the largest scaled dfbeta
row_max <- apply(abs_dfbs, 1, max)
top <- head(order(-row_max, seq_along(row_max)), 10)
infl_rows <- lapply(top, function(r) {
j <- which.max(abs_dfbs[r, ])
list(row = r, term = labels[j], dfbeta = dfb[r, j], dfbetas = dfbs[r, j], martingale = mart[r])
})
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fit_rows <- list(
list(measure = "Concordance (C, apparent)", value = conc, low = c_lo, high = c_hi,
note = sprintf("Harrell's C on the data the model was fitted to; SE %.4f (infinitesimal jackknife).", c_se)),
list(measure = "AIC", value = aic, low = NA_real_, high = NA_real_, note = "−2 log partial likelihood + 2k."),
list(measure = "BIC", value = bic, low = NA_real_, high = NA_real_, note = sprintf("−2 log partial likelihood + k·log(events), events = %d.", sum(ev)))
)
if (!is.na(c_corrected)) {
fit_rows <- append(fit_rows, list(list(measure = "Concordance (optimism-corrected)", value = c_corrected, low = NA_real_, high = NA_real_,
note = sprintf("Apparent C minus the mean optimism %.4f over %d bootstrap refits (Harrell).", optimism, boot_used))), after = 1)
}
cs_publish(list(
method = "survival.cox",
methodVersion = "1.1.0",
title = "Cox proportional hazards model",
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = sprintf("Cox model (%d events): likelihood-ratio χ²(%d) = %.2f, %s; apparent concordance %.3f.", sum(ev), k, lr, cs_fmt_p(lr_p), conc),
apa = sprintf("HR = %s, %s CI [%s, %s], %s", cs_fmt_num(hr[1]), pct, cs_fmt_num(hr_lo[1]), cs_fmt_num(hr_hi[1]), cs_fmt_p(pv[1])),
statistics = list(
list(key = "lr_chisq", label = "Likelihood-ratio χ²", value = lr), list(key = "lr_df", label = "df", value = k, format = "integer"),
list(key = "lr_p", label = "p", value = lr_p, format = "p"), list(key = "concordance", label = "Concordance (C, apparent)", value = conc),
list(key = "aic", label = "AIC", value = aic)
),
tables = list(
list(key = "coefficients", title = "Hazard ratios", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "hr", label = "HR", type = "number"),
list(key = "hr_low", label = paste(pct, "CI low"), type = "number"), list(key = "hr_high", label = paste(pct, "CI high"), type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue")
), rows = coef_rows),
list(key = "tests", title = "Overall tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
), rows = list(
list(test = "Likelihood ratio", chisq = lr, df = k, p = lr_p),
list(test = "Wald", chisq = wald, df = k, p = values$wald_p),
list(test = "Score (log-rank)", chisq = score, df = k, p = values$score_p)
)),
list(key = "proportional_hazards", title = "Proportional-hazards test (Grambsch–Therneau)", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
), rows = ph_rows, note = "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."),
list(key = "fit", title = "Model fit", columns = list(
list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number"),
list(key = "note", label = "Note", type = "string")
), rows = fit_rows, note = "The apparent C is optimistic for new data; the bootstrap option estimates by how much."),
list(key = "influence", title = "Most influential subjects", columns = list(
list(key = "row", label = "Row", type = "integer"), list(key = "term", label = "Term most affected", type = "string"),
list(key = "dfbeta", label = "DFBETA", type = "number"), list(key = "dfbetas", label = "DFBETAS", type = "number"),
list(key = "martingale", label = "Martingale residual", type = "number")
), rows = infl_rows, note = "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.")
),
effectSizes = list(list(key = "hr_1", label = sprintf("Hazard ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
ciHigh = hr_hi[1], ciLevel = conf, method = "Wald interval on log(HR)")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Event: %s. Ties: %s.", event_label, ties), if (!is.null(sname)) sprintf(" Stratified by %s.", sname) else "")),
charts = list(
cs_chart("hr", "forest", "Hazard ratios", list(
label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Hazard ratio", hr, "numeric"),
low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
), controls = list(reference = 1, log = TRUE)),
cs_chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", list(
time = cs_col(tcol, sch_time, "numeric"), residual = cs_col("β(t)", sch_res, "numeric"),
term = cs_col("Term", sch_term, "categorical", levels = labels)
)),
if (length(num_preds)) cs_chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", list(
x = cs_col("Predictor value", mart_x, "numeric"), partial = cs_col("Martingale residual", mart_r, "numeric"),
term = cs_col("Predictor", mart_term, "categorical", levels = num_preds)
), controls = list(smooth = TRUE)),
cs_chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", list(
time = cs_col("Cox–Snell residual", c(cox_snell[rows_cs], cs_fit), "numeric"),
event = cs_col("Event", c(as.numeric(ev[rows_cs]), rep(NA_real_, length(cs_fit))), "numeric"),
fit = cs_col("Unit exponential F(r)", c(rep(NA_real_, length(rows_cs)), -expm1(-cs_fit)), "numeric"),
family = cs_col("Series", c(rep("data", length(rows_cs)), rep("unit exponential", length(cs_fit))), "categorical",
levels = c("data", "unit exponential"))
), controls = list(paper = "exponential"))
),
values = values
))
HR = 1.02, 95% CI [1.00, 1.04], p = .065
- Likelihood-ratio χ²
- 14.123
- df
- 2
- p
- < .001
- Concordance (C, apparent)
- 0.6029
- AIC
- 1489.70
Effect size
- Hazard ratio (age) 1.017 95% CI [0.9990, 1.036]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Proportional hazards — Global Grambsch–Therneau χ²(2) = 2.77, p = .250; no evidence that hazard ratios change over time.
- Events per variable — 82.5 events per coefficient.
- Non-informative censoring — 63 of 228 observations are censored.
- Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
- Influential observations — Largest |DFBETAS| = 0.42; 18 of 228 subjects above 2/√n = 0.13.
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0170 | 0.0092 | 1.017 | 0.9990 | 1.036 | 1.848 | .065 |
| sex: female | −0.5132 | 0.1675 | 0.5986 | 0.4311 | 0.8311 | −3.065 | .002 |
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 14.123 | 2 | < .001 |
| Wald | 13.473 | 2 | .001 |
| Score (log-rank) | 13.722 | 2 | .001 |
Proportional-hazards test (Grambsch–Therneau)
| Term | χ² | df | p |
|---|---|---|---|
| age | 0.2092 | 1 | .647 |
| sex | 2.608 | 1 | .106 |
| Global | 2.771 | 2 | .250 |
Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6029 | 0.5529 | 0.6528 | Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife). |
| AIC | 1489.70 | — | — | −2 log partial likelihood + 2k. |
| BIC | 1495.91 | — | — | −2 log partial likelihood + k·log(events), events = 165. |
The apparent C is optimistic for new data; the bootstrap option estimates by how much.
Most influential subjects
| Row | Term most affected | DFBETA | DFBETAS | Martingale residual |
|---|---|---|---|---|
| 6 | age | −0.0039 | −0.4236 | −4.254 |
| 85 | age | 0.0036 | 0.3922 | −2.239 |
| 38 | sex: female | −0.0436 | −0.2604 | −2.222 |
| 68 | sex: female | −0.0379 | −0.2265 | −1.981 |
| 3 | age | 0.0019 | 0.2079 | −3.130 |
| 89 | age | 0.0019 | 0.2061 | −1.235 |
| 74 | age | −0.0017 | −0.1827 | 0.8410 |
| 71 | sex: female | 0.0292 | 0.1746 | −3.254 |
| 129 | age | −0.0016 | −0.1712 | −1.298 |
| 149 | age | 0.0014 | 0.1541 | 0.9190 |
Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.
- Event: dead = true. Ties: efron.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec be108a13077d2af0
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import survival as sv # Cox fit, proportional-hazards test, concordance
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead", "age", "sex"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"]) # stored level order
df = df.dropna(subset=["time", "dead", "age", "sex"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "dead", "age", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "dead"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
event_level = "true" # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Design matrix (treatment contrasts against the first stored level)
preds = ["age", "sex"]
cols, labels, terms = [], [], []
for pname in preds:
s = df[pname]
if isinstance(s.dtype, pd.CategoricalDtype):
lv = [str(x) for x in s.cat.categories]
if len(lv) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pname, min=2, k=len(lv)) # a factor needs two levels with data
idx = []
for level in lv[1:]:
idx.append(len(cols))
cols.append((s.astype(str) == level).to_numpy(dtype=float))
labels.append(f"{pname}: {level}")
terms.append(idx)
else:
terms.append([len(cols)])
cols.append(s.to_numpy(dtype=float))
labels.append(pname)
X = np.column_stack(cols)
# %% Cox model
conf = 0.95
ties = "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname = None
scodes = None
fit = sv.cox_fit(t, ev, X, strata=scodes, ties=ties)
beta = fit["coef"]
se = np.sqrt(np.diag(fit["cov"]))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
q = stats.norm.ppf(1 - (1 - conf) / 2)
hr, hr_lo, hr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
lr_p = float(stats.chi2.sf(fit["lr"], k))
conc = sv.concordance(t, ev, X @ beta, strata=scodes)["concordance"]
one_time = np.unique(t[ev]).size < 2 # with every event at one time the proportional-hazards test is undefined
if one_time:
warnings.append(cs.cs_warning("CS_W_TIES", column=tcol, consequence="every event happened at the same time, so the proportional-hazards test is not computed."))
zph = {"global": (None, None, None), "terms": [(None, None, None) for _ in preds], "times": np.zeros(0), "scaled": np.zeros((0, k))}
else:
zph = sv.cox_zph(t, ev, X, beta, terms, strata=scodes, ties=ties)
ph_chisq, _, ph_p = zph["global"]
# %% Fit measures and the apparent concordance
aic = -2 * fit["loglik"] + 2 * k
bic = -2 * fit["loglik"] + k * np.log(ev.sum()) # n = the number of events, as R's BIC() for coxph
cvar = sv.concordance_var(t, ev, X @ beta, strata=scodes) # infinitesimal-jackknife SE, as survival::concordance()
c_se = cvar["se"]
c_lo, c_hi = (max(0.0, conc - q * c_se), min(1.0, conc + q * c_se)) if np.isfinite(conc) and np.isfinite(c_se) else (None, None)
# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
res = sv.cox_residuals(t, ev, X, beta, strata=scodes, ties=ties)
mart = res["martingale"]
cox_snell = ev - mart
dfb = res["score"] @ fit["cov"] # one-step change in each coefficient when the row is left out
dfbs = dfb / se
abs_dfbs = np.abs(dfbs)
infl_cut = 2 / np.sqrt(len(t))
n_infl = int((abs_dfbs.max(axis=1) > infl_cut).sum())
max_dfbs = float(abs_dfbs.max())
num_preds = [pname for pname, idx in zip(preds, terms) if len(idx) == 1 and not isinstance(df[pname].dtype, pd.CategoricalDtype)
and not pd.api.types.is_bool_dtype(df[pname]) and df[pname].nunique() > 2]
optimism = c_corrected = None
boot_used = 0
values = {
"n": float(len(t)), "events": float(ev.sum()), "n_coef": float(k), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
"lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p,
"wald_chisq": fit["wald"], "wald_p": float(stats.chi2.sf(fit["wald"], k)),
"score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], k)),
"concordance": conc, "ph_chisq": ph_chisq, "ph_p": ph_p,
"coef_1_label": labels[0], "hr_1": float(hr[0]), "hr_1_low": float(hr_lo[0]), "hr_1_high": float(hr_hi[0]), "p_1": float(pv[0]),
"epv": float(ev.sum()) / k, "event_label": event_label,
"aic": float(aic), "bic": float(bic), "concordance_se": float(c_se), "concordance_low": c_lo, "concordance_high": c_hi,
"max_abs_dfbetas": max_dfbs, "n_influential": float(n_infl), "martingale_min": float(mart.min()), "martingale_max": float(mart.max()),
"optimism": optimism, "concordance_corrected": c_corrected, "boot_used": float(boot_used),
}
coef_rows = []
for i, lab in enumerate(labels):
for key, val in (("coef", beta[i]), ("se", se[i]), ("hr", hr[i]), ("hr_low", hr_lo[i]), ("hr_high", hr_hi[i]), ("z", z[i]), ("p", pv[i])):
values[f"{key}[{lab}]"] = float(val)
values[f"dfbetas_max[{lab}]"] = float(abs_dfbs[:, i].max())
coef_rows.append({"term": lab, "coef": float(beta[i]), "se": float(se[i]), "hr": float(hr[i]), "hr_low": float(hr_lo[i]),
"hr_high": float(hr_hi[i]), "z": float(z[i]), "p": float(pv[i])})
ph_rows = []
for pname, (c2, dfree, pp) in zip(preds, zph["terms"]):
values[f"ph_chisq[{pname}]"], values[f"ph_p[{pname}]"] = c2, pp
ph_rows.append({"term": pname, "chisq": c2, "df": None if dfree is None else float(dfree), "p": pp})
ph_rows.append({"term": "Global", "chisq": ph_chisq, "df": float(k), "p": ph_p})
# %% Assumptions
bad = [r["term"] for r in ph_rows[:-1] if r["p"] is not None and r["p"] < 0.05]
if one_time:
ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "info", "detail": "Not tested: every event happened at the same time."}
else:
ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "warn" if ph_p < 0.05 or bad else "pass",
"statistic": ph_chisq, "p": ph_p,
"detail": f"Global Grambsch–Therneau χ²({k}) = {ph_chisq:.2f}, {cs.fmt_p(ph_p)}"
+ (f"; time-varying effect for {', '.join(bad)}. Consider stratifying by {'it' if len(bad) == 1 else 'them'}, a time-varying"
" effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."
if bad else "; no evidence that hazard ratios change over time.")}
assumptions = [
ph_check,
{"key": "events_per_variable", "label": "Events per variable", "status": "warn" if values["epv"] < 10 else "pass",
"detail": f"{values['epv']:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if values["epv"] < 10 else ".")},
{"key": "censoring", "label": "Non-informative censoring", "status": "info", "detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."},
{"key": "functional_form", "label": "Functional form", "status": "info",
"detail": (f"Not tested: look at the martingale residuals against {', '.join(num_preds)}. A smooth that bends away from zero"
" suggests a transformation or a spline." if num_preds else "No numeric predictor with more than two values to check.")},
{"key": "influence", "label": "Influential observations", "status": "warn" if max_dfbs > 1 else "pass", "statistic": max_dfbs,
"detail": f"Largest |DFBETAS| = {max_dfbs:.2f}; {n_infl} of {len(t)} subjects above 2/√n = {infl_cut:.2f}"
+ (". At least one subject moves a coefficient by more than one standard error." if max_dfbs > 1 else ".")},
]
# %% Charts: hazard ratios and scaled Schoenfeld residuals
rows_sch = np.arange(len(zph["times"]))
if len(rows_sch) * k > 5000:
rows_sch = np.unique(np.round(np.linspace(0, len(rows_sch) - 1, max(5000 // k, 2))).astype(int))
sch_time, sch_res, sch_term = [], [], []
for i, lab in enumerate(labels):
sch_time += zph["times"][rows_sch].tolist()
sch_res += zph["scaled"][rows_sch, i].tolist()
sch_term += [lab] * len(rows_sch)
# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x, mart_r, mart_term = [], [], []
if num_preds:
rows_m = np.arange(len(t))
if len(rows_m) * len(num_preds) > 5000:
rows_m = np.unique(np.round(np.linspace(0, len(t) - 1, max(5000 // len(num_preds), 2))).astype(int))
for pname in num_preds:
mart_x += df[pname].to_numpy(dtype=float)[rows_m].tolist()
mart_r += mart[rows_m].tolist()
mart_term += [pname] * len(rows_m)
rows_cs = np.arange(len(t))
if len(rows_cs) > 5000:
rows_cs = np.unique(np.round(np.linspace(0, len(t) - 1, 5000)).astype(int))
cs_fit = np.linspace(0.0, float(cox_snell.max()), 61)[1:] if cox_snell.max() > 0 else np.zeros(0)
# %% Influence: the subjects with the largest scaled dfbeta
top = np.lexsort((np.arange(len(t)), -abs_dfbs.max(axis=1)))[:10]
infl_rows = []
for r in top:
j = int(np.argmax(abs_dfbs[r]))
infl_rows.append({"row": float(r + 1), "term": labels[j], "dfbeta": float(dfb[r, j]), "dfbetas": float(dfbs[r, j]), "martingale": float(mart[r])})
# %% Result
pct = f"{conf:.0%}"
fit_rows = [
{"measure": "Concordance (C, apparent)", "value": conc, "low": c_lo, "high": c_hi,
"note": f"Harrell's C on the data the model was fitted to; SE {c_se:.4f} (infinitesimal jackknife)."},
{"measure": "AIC", "value": float(aic), "low": None, "high": None, "note": "−2 log partial likelihood + 2k."},
{"measure": "BIC", "value": float(bic), "low": None, "high": None, "note": f"−2 log partial likelihood + k·log(events), events = {int(ev.sum())}."},
]
if c_corrected is not None:
fit_rows.insert(1, {"measure": "Concordance (optimism-corrected)", "value": c_corrected, "low": None, "high": None,
"note": f"Apparent C minus the mean optimism {optimism:.4f} over {boot_used} bootstrap refits (Harrell)."})
cs.publish({
"method": "survival.cox",
"methodVersion": "1.1.0",
"title": "Cox proportional hazards model",
"engine": cs.engine_info("numpy", "scipy", "statsmodels", "codesplash"),
"n": int(len(t)),
"summary": f"Cox model ({int(ev.sum())} events): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}; apparent concordance {conc:.3f}.",
"apa": f"HR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}",
"statistics": [
{"key": "lr_chisq", "label": "Likelihood-ratio χ²", "value": fit["lr"]}, {"key": "lr_df", "label": "df", "value": float(k), "format": "integer"},
{"key": "lr_p", "label": "p", "value": lr_p, "format": "p"}, {"key": "concordance", "label": "Concordance (C, apparent)", "value": conc},
{"key": "aic", "label": "AIC", "value": float(aic)},
],
"tables": [
{"key": "coefficients", "title": "Hazard ratios", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "hr", "label": "HR", "type": "number"},
{"key": "hr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "hr_high", "label": f"{pct} CI high", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
], "rows": coef_rows},
{"key": "tests", "title": "Overall tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
], "rows": [
{"test": "Likelihood ratio", "chisq": fit["lr"], "df": float(k), "p": lr_p},
{"test": "Wald", "chisq": fit["wald"], "df": float(k), "p": values["wald_p"]},
{"test": "Score (log-rank)", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
]},
{"key": "proportional_hazards", "title": "Proportional-hazards test (Grambsch–Therneau)", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
], "rows": ph_rows, "note": "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."},
{"key": "fit", "title": "Model fit", "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "note", "label": "Note", "type": "string"},
], "rows": fit_rows, "note": "The apparent C is optimistic for new data; the bootstrap option estimates by how much."},
{"key": "influence", "title": "Most influential subjects", "columns": [
{"key": "row", "label": "Row", "type": "integer"}, {"key": "term", "label": "Term most affected", "type": "string"},
{"key": "dfbeta", "label": "DFBETA", "type": "number"}, {"key": "dfbetas", "label": "DFBETAS", "type": "number"},
{"key": "martingale", "label": "Martingale residual", "type": "number"},
], "rows": infl_rows, "note": "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE."},
],
"effectSizes": [{"key": "hr_1", "label": f"Hazard ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
"ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(HR)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")],
"charts": [
cs.chart("hr", "forest", "Hazard ratios", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Hazard ratio", hr, "numeric"),
"low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
}, controls={"reference": 1, "log": True}),
cs.chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", {
"time": cs.col(tcol, sch_time, "numeric"), "residual": cs.col("β(t)", sch_res, "numeric"),
"term": cs.col("Term", sch_term, "categorical", levels=labels),
}),
*([cs.chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", {
"x": cs.col("Predictor value", mart_x, "numeric"), "partial": cs.col("Martingale residual", mart_r, "numeric"),
"term": cs.col("Predictor", mart_term, "categorical", levels=num_preds),
}, controls={"smooth": True})] if num_preds else []),
cs.chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", {
"time": cs.col("Cox–Snell residual", np.concatenate((cox_snell[rows_cs], cs_fit)), "numeric"),
"event": cs.col("Event", np.concatenate((ev[rows_cs].astype(float), np.full(cs_fit.size, np.nan))), "numeric"),
"fit": cs.col("Unit exponential F(r)", np.concatenate((np.full(rows_cs.size, np.nan), -np.expm1(-cs_fit))), "numeric"),
"family": cs.col("Series", ["data"] * rows_cs.size + ["unit exponential"] * cs_fit.size, "categorical", levels=["data", "unit exponential"]),
}, controls={"paper": "exponential"}),
],
"values": values,
})
Each extra year of age multiplies the hazard by 1.017, adjusted for sex. That looks tiny, but it is per year: over 10 years it compounds to .
How good is the model?
ReadHarrell's concordance is the share of comparable pairs the model ranks correctly: 0.5 is a coin flip, 1 is perfect. Here it is 0.60, so age and sex alone rank pairs only modestly better than chance.
A statistically clear hazard ratio doesn't imply useful prediction. The overall test here gives p < .001, and the ranking is still weak.
Events per variableEvents per variableEvents (the rarer outcome) per estimated coefficient in logistic or Cox models. is the sample size that matters: 82.5 here. Below about 10, coefficients become unstable.
Say it in plain words
ReflectWrite one sentence for a colleague that explains this card's hazard ratio for age without using the word "hazard". What would you add so nobody reads it as a difference in how long people live?
Same model, two dialects
ReadBoth default to Efron's method for ties, so these match the card. Set the reference level yourself: R uses the first factor level, and one-hot encoding in Python makes you choose.
import pandas as pd
from lifelines import CoxPHFitter
df = pd.read_csv("lung.csv")
data = pd.DataFrame({
"time": df["time"], "dead": df["dead"], "age": df["age"],
"female": (df["sex"] == "female").astype(int),
})
cox = CoxPHFitter().fit(data, "time", "dead")
print(cox.summary[["exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%", "p"]])
print(cox.concordance_index_)library(survival)
df <- read.csv("lung.csv")
df$sex <- relevel(factor(df$sex), ref = "male")
fit <- coxph(Surv(time, dead == "true") ~ age + sex, data = df)
summary(fit)Check your understanding
CheckpointCheck yourself
In the lung data the hazard ratio for women against men is 0.60 (95% interval 0.43 to 0.83). Which sentence fits?
Show the answer
Answer: b
A hazard ratio compares rates at each moment among those still at risk. It doesn't convert directly to survival time or eventual deaths, and these data are observational.
Check yourself
A covariate has a hazard ratio of 1.02 per unit. What is the hazard ratio for a 10-unit difference? Give two decimals.
Show the answer
Answer: 1.22
Hazard ratios multiply: .
Check yourself
A dataset has 5,000 patients and 60 events. You plan a Cox model with 12 predictors. What should worry you?
Show the answer
Answer: a
Precision in a survival model depends on events, not patients. Reduce the predictors or use a penalized model.
Recap
Recap- The Cox model estimates hazard ratios without specifying the baseline hazard.
- A hazard ratio compares event rates among those still at risk, at any moment.
- It assumes those ratios stay constant over time.
- Concordance measures ranking; events, not rows, set the sample size.
Concepts in this lesson