Tell diagnostic, prognostic and predictive biomarkers apart, analyse real breast cancer survival data with Kaplan–Meier curves and a Cox model, and see why an 'optimal' cut-off and a missing validation study can turn noise into a finding.
From a marker to a decision about a patient
In AI for gene editing: designing CRISPR guides the question was where to cut a genome. This lesson asks what it takes for an omics finding to change how a patient is treated. In Machine learning on an expression table: from patients to marker genes you found genes that separate two leukaemias and saw how leakage can invent a signal. Between a gene on a ranked list and a test a doctor can order lie three more things: outcomes that unfold over years, studies that confirm the first result, and reports that let others check it.
A biomarker is a measurable characteristic that indicates a biological state, a disease process or a response to treatment: a mutation, a protein level, a gene-expression score. What matters is the question it answers, and there are three main kinds.
- Diagnostic markers say whether a disease, or which subtype, is present. The BCR-ABL1 fusion gene, created by the Philadelphia chromosome, is a defining feature of chronic myeloid leukaemia and is used to confirm the diagnosis.
- Prognostic markers say how the disease is likely to go. The number of lymph nodes containing cancer is a classic prognostic factor in breast cancer. Oncotype DX is a multi-gene example: it combines the expression of 21 genes (16 cancer-related, 5 reference) in tumour tissue into a recurrence score for early, hormone-receptor-positive breast cancer.
- Predictive markers say whether a particular treatment is likely to work. Breast cancers with amplified or overexpressed HER2 can respond to trastuzumab, an antibody against the HER2 protein. Tumours with harmful BRCA1 or BRCA2 mutations are sensitive to PARP inhibitors such as olaparib, because those cells already lack one DNA-repair route and cannot survive losing a second. Lung cancers with activating EGFR mutations often respond to EGFR inhibitors such as gefitinib or osimertinib.
The prognostic–predictive difference is easy to blur. A prognostic marker separates good outcomes from bad ones. A predictive marker changes the effect of a treatment: the drug helps marker-positive patients more than marker-negative ones. Showing that needs treated and untreated patients, ideally from a randomised trial, and a test of whether the treatment effect differs between marker groups, called an interaction. One marker can be both: HER2 amplification was first known as a sign of aggressive disease, then became the reason to give trastuzumab.
Time-to-event data and censoring
Most prognostic questions are about when: how long until the cancer comes back, or until death. Such data are called time-to-event or survival data, even when the event is not death. Each patient contributes a time, measured from a fixed starting point such as surgery, and whether the event was seen at that time.
Studies end and people move away. If a patient was well at her last visit three years after surgery, we know she had no event for three years and nothing after that. Her time is censored (right-censored: the true event time lies somewhere to the right of what we saw). Dropping her would waste information, and counting her last visit as an event would be wrong. Survival methods use each patient for exactly as long as they were watched.
How to read this figure
All five lines start at zero, the day of surgery, though the operations happened on different dates. Patients 1 and 3 relapsed; the other three are censored. The standard methods assume censoring is non-informative: a patient who leaves is no more or less likely to relapse than those who stay. If the sickest patients stop coming to clinic, that fails and the curves look better than the truth.
A real cohort: the GBSG2 breast cancer data
The code uses a dataset bundled with lifelines, the main Python package for survival analysis. It comes from the German Breast Cancer Study Group 2 trial of hormone therapy and chemotherapy duration: 686 women with breast cancer that had spread to the lymph nodes. Each row records age, menopausal status, tumour size (mm), tumour grade (I to III), the number of positive nodes, whether she received hormone therapy, and two receptor levels in the tumour, progesterone receptor (progrec) and oestrogen receptor (estrec), in fmol. The outcome is recurrence-free survival in days: time is follow-up and cens is 1 if a recurrence or death was seen, 0 if censored. Despite its name, cens marks events. The first line installs lifelines in Colab.
!pip install -q lifelines # Colab only; not preinstalled
import numpy as np, pandas as pd
from lifelines.datasets import load_gbsg2
df = load_gbsg2()
print(df.shape)
print(df[["time", "cens", "progrec", "pnodes", "tgrade", "horTh"]].head(3).to_string())
print("events:", df["cens"].sum(), "| censored:", (df["cens"] == 0).sum())Reading the output
686 women; 299 had a recurrence or died during follow-up and 387, more than half, are censored. Discarding them would keep mainly the women who relapsed and make the outlook look far worse than it is.
Kaplan–Meier curves and the log-rank test
The Kaplan–Meier estimator draws a survival curve that handles censoring. At each event it asks: of the patients still followed just before this moment, the risk set, what fraction got through? The curve is the running product of those fractions. A censored patient leaves the risk set without causing a drop.
Worked example · a Kaplan–Meier curve by hand
2 years: patient 2 censored → no step, 4 left
3.2 years: 3 at risk, 1 relapse → S = 0.80 × 2 ÷ 3 = 0.53
3.8 and 5 years: censored → no step; S(5 years) = 0.53
Step by step. Using Figure 1: at 1.5 years all five are at risk and one relapses. Patient 2 then leaves without a drop. At 3.2 years patients 3, 4 and 5 are at risk; one relapses, so the curve falls by a third. The naive answer, "2 of 5 relapsed, so 0.60 stayed free", assumes patient 2 was well at 5 years, which nobody knows.
Now group the real patients by progesterone receptor (PgR). The cut-off, 10 fmol, is fixed before looking at any outcome; why that matters comes later.
from lifelines import KaplanMeierFitter
df["pgr_pos"] = (df["progrec"] >= 10).astype(int) # cut-off fixed in advance
print(df["pgr_pos"].value_counts().sort_index().to_dict())
kmf = KaplanMeierFitter()
for label, grp in df.groupby("pgr_pos"):
name = "PgR+" if label else "PgR-"
kmf.fit(grp["time"], grp["cens"], label=name)
s5 = kmf.survival_function_at_times(5 * 365.25).iloc[0]
print(f"{name}: n={len(grp)}, median {kmf.median_survival_time_:.0f} days, "
f"recurrence-free at 5 years {s5:.2f}")
kmf.plot_survival_function() # draws one curve per group (in Colab)What this does
fit(time, event)fits one group's curve;median_survival_time_is where it first reaches 0.5, andsurvival_function_at_times(5 * 365.25)reads it at five years.plot_survival_function()draws each staircase with a shaded 95% confidence band, both groups on one chart.
Reading the output
Half the 199 PgR-negative women had a recurrence or died within 1,093 days, about three years, against 2,034 days for the 487 PgR-positive women. At five years an estimated 34% and 55% respectively were recurrence-free. On the plot the PgR-positive curve stays above, and the bands widen as fewer women remain.
Could chance produce a gap like this? The log-rank test compares, at each event time, the events seen in each group with those expected if both shared one curve, and adds the differences over the whole follow-up.
from lifelines.statistics import logrank_test
pos, neg = df[df.pgr_pos == 1], df[df.pgr_pos == 0]
res = logrank_test(pos["time"], neg["time"], pos["cens"], neg["cens"])
print(f"log-rank statistic {res.test_statistic:.2f}, p = {res.p_value:.2g}")Reading the output
A p-value around 3 × 10−10: a gap this large would almost never arise by chance. But the test says only that the curves differ, not by how much, and allows for nothing else. PgR-positive tumours here are also more often low grade, so does PgR add anything grade does not? That needs a model.
Cox proportional hazards and hazard ratios
The hazard is the instantaneous event rate among patients still at risk. The Cox proportional hazards model says each covariate multiplies the hazard by a fixed factor, the hazard ratio (HR), without specifying how the baseline hazard changes over time. HR 2 means twice the event rate at any moment, 0.5 half, 1 no association. Fitting covariates together gives each HR adjusted for the others.
PgR is very skewed, from 0 to over 2,000 fmol, so it enters on a log2 scale, making its HR per doubling. Grade becomes indicator columns, with grade I as the baseline.
from lifelines import CoxPHFitter
X = df[["time", "cens", "age", "tsize", "pnodes", "progrec", "horTh", "tgrade"]].copy()
X["log_pgr"] = np.log2(X.pop("progrec") + 1) # skewed marker: log scale
X["horTh"] = (X["horTh"] == "yes").astype(int)
X = pd.get_dummies(X, columns=["tgrade"], drop_first=True, dtype=int) # grade I is baseline
cph = CoxPHFitter()
cph.fit(X, duration_col="time", event_col="cens")
cols = ["exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%", "p"]
print(cph.summary[cols].round(3).to_string())
print("concordance:", round(cph.concordance_index_, 3))Reading the output
exp(coef) is the hazard ratio, with its 95% interval and p-value (0.000 means below 0.0005). Each doubling of PgR goes with a hazard about 12% lower (HR 0.88, interval 0.85 to 0.92) after allowing for grade, nodes, size, age and hormone therapy, so PgR carries prognostic information of its own. Each extra positive node raises the hazard by about 5%. Grades II and III have about 1.7 to 1.8 times the hazard of grade I, with wide intervals because only 81 women had grade I tumours. Hormone therapy goes with a hazard about 28% lower; read every covariate here as an adjusted association, not proof of cause.
The concordance index (C-index), 0.695, is the survival cousin of the ROC AUC from Measuring a model honestly: confusion matrix, ROC, precision, recall and imbalance: among pairs of patients where one is known to have relapsed first, the share in which the model ranked her as higher risk. 0.5 is guessing. It is measured on the women the model was fitted to, so it is optimistic.
Worked example · turning hazard ratios into comparisons
HR per doubling of PgR = 0.882; 10 → 160 fmol is 4 doublings: 0.8824 ≈ 0.61
Step by step. Hazard ratios multiply. A woman with 8 positive nodes has about 1.29 times the hazard of an otherwise identical woman with 3. From 10 to 160 fmol of PgR is four doublings, so the hazard is multiplied by 0.882 four times. Neither number is a probability of relapse: turning a hazard ratio into an absolute risk also needs the baseline survival curve.
Checking proportional hazards
The model assumes each hazard ratio is the same throughout follow-up. If a marker matters greatly in the first two years and not afterwards, one HR averages that away. Crossing Kaplan–Meier curves are a warning sign; a formal check uses the model's Schoenfeld residuals to test whether each effect drifts over time.
from lifelines.statistics import proportional_hazard_test ph = proportional_hazard_test(cph, X, time_transform="rank") print(ph.summary[["test_statistic", "p"]].round(3).to_string())
Reading the output
A small p-value means that covariate's effect seems to change over time. PgR passes (p = 0.12), as do nodes, size and hormone therapy. Age clearly fails (p = 0.001) and grade III is borderline. So age's HR of 1.00 may be averaging an effect that changes over follow-up rather than showing none. Common fixes are to stratify, giving each group its own baseline hazard (strata=[...] in cph.fit, after grouping ages), or to let the effect vary with time. cph.check_assumptions(X) gives advice and plots; in large studies tiny departures reach significance, so look at the plots too.
Go deeper: why not logistic regression at five years?
You could label each woman "relapsed by five years: yes or no" and fit a classifier. But a woman censored at three years has no label and must be dropped, which biases the sample towards early relapses, and a relapse at six months becomes the same as one at four years eleven months. Survival models use all the follow-up. Machine-learning versions exist, such as random survival forests in scikit-survival, and they need the same honest evaluation as any other model.
The optimal cut-off trap
Clinicians like a cut-off: high or low. Turning a continuous marker into two groups is called dichotomising. The trap is trying many cut-offs and keeping the one with the smallest p-value. Each try is another chance for luck. It is the gene-selection leakage of the earlier lesson, in a new place.
The code makes a "marker" of pure random numbers, tests every cut-off from the 10th to the 90th centile against the real GBSG2 outcomes, and repeats this for 200 noise markers. It takes a few minutes.
rng = np.random.default_rng(0)
def best_cutoff_p(marker):
"""Try every cut-off between the 10th and 90th centile; keep the smallest p."""
best = 1.0
for c in np.unique(np.quantile(marker, np.linspace(0.1, 0.9, 81))):
hi = marker > c
p = logrank_test(df.time[hi], df.time[~hi], df.cens[hi], df.cens[~hi]).p_value
best = min(best, p)
return best
pvals = [best_cutoff_p(rng.normal(size=len(df))) for _ in range(200)] # pure noise
print("noise markers with an 'optimal' cut-off at p < 0.05:", np.mean(np.array(pvals) < 0.05))Reading the output
With no real signal, an honest test is "significant" at p < 0.05 about 5% of the time. With the cut-off chosen for the smallest p, 35% of meaningless markers pass, seven times the advertised rate. The hazard ratio at an optimised cut-off is exaggerated too, so the next study usually finds a weaker effect or none.
Even a cut-off fixed in advance throws information away: 9 and 0 fmol become identical while 9 and 11 become opposites. Keep the marker continuous in the model, transformed if needed as with log2 PgR. If the clinic needs a threshold, fix it from biology or earlier studies, then validate it in new patients.
From discovery to clinical use
A marker passes through three broad stages. Discovery finds candidates, often from omics data in one cohort, with all the overfitting risks you have seen. Independent validation tests a locked version (same genes, weights, cut-off and assay) in a different cohort, ideally from other hospitals, with nothing re-tuned. Clinical utility asks whether using the test improves what happens to patients; that usually needs a trial or a careful study of stored trial samples.
Analytical validity is whether the assay measures the marker accurately and reproducibly across runs, laboratories and batches. Clinical validity is whether the result is associated with the outcome. A test can be analytically perfect and clinically useless, and a strong research finding can fail because its assay does not reproduce elsewhere.
Tests used to treat patients run in clinical laboratories under quality systems and accreditation, such as the international standard ISO 15189 for medical laboratories, not in research labs. When a drug works only in patients with a particular marker, it is approved together with a companion diagnostic, a test whose result decides who should receive it, as HER2 tests do for trastuzumab.
Reporting so others can check
Two checklists matter here. REMARK covers tumour-marker prognostic studies; TRIPOD covers multivariable prediction models. Before writing up, make sure you can answer:
- Who were the patients, how were they selected and treated, and was the assay done blind to outcome?
- What were the time origin, endpoint, follow-up and number of events?
- Was any cut-off fixed in advance, and how many analyses were tried?
- Was the marker tested alongside standard factors, and was the final model checked in an independent cohort, with discrimination and calibration reported?
Events, not patients, limit what a survival model can support: 299 events is plenty for seven covariates, but a study testing thousands of genes against a few dozen events will almost surely find something false.
Altman, Lausen, Sauerbrei and Schumacher (1994, Journal of the National Cancer Institute) described the "optimal" cut-off inflation shown above. REMARK (REporting recommendations for tumour MARKer prognostic studies) was published by McShane and colleagues in 2005 in several journals, including the Journal of the National Cancer Institute. TRIPOD (Transparent Reporting of a multivariable prediction model for Individual Prognosis Or Diagnosis) was published by Collins and colleagues in 2015, including in the BMJ, and extended as TRIPOD+AI in 2024 for machine-learning models. Sauerbrei and Royston (1999, Journal of the Royal Statistical Society, Series A) used the GBSG2 data to show how to model continuous predictors without cutting them.
Key point
Name the question first: diagnostic, prognostic or predictive. Analyse time-to-event outcomes with methods that respect censoring, keep markers continuous rather than hunting for the best cut-off, check proportional hazards, validate a locked model in new patients, and report every step.
Next comes the module's closing project, Predict a protein's function class from its sequence, where you build and evaluate a model from start to finish with the same honesty.
Further reading · Module 7lifelines documentation: Kaplan–Meier, Cox models and assumption checks in Python. · TRIPOD statement: reporting checklists for prediction models. · EQUATOR Network: a library of reporting guidelines, including REMARK. · All reading for this course
Check your understanding
1. Patients with a marker benefit from a drug, while patients without it do not benefit at all. What kind of biomarker is this?
2. A patient is still well when the study closes after three years. How do survival methods handle her?
3. A study tries every cut-off of a continuous marker and reports the one with the smallest log-rank p-value. What is the problem?