Algorithmcore
Nelson-Aalen estimator
Also called Nelson-Aalen cumulative hazard estimator.
Estimates the cumulative hazard as the sum over event times of the deaths over the number at risk. It is a counting process martingale estimator.
- Time
- Θ(n log n) worst
- Space
- Θ(n) extra
- Where
- n = the number of subjects
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Wayne Nelson, Odd O. Aalen, 1972
The Nelson-Aalen estimator estimates the cumulative hazard of an event time from right-censored data. At each distinct event time it adds the number of events divided by the number still at risk:
Each term estimates the hazard at , the chance that a subject at risk has the event at that time, so the sum estimates the accumulated hazard. It uses the same table of and as the Kaplan-Meier estimator, which multiplies instead of adding . Nelson-Aalen is the natural estimate when the quantity of interest is the hazard itself, for checking a parametric model by a plot, and for the baseline of the Cox model, where the Breslow estimator reduces to it when all coefficients are zero.
In plain words
Follow a group of patients over time. Each time someone has the event, look at how many people were still being watched just before, and write down one divided by that number (or the number of events divided by it, if several happen at once). Keep a running total. The total grows fast when events happen among few people at risk, and slowly when they happen among many. It measures how much risk has built up so far. People who leave the study early count in the totals until the time they leave and then stop counting.
The problem
Input. Observations for , with the observed time and the event indicator, as on the censoring page.
Model. The subjects are independent, and censoring is independent: given that a subject is at risk just before , its chance of an event at is the hazard of at and does not depend on the censoring. In the counting process form, the number of observed events has intensity , where is the number at risk. This is Aalen's multiplicative intensity model.
Output. The distinct event times with and , the values , and two variance estimates:
The first (Aalen's) treats the events at as Poisson, the second as binomial. They are close when every is small compared with , and the first is always the larger.
The algorithm
NELSON-AALEN(y[1..n], δ[1..n])- 1
sort the indices 1..n by y - 2
r ← n; H ← 0; V ← 0; out ← empty list - 3
i ← 1 - 4
while i ≤ n - 5
t ← y of the i-th sorted index; d ← 0; c ← 0 - 6
while i ≤ n and y of the i-th sorted index = t: add 1 to d if δ = 1, else to c; i ← i + 1 - 7
if d > 0 then H ← H + d/r; V ← V + d/r²; append (t, r, d, H, V) to out - 8
r ← r - d - c ▷ events and censorings at t leave after t - 9
return out
The structure is that of the Kaplan-Meier pass: a censored subject at is still in the risk set at . The code also accumulates in line L7, and it has a second tie rule, ties="sequential", which replaces by . That is the value obtained if the tied events are taken to happen one after another in a very short time. The survival estimate is a separate function.
Example
For the 6-MP arm of the leukemia trial (Freireich et al. 1963, as listed by Gehan 1965; the data are on the Kaplan-Meier page), the event times and the results are:
| Kaplan-Meier | |||||||
|---|---|---|---|---|---|---|---|
| 6 | 21 | 3 | 0.14286 | 0.14286 | 0.8669 | 0.8571 | 0.0825 |
| 7 | 17 | 1 | 0.05882 | 0.20168 | 0.8174 | 0.8067 | 0.1013 |
| 10 | 15 | 1 | 0.06667 | 0.26835 | 0.7646 | 0.7529 | 0.1213 |
| 13 | 12 | 1 | 0.08333 | 0.35168 | 0.7035 | 0.6902 | 0.1471 |
| 16 | 11 | 1 | 0.09091 | 0.44259 | 0.6424 | 0.6275 | 0.1730 |
| 22 | 7 | 1 | 0.14286 | 0.58545 | 0.5569 | 0.5378 | 0.2243 |
| 23 | 6 | 1 | 0.16667 | 0.75211 | 0.4714 | 0.4482 | 0.2795 |
Exactly, . At , with three tied events, and ; the sequential tie rule gives instead of . At every time is above the Kaplan-Meier value, and the gap grows as grows. If the hazard were constant, would grow linearly; here is about per week at and at , but the late steps rest on risk sets of 6 and 7.
Correctness
The proof in proofs/correctness.md shows that the pass computes and the two variance sums, by the same invariant as for Kaplan-Meier. It then shows, for event times on a finite grid and under independent censoring, that is a martingale, where is the discrete hazard; that , so the bias is ; and that is the maximum likelihood estimate of the cumulative hazard .
Proof: The pass computes the Nelson-Aalen sums, and in discrete time the estimate is a martingale estimator with an explicit bias and the MLE of the cumulative hazardfull
Let the data be , , with distinct event times , and .
Claim 1 (the pass computes the sums). Every row that line L7 appends is , one row for each , in order.
Proof. After the sort of line L1, the inner loop of line L6 reads exactly the subjects at the current distinct time , and sets and to the numbers of events and censorings at . Invariant: at the start of the group at , , and and hold the two sums over the event times below . It holds at the first group, with and empty sums. Line L7 adds the terms of if is an event time, with at that moment, and line L8 removes the subjects at , so , which is the count at risk at the next distinct time. The same argument covers the binomial sum and the sequential tie rule, which only change the term added in line L7.
For the remaining claims, fix a time , let the support of in be a finite set , and let be the discrete hazard. The cumulative hazard of the discrete distribution is . Observed event times in are among the , so , with (and the term ) where no event is observed, and the term when . Assume:
- the subjects are independent;
- independent censoring in the sequential form: given everything observed before (which determines who is at risk at ), each subject at risk at has an event at with probability , independently of the others.
Condition 2 holds when the pairs are independent and is independent of . Let be the information observed before ; then is -measurable, and given is binomial with trials and success probability .
Claim 2 (martingale). is a martingale with respect to , and so is minus its compensator: .
Proof. and are -measurable, bounded, and have conditional mean given , because . A sum of bounded increments with conditional mean is a martingale.
Claim 3 (bias). , so is unbiased for in mean, and
Proof. by Claim 2, and . Take expectations. For the bound, for , so .
Claim 4 (variance). , and (for ) has conditional mean given .
Proof. Martingale increments are uncorrelated: for , the increment at is -measurable and the increment at has conditional mean given . So the variance of the sum is the sum of the expected conditional variances, and the conditional variance of given is on . For the second statement, . Divide by .
The binomial estimate of the code uses in place of , and Aalen's has conditional mean , which is the continuous-time limit where .
Claim 5 (maximum likelihood). Under conditions 1 and 2, with noninformative censoring, the likelihood of the hazards is times a factor free of (the Kaplan-Meier correctness proof derives this product). Each factor is maximized uniquely at when . By the invariance of maximum likelihood under the map , is the MLE of in this model.
Cost. One sort, , and a pass in which each subject advances the index once, . The sequential tie rule adds terms at , in total.
Complexity
Line L1 sorts in comparisons. Lines L4 to L8 handle each subject once with arithmetic, in . The total is time and extra space in the real RAM model, and if the data are already sorted. Every term is positive, so the floating-point sum has relative error at most about units in the last place for event times, with no cancellation.
Properties
- Martingale and bias. In continuous time, is a martingale, and with is a martingale with mean zero (Aalen 1978). So is unbiased for , and , which is exponentially small in when .
- Variance. The predictable variation of is , estimated by . With ties, is conditionally unbiased for the binomial variance; has in place of .
- Large samples. If , then in probability, and converges to a Gaussian martingale with variance for continuous , where (Andersen et al. 1993, Chapter IV).
- Relation to Kaplan-Meier. , because term by term. The Kaplan-Meier estimate is the product integral of : . Both are consistent for in continuous time, where the hazard increments are small.
- Maximum likelihood. For a discrete model with hazards at the observed event times, is the MLE of , and is the MLE of .
The measured finite-sample behaviour, with exponential with rate 1, independent exponential with rate 0.5, with (), replications and seed 1972:
| mean of | variance of | mean of | mean of | plain 95% with | log-scale 95% | |
|---|---|---|---|---|---|---|
| 20 | 0.690 | 0.0658 | 0.0642 | 0.0569 | 0.915 | 0.960 |
| 50 | 0.691 | 0.0253 | 0.0248 | 0.0238 | 0.933 | 0.949 |
| 200 | 0.691 | 0.00619 | 0.00610 | 0.00604 | 0.946 | 0.949 |
The log-scale interval is . In the same runs, the mean of was 0.517 at against 0.502 for Kaplan-Meier, both for .
Variants and improvements
- Tie rules. The Breslow form and the sequential form . The second is larger and corresponds to events that are distinct but recorded at the same time.
- Delayed entry. With entry times , use the risk set . The estimate is then of .
- Smoothed hazard. A kernel smoother applied to the increments of estimates the hazard itself (Ramlau-Hansen 1983).
- Covariates. The Breslow estimator of the baseline cumulative hazard in the Cox model replaces by . Aalen's additive model gives covariate effects on the cumulative hazard scale.
- Several states. The Nelson-Aalen estimates of the transition hazards of a multi-state model, combined by a product integral, give the Aalen-Johansen estimator of the transition probabilities, used for competing risks.
When to use it
Use Nelson-Aalen when the hazard is of interest: to see whether it is constant ( linear in ), Weibull ( linear in ) or proportional between groups (parallel curves). It is the building block for the cumulative incidence in competing risks and for the baseline hazard in regression. To estimate a survival probability, the Kaplan-Meier estimator is the standard choice; is close to it when risk sets are large.
Pitfalls
- is not a probability. It can exceed 1, and it does when the curve continues long enough. , not , is a probability.
- Slope, not level. The hazard is the slope of . A large means much risk accumulated, not a high current hazard.
- Ties in grouped data. With coarse time units many events share a time, and the two tie rules and the two variance estimates differ. Report which one is used.
- Plain intervals near zero. For small the interval can go below 0 and undercovers. Use the log-scale interval.
- The right tail. Late steps rest on few subjects and have large variance; grows by at each step.
- Independent censoring. As for Kaplan-Meier, dependent censoring biases , and the data cannot reveal it.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nelson-aalen-estimator/. The authors are listed in prov/2X5FTW.jsonl.
import math
from collections.abc import Sequence
from fractions import Fraction
from typing import NamedTuple
class Step(NamedTuple):
"""One distinct event time t_j of the Nelson-Aalen table."""
time: float
at_risk: int # n_j, the number with y_i >= t_j
events: int # d_j, the number of events at t_j
cum_hazard: float # H-hat(t_j)
var_poisson: float # sum over t_l <= t_j of d_l / n_l^2 (Aalen's estimate)
var_binomial: float # sum over t_l <= t_j of d_l (n_l - d_l) / n_l^3
def _increment(r: int, d: int, ties: str, exact: bool):
if ties == "breslow":
return Fraction(d, r) if exact else d / r
if ties == "sequential":
# The events at t_j are taken one after another: 1/r + 1/(r - 1) + ... + 1/(r - d + 1).
s = sum((Fraction(1, r - l) for l in range(d)), Fraction(0))
return s if exact else float(s)
raise ValueError("ties must be 'breslow' or 'sequential'")
def nelson_aalen(times: Sequence[float], events: Sequence[int], exact: bool = False, ties: str = "breslow") -> list[Step]:
"""Nelson-Aalen estimate of the cumulative hazard from right-censored data.
times[i] is y_i = min(T_i, C_i) and events[i] is 1 for an event and 0 for a
censoring. A censoring tied with an event counts as at risk at that time.
ties='breslow' adds d_j / n_j at each event time; ties='sequential' adds
1/n_j + 1/(n_j - 1) + ... + 1/(n_j - d_j + 1). With exact=True the values
are Fractions. Cost: one sort, O(n log n), and one O(n) scan.
"""
n = len(times)
if n == 0 or len(events) != n:
raise ValueError("need the same positive number of times and event flags")
if any(e not in (0, 1) for e in events):
raise ValueError("event flags must be 0 or 1")
zero = Fraction(0) if exact else 0.0
order = sorted(range(n), key=lambda k: times[k]) # @line L1
r, h, v, w, out = n, zero, zero, zero, [] # @line L2
i = 0 # @line L3
while i < n: # @line L4
t, d, c = times[order[i]], 0, 0 # @line L5
while i < n and times[order[i]] == t: # @line L6
if events[order[i]]:
d += 1
else:
c += 1
i += 1
if d > 0: # @line L7
h += _increment(r, d, ties, exact)
v += Fraction(d, r * r) if exact else d / (r * r)
w += Fraction(d * (r - d), r**3) if exact else d * (r - d) / r**3
out.append(Step(t, r, d, h, v, w))
r -= d + c # @line L8
return out # @line L9
def evaluate(steps: list[Step], t: float, field: str = "cum_hazard"):
"""The value of a step-function field at time t (0 before the first event time)."""
value = 0
for step in steps:
if step.time > t:
break
value = getattr(step, field)
return value
def survival_from_hazard(steps: list[Step], t: float) -> float:
"""The estimate exp(-H-hat(t)) of the survival function."""
return math.exp(-float(evaluate(steps, t)))
test_nelson_aalen_estimator.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nelson-aalen-estimator/. The authors are listed in prov/2X5FTW.jsonl.
import math
import random
from fractions import Fraction
import pytest
from nelson_aalen_estimator import evaluate, nelson_aalen, survival_from_hazard
# 6-MP arm of Freireich et al. (1963), as listed by Gehan (1965). 0 marks a censored time.
MP_T = [6, 6, 6, 6, 7, 9, 10, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 32, 32, 34, 35]
MP_D = [1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]
def direct(times, events, t):
"""Direct summation over the distinct event times s <= t of d(s)/n(s), d(s)/n(s)^2 and d(s)(n(s)-d(s))/n(s)^3."""
h = v = w = Fraction(0)
for s in sorted({y for y, e in zip(times, events) if e}):
if s > t:
break
n = sum(1 for y in times if y >= s)
d = sum(1 for y, e in zip(times, events) if y == s and e)
h += Fraction(d, n)
v += Fraction(d, n * n)
w += Fraction(d * (n - d), n**3)
return h, v, w
def test_six_mp_table() -> None:
steps = nelson_aalen(MP_T, MP_D, exact=True)
assert [(s.time, s.at_risk, s.events) for s in steps] == [
(6, 21, 3), (7, 17, 1), (10, 15, 1), (13, 12, 1), (16, 11, 1), (22, 7, 1), (23, 6, 1)
]
h = Fraction(3, 21) + Fraction(1, 17) + Fraction(1, 15) + Fraction(1, 12) + Fraction(1, 11) + Fraction(1, 7) + Fraction(1, 6)
assert steps[-1].cum_hazard == h
assert math.isclose(float(h), 0.75211, abs_tol=5e-6)
assert math.isclose(float(steps[-1].var_poisson), 0.07810, abs_tol=5e-6)
assert steps[0].var_poisson == Fraction(3, 441) and steps[0].var_binomial == Fraction(54, 9261)
assert math.isclose(survival_from_hazard(steps, 23), 0.47137, abs_tol=5e-6)
assert evaluate(steps, 5) == 0 and evaluate(steps, 100) == h
def test_against_direct_summation() -> None:
rng = random.Random(1969)
for _ in range(300):
n = rng.randint(1, 25)
times = [rng.randint(1, rng.randint(1, 12)) for _ in range(n)]
p = rng.random()
events = [0 if rng.random() < p else 1 for _ in range(n)]
steps = nelson_aalen(times, events, exact=True)
for t in range(0, max(times) + 2):
h, v, w = direct(times, events, t)
assert evaluate(steps, t) == h
assert evaluate(steps, t, "var_poisson") == v
assert evaluate(steps, t, "var_binomial") == w
def test_exp_minus_h_is_at_least_kaplan_meier() -> None:
rng = random.Random(1972)
for _ in range(200):
n = rng.randint(1, 25)
times = [rng.randint(1, 10) for _ in range(n)]
events = [rng.randint(0, 1) for _ in range(n)]
steps = nelson_aalen(times, events)
s = 1.0
for st in steps:
s *= 1 - st.events / st.at_risk
assert math.exp(-st.cum_hazard) >= s - 1e-15
def test_sequential_ties_equal_broken_ties() -> None:
# Breaking the ties among events at t_j into distinct nearby times gives the sequential sum.
rng = random.Random(1978)
for _ in range(200):
n = rng.randint(1, 20)
times = [rng.randint(1, 6) for _ in range(n)]
events = [rng.randint(0, 1) for _ in range(n)]
seq = nelson_aalen(times, events, exact=True, ties="sequential")
# Spread the events of each tie over distinct times just below the next integer.
# Censorings at t move after all events at t, to t + 0.9, keeping them at risk.
spread, k = [], {}
for y, e in zip(times, events):
if e:
k[y] = k.get(y, 0) + 1
spread.append(y + Fraction(k[y], 1000))
else:
spread.append(y + Fraction(9, 10))
broken = nelson_aalen(spread, events, exact=True)
for t in range(0, 8):
assert evaluate(seq, t) == evaluate(broken, t + Fraction(1, 2))
def test_monte_carlo_mean_and_variance() -> None:
# T ~ Exp(1), C ~ Exp(0.5), n = 40, t = log 2, so H(t) = log 2. r = 2000, seed 2026.
rng = random.Random(2026)
n, r, t = 40, 2000, math.log(2)
hs, vs = [], []
for _ in range(r):
y, d = [], []
for _ in range(n):
a, b = rng.expovariate(1.0), rng.expovariate(0.5)
y.append(min(a, b))
d.append(1 if a <= b else 0)
steps = nelson_aalen(y, d)
hs.append(evaluate(steps, t))
vs.append(evaluate(steps, t, "var_poisson"))
mean = sum(hs) / r
var = sum((x - mean) ** 2 for x in hs) / (r - 1)
assert abs(mean - t) < 4 * math.sqrt(var / r)
assert abs(sum(vs) / r / var - 1) < 0.15
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
nelson_aalen([], [])
with pytest.raises(ValueError):
nelson_aalen([1, 2], [1, 3])
with pytest.raises(ValueError):
nelson_aalen([1, 2], [1, 1], ties="efron")
History
Wayne Nelson, an engineer at General Electric, introduced the cumulative hazard plot for censored failure data in 1969 and gave its theory in Technometrics in 1972: one plots the running sum of against time on paper scaled for a parametric family and reads off whether the family fits. Odd Aalen, in his 1975 Berkeley thesis and his 1978 Annals paper, placed the estimate in the theory of counting processes: for any counting process with intensity , the estimator of is a martingale transform, and martingale central limit theorems give its large-sample laws. This view, developed further by Gill and by Andersen, Borgan and Keiding, became the basis of modern survival analysis.
References
- Wayne Nelson, Hazard plotting for incomplete failure data, Journal of Quality Technology 1(1), 1969, pp. 27 to 52 (the cumulative hazard plot, with the sum of the reciprocals of the numbers at risk)
- Wayne Nelson, Theory and applications of hazard plotting for censored failure data, Technometrics 14(4), 1972, from p. 945 (the theory of the cumulative hazard estimate and its plots)
- Odd Aalen, Nonparametric inference for a family of counting processes, Annals of Statistics 6(4), 1978, pp. 701 to 726 (the multiplicative intensity model, the estimator of the integrated intensity and its martingale properties)
- Per Kragh Andersen, Ørnulf Borgan, Richard D. Gill and Niels Keiding, Statistical Models Based on Counting Processes, Springer, 1993, Chapter IV (the Nelson-Aalen estimator, its variance estimators, the tie conventions and the large-sample theory)
- John P. Klein and Melvin L. Moeschberger, Survival Analysis, Techniques for Censored and Truncated Data, 2nd edition, Springer, 2003, Chapter 4 (the Nelson-Aalen estimator of the cumulative hazard with its variance and confidence intervals)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2X5FTW Edit this page History Report an error Markdown