Survival analysis: a censored record is not a failure
生存分析
Calculate risk sets, Kaplan–Meier survival and a restricted mean, including ties and incomplete follow-up.
survival-analysis“Still running” is not a failure time
You test six machines. Some break; others are still working when observation ends. A working machine observed for five hours has not supplied a five-hour failure time. It has supplied a lower bound on its lifetime.
Survival analysis studies time until an event: failure, repair, churn or another clearly defined endpoint. The term does not restrict the method to human survival. Right censoring means the event has not been observed before a known follow-up time. Discarding these records or treating them as failures changes the question. Read conditional probability and likelihood first.
Keep event time and observation time separate
Let T be event time and C censoring time. A simple independent-censoring model observes:
An event has δ=1; a right-censored record has δ=0. Independent subjects and censoring independent of event time are sufficient assumptions for the basic unconditional estimator here. If independence holds only after conditioning on covariates, ignoring those covariates may still bias an unconditional analysis.
For continuous event times with density f and independent censoring, the likelihood terms involving the event distribution are:
An observed failure contributes a density; a censored observation contributes survival past its last observed time. Factors describing the censoring distribution can be separated under the model. This expression is not a license to assume censoring is harmless: stopping observation because a machine seems close to failing can violate independence. Stanford STAT 331 Unit 3, pages 1–2, states the model and derives the product-limit construction.
At each distinct observed event time tⱼ, let nⱼ be the number at risk just before that time and dⱼ the event count. Multiplying estimated conditional survival probabilities gives:
This is the Kaplan–Meier estimator. With no censoring it reduces to the empirical fraction of event times strictly greater than t. Censoring removes a subject from later risk sets without making the survival curve fall at that censoring time. A hazard rate, when a density exists, is f(t)/S(t); it is a rate per unit time, not a cumulative event probability. STATS 305B’s survival notes distinguish these quantities.
Six records, including tied times
Use observed times(2,2,3,4,4,5) and event indicators(1,0,1,1,0,0). At a time shared by events and censoring, our convention includes everyone with U≥t in the risk set, applies the event fraction, then removes both events and censoring. This matches the risk-set definition; coarsely rounded timestamps may require a different observation model.
At time 2, six are at risk and one fails: Ŝ=5/6. At 3, four remain at risk and one fails: Ŝ=(5/6)(3/4)=5/8. At 4, three are at risk and one fails: Ŝ=(5/8)(2/3)=5/12. At 5, the last record is censored, so the curve stays at 5/12.
The estimated median is 4, the first time the curve is at most 1/2. The restricted mean through time 5 is the area under the step curve: 2+5/6+5/8+5/12=31/8. It is a restricted mean, not an identified unrestricted mean lifetime.
Build risk sets before multiplying
This complete Python 3.12 program groups tied observations, keeps exact rational survival values and integrates the step curve over a supplied horizon. It returns a row at censor-only times too, making their effect on later risk sets inspectable.
from fractions import Fraction as F
def observations(times, events):
times,events=list(times),list(events)
if not 1<=len(times)<=64 or len(times)!=len(events):
raise ValueError('one to64 paired observations required')
if any(type(t) not in (int,F) or not 0<=t<=1000000 for t in times):
raise ValueError('nonnegative rational times at most1000000 required')
if any(type(d) is not int or d not in (0,1) for d in events):
raise ValueError('integer event indicators zero or one required')
return list(map(F,times)),events
def kaplan_meier(times, events):
times,events=observations(times,events);groups={}
for t,d in zip(times,events):
if t not in groups:groups[t]=[0,0]
groups[t][0 if d else 1]+=1
risk=len(times);survival=F(1);rows=[]
for t,(deaths,censored) in sorted(groups.items()):
survival*=1-F(deaths,risk)
rows.append((t,risk,deaths,censored,survival))
risk-=deaths+censored
median=next((t for t,_,_,_,s in rows if s<=F(1,2)),None)
return rows,median
def restricted_mean(times, events, tau):
times,events=observations(times,events)
if type(tau) not in (int,F) or not 0<=tau<=max(times):
raise ValueError('rational horizon within observed follow-up required')
rows,_=kaplan_meier(times,events);area=F(0);previous=F(0);survival=F(1)
for t,_,_,_,new_survival in rows:
if t>tau:break
area+=(t-previous)*survival;previous=t;survival=new_survival
return area+(F(tau)-previous)*survival
if __name__=='__main__':
times=[2,2,3,4,4,5];events=[1,0,1,1,0,0]
rows,median=kaplan_meier(times,events)
print('time; at risk; events; censored; survival after time')
for row in rows:print(*map(str,row),sep='; ')
print('estimated median:',median)
print('restricted mean through5:',restricted_mean(times,events,5))
wrong,_=kaplan_meier(times,[1]*len(times))
print('incorrectly treating all censoring as events:',*[str(row[-1]) for row in wrong])
Output:
time; at risk; events; censored; survival after time
2; 6; 1; 1; 5/6
3; 4; 1; 0; 5/8
4; 3; 1; 1; 5/12
5; 1; 0; 1; 5/12
estimated median: 4
restricted mean through5: 31/8
incorrectly treating all censoring as events: 2/3 1/2 1/6 0
The API allows up to 64 records, rational nonnegative times and explicit integer event indicators. It accepts unsorted observations. Grouping costs O(n), sorting up to n distinct times costs O(nlogn), and the sweep takes O(n) work, apart from rational bit costs. Memory is O(n).
The restricted-mean helper requires its horizon to be within the observed follow-up range. It deliberately refuses to turn an unobserved tail into an extrapolated lifetime estimate. The example does not fit a Cox model or compute confidence intervals. Tests compare its output with the hand calculation, an uncensored empirical survival curve and all-censored boundaries.
No recorded failure does not mean no future failure
When the curve never reaches 1/2, the observed follow-up does not provide a Kaplan–Meier median; the program returns None. A final plateau above zero is not evidence that some machines last forever. Sample size at risk often becomes very small near the right edge, making late estimates uncertain.
Informative censoring cannot be repaired by multiplying the right fractions. Consider machines withdrawn early because they start overheating: the remaining machines may no longer represent those still at risk in the target population. Delayed entry, interval censoring and competing events also need their own definitions and methods; this program handles none of them.
Survival curves describe event-time distributions. Comparing two curves does not by itself establish that a treatment or policy caused the difference. Models such as Cox proportional hazards and accelerated failure time incorporate covariates under additional assumptions. Evaluate the event definition, time origin, follow-up rules and target horizon before selecting a model.
Read the risk set, not just the endpoint
- Why is the risk set at time 3 equal to 4?
Answer 1: One event and one censored record left at time 2, reducing six records to four.
- Does censoring at time 5 lower the estimated survival curve?
Answer 2: No. There is no event at 5; the curve remains 5/12.
- What is the restricted mean through 5?
Answer 3: 31/8, the area under the step curve through that horizon.
- What does
Nonefor the median mean?
Answer 4: The estimated curve did not reach 1/2 during observed follow-up; it does not prove infinite lifetime.
Make the observation process part of the experiment
Project: simulate a known event-time distribution and compare independent administrative censoring with censoring that depends on the latent event time. Across repeated datasets, compare the estimated curve at a prespecified horizon with the known survival probability. Keep simulation truth out of the estimator.
Report at-risk counts beside curves, distinguish censoring from competing events, and state whether a requested horizon has sufficient follow-up. Continue with uncertainty intervals and causal inference to separate estimation uncertainty from causal identification.
Make a prediction, then check
What happens at the final censor-only time5?
Learning objectives
- Distinguish event times from right-censored observations.
- Compute tied-time risk sets and the product-limit curve.
- Explain follow-up limits, median and restricted mean.
Prerequisites & connections
Explore related knowledge →References
- STAT331 Unit3: Kaplan–Meier Estimator
Lu Tian - STATS305B — Survival analysis
Stanford STATS305B course staff
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Graph scores use analytic references; KM and random-query expectations use exact fractions; ranking gradients use literal and finite-difference checks. No NumPy dependency in these examples.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- STAT331 Unit3: Kaplan–Meier Estimator · Unit3 physical pages1–3: independent right-censoring model, likelihood, risk setU>=t, product-limit estimator and example with event/censor ties. No unverified course publication year.
- STATS305B — Survival analysis · Survival introduction and hazard-function section: observed versus event time, continuous hazardf/S, cumulative hazard and distinct discrete behavior. No copied code or clinical advice.
Related topics