Algorithm Search⌘K

Algorithmadvanced

Breslow estimator

Also called Breslow baseline hazard estimator.

Estimates the cumulative baseline hazard of a Cox model by summing the deaths over the risk-weighted sum of exp(x^T beta) of those at risk at each event time.

Time
Θ(n log n + n p) worst
Space
Θ(n) extra
Where
k = the number of distinct event times; n = the number of subjects; p = the number of covariates
Properties
deterministicexactofflineiterative
Origin
Norman E. Breslow, 1974

The Breslow estimator turns a fitted Cox model into survival curves. The partial likelihood estimates β\beta but says nothing about the baseline hazard h0h_0. Given β\beta, Breslow's estimate of the cumulative baseline hazard H0(t)=∫0th0(u) duH_0(t) = \int_0^t h_0(u)\,du is

H^0(t)=∑j: tj≤tdj∑i∈R(tj)exp⁡(βTxi),\hat H_0(t) = \sum_{j:\, t_j \le t} \frac{d_j}{\sum_{i \in R(t_j)} \exp(\beta^{\mathsf T}x_i)},

where tjt_j are the distinct event times, djd_j the number of events at tjt_j and R(tj)={i:yi≥tj}R(t_j) = \{i : y_i \ge t_j\} the risk set. The survival curve for covariate xx is then S^(t∣x)=exp⁡(−H^0(t) eβTx)\hat S(t \mid x) = \exp\bigl(-\hat H_0(t)\, e^{\beta^{\mathsf T}x}\bigr). At β=0\beta = 0 the estimate is the Nelson-Aalen estimator. One sort and one backward pass of running sums compute it in Θ(nlog⁡n)\Theta(n \log n) time.

In plain words

The Nelson-Aalen estimator adds, at each event time, the number of events divided by the number of people at risk. In a Cox model people at risk are not equal: someone with relative risk 3 counts like three people with relative risk 1. So the Breslow estimator divides the number of events by the sum of the relative risks of the people at risk. The result is the cumulative hazard of a person whose covariates are all zero. Multiply it by a person's relative risk to get that person's cumulative hazard, and take ee to minus that to get their survival curve.

The problem

Input. Observations (yi,δi,xi)(y_i, \delta_i, x_i) for i=1,…,ni = 1, \ldots, n, where yiy_i is the observed time, δi=1\delta_i = 1 for an event and 00 for a censored time, and xi∈Rpx_i \in \mathbb{R}^p. A coefficient vector β\beta, usually the Cox estimate β^\hat\beta. The code takes the risk scores wi=exp⁡(βTxi)w_i = \exp(\beta^{\mathsf T}x_i), which cost O(np)O(np) to compute.

Model. The hazard of subject ii is h0(t)wih_0(t) w_i with h0h_0 unspecified, and censoring is independent, as on the censoring page.

Output. The distinct event times t1<⋯<tkt_1 < \cdots < t_k, and at each the risk sum Sj=∑i∈R(tj)wiS_j = \sum_{i \in R(t_j)} w_i, the count djd_j, the increment, H^0(tj)\hat H_0(t_j), and the variance term ∑l≤jdl/Sl2\sum_{l \le j} d_l/S_l^2. H^0\hat H_0 is the right-continuous step function with these values, 00 before t1t_1.

Ties. A censored time equal to an event time counts as at risk at that time. With tied events the Breslow rule adds dj/Sjd_j/S_j. The Efron rule, which matches the Efron partial likelihood, adds ∑r=0dj−11/(Sj−rdjDj)\sum_{r=0}^{d_j - 1} 1/(S_j - \frac{r}{d_j}D_j), where DjD_j is the sum of wiw_i over the djd_j subjects with the event.

The algorithm

  1. BRESLOW(y[1..n], δ[1..n], w[1..n], ties)
  2. 1sort the indices 1..n by decreasing y
  3. 2S ← 0; rows ← empty list
  4. 3for each distinct time t in that order
  5. 4for each i with y_i = t: S ← S + w_i; if δ_i = 1 then d ← d + 1, D ← D + w_i
  6. 5if d > 0 then append (t, S, d, D) to rows
  7. 6reverse rows ▷ now in increasing time
  8. 7H ← 0; V ← 0; for each (t, S, d, D) in rows
  9. 8inc ← d / S (Efron: Σ_{r<d} 1 / (S - rD/d))
  10. 9H ← H + inc; V ← V + d / S²; output (t, S, d, inc, H, V)

Line L1 sorts once. Lines L3 and L4 visit the times from the largest down, so SS is a running sum that only grows: when the group at time tt is done, S=∑yi≥twiS = \sum_{y_i \ge t} w_i, which is exactly the risk sum at tt. The counters dd and DD start at 00 for each group. Line L5 keeps only event times. Lines L7 to L9 then add the increments in time order. VV estimates the variance of H^0(t)\hat H_0(t) when β\beta is known.

Example

A small example. Times 1,2,3+,4,51, 2, 3^+, 4, 5 with x=1,0,1,0,1x = 1, 0, 1, 0, 1. At β=0\beta = 0 all wi=1w_i = 1, the risk sums are 5,4,2,15, 4, 2, 1 at the event times 1,2,4,51, 2, 4, 5, and

H^0=15,15+14=920,920+12=1920,1920+1=3920,\hat H_0 = \tfrac15,\quad \tfrac15 + \tfrac14 = \tfrac{9}{20},\quad \tfrac{9}{20} + \tfrac12 = \tfrac{19}{20},\quad \tfrac{19}{20} + 1 = \tfrac{39}{20},

the Nelson-Aalen estimate. There are no tied events, so the Efron rule gives the same values.

The leukemia data. The Gehan data have 21 patients on 6-MP and 21 on placebo, with 30 events at 17 distinct times. Take x=1x = 1 for placebo and the Breslow-ties estimate β^=1.509191\hat\beta = 1.509191, so a placebo patient has w=eβ^=4.5231w = e^{\hat\beta} = 4.5231 and a 6-MP patient w=1w = 1. At t=1t = 1 all 42 are at risk, so S1=21+21⋅4.5231=115.98S_1 = 21 + 21 \cdot 4.5231 = 115.98 and the increment is 2/115.98=0.017242/115.98 = 0.01724. Some rows of the output:

tt djd_j SjS_j H^0(t)\hat H_0(t) standard error, β\beta fixed S^(t)\hat S(t), 6-MP S^(t)\hat S(t), placebo
1 2 115.98 0.0172 0.0122 0.983 0.925
4 2 93.37 0.0676 0.0256 0.935 0.737
8 4 70.28 0.2021 0.0498 0.817 0.401
12 2 39.14 0.3134 0.0706 0.731 0.242
17 1 23.57 0.4641 0.1036 0.629 0.123
23 2 10.52 0.7788 0.1912 0.459 0.030

The 6-MP column is exp⁡(−H^0(t))\exp(-\hat H_0(t)) and the placebo column is exp⁡(−4.5231 H^0(t))\exp(-4.5231\,\hat H_0(t)). Compare the Kaplan-Meier values of the two arms: 0.448 for 6-MP at week 23, and 8/21=0.3818/21 = 0.381 for placebo after week 8. The model curves are close but not equal, because the Cox model forces the two curves to be powers of each other. With the Efron rule, H^0(23)=0.8400\hat H_0(23) = 0.8400 at the Efron estimate. Summing the residuals wiH^0(yi)w_i \hat H_0(y_i) over all 42 patients gives exactly 30, the number of events.

Correctness

The proof in proofs/correctness.md shows five things. First, the backward pass keeps the invariant that S=∑yi>twiS = \sum_{y_i > t} w_i at the start of the group at tt, so every output row is (tj,Sj,dj)(t_j, S_j, d_j) and H=H^0(tj)H = \hat H_0(t_j) after line L9. Second, at β=0\beta = 0 the estimate is Nelson-Aalen, and the Efron increment is at least dj/njd_j/n_j, with equality iff dj=1d_j = 1. Third, for fixed β\beta, H^0\hat H_0 is the unique maximizer of the full likelihood over all step-function cumulative hazards, and the maximum equals e−d∏jdjdje^{-d}\prod_j d_j^{d_j} times the Breslow-ties partial likelihood, so the Cox estimate with H^0(⋅ ;β^)\hat H_0(\cdot\,; \hat\beta) is a joint profile maximum likelihood estimate. Fourth, the Cox-Snell residuals wiH^0(yi)w_i\hat H_0(y_i) sum to the number of events dd for every β\beta. Fifth, with β\beta fixed, VV estimates the variance by the Nelson-Aalen argument. The extra variance from estimating β\beta is cited, not proved.

Proof: The pass computes the Breslow sums, which reduce to Nelson-Aalen at beta = 0, maximize the full likelihood over the baseline jumps, and make the Cox-Snell residuals sum to the number of eventsfull

Let the data be (yi,δi,xi)(y_i, \delta_i, x_i), i=1,…,ni = 1, \ldots, n, with risk scores wi=exp⁡(βTxi)>0w_i = \exp(\beta^{\mathsf T}x_i) > 0 for a fixed β\beta. Let t1<⋯<tkt_1 < \cdots < t_k be the distinct event times, Rj={i:yi≥tj}R_j = \{i : y_i \ge t_j\} the risk set, nj=∣Rj∣n_j = |R_j|, djd_j the number of events at tjt_j, Sj=∑i∈RjwiS_j = \sum_{i \in R_j} w_i and DjD_j the sum of wiw_i over the djd_j subjects that have the event at tjt_j. The Breslow estimate is

H^0(t)=∑tj≤tdjSj.\hat H_0(t) = \sum_{t_j \le t} \frac{d_j}{S_j}.

Claim 1 (the pass computes the sums). Every row that line L5 keeps is (tj,Sj,dj,Dj)(t_j, S_j, d_j, D_j), one row for each jj, and after line L9 the variable HH holds H^0(tj)\hat H_0(t_j).

Proof. Line L1 sorts the subjects by decreasing time. The inner loop of line L4 reads exactly the subjects at the current distinct time uu. Invariant: at the start of the group at uu, the variable SS is the sum of wiw_i over {i:yi>u}\{i : y_i > u\}. It holds at the first group with the empty sum. The group adds the wiw_i of all subjects with yi=uy_i = u, so after the group S=∑yi≥uwiS = \sum_{y_i \ge u} w_i, which is SjS_j when u=tju = t_j. In the same loop dd and DD count the events at uu and add their scores. Line L5 keeps the row only if d>0d > 0, that is, if uu is an event time. Line L6 puts the rows in increasing order of time, and lines L7 to L9 add dj/Sjd_j/S_j in that order. □\square

The sum SjS_j is built from the largest time down, so each SjS_j is a sum of positive terms. A forward pass that subtracts the scores that leave the risk set would give the same value in exact arithmetic, but in floating point it can cancel when the late scores are small compared with the early ones.

Claim 2 (Nelson-Aalen at β=0\beta = 0). If β=0\beta = 0, then H^0(t)=∑tj≤tdj/nj\hat H_0(t) = \sum_{t_j \le t} d_j/n_j, the Nelson-Aalen estimator. With the Efron rule the increment at tjt_j is at least dj/njd_j/n_j, with equality exactly when dj=1d_j = 1.

Proof. At β=0\beta = 0 every wi=1w_i = 1, so Sj=njS_j = n_j and Dj=djD_j = d_j. The Breslow increment is dj/njd_j/n_j. The Efron increment is ∑r=0dj−11/(nj−r)\sum_{r=0}^{d_j - 1} 1/(n_j - r). Each term is at least 1/nj1/n_j, and the term with r=1r = 1 is strictly larger when dj≥2d_j \ge 2. □\square

Claim 3 (profile maximum likelihood). Fix β\beta. Over all cumulative baseline hazards Λ0\Lambda_0 that are nondecreasing step functions, the full likelihood

L(β,Λ0)=∏i=1n(wi ΔΛ0(yi))δiexp⁡(−wiΛ0(yi))L(\beta, \Lambda_0) = \prod_{i=1}^n \bigl(w_i\,\Delta\Lambda_0(y_i)\bigr)^{\delta_i} \exp\bigl(-w_i \Lambda_0(y_i)\bigr)

is maximized uniquely by Λ0=H^0\Lambda_0 = \hat H_0. The maximum value is e−d∏jdjdje^{-d} \prod_j d_j^{d_j} times the Cox partial likelihood with the Breslow tie rule, where d=∑jdjd = \sum_j d_j.

Proof. If Λ0\Lambda_0 has no jump at some tjt_j, then L=0L = 0, so a maximizer has a jump λj>0\lambda_j > 0 at each tjt_j. A jump at a time that is not an event time does not change any factor ΔΛ0(yi)\Delta\Lambda_0(y_i) with δi=1\delta_i = 1, and it increases Λ0(yi)\Lambda_0(y_i) for every yiy_i at or after it, so removing it does not decrease LL, and strictly increases LL if some yiy_i is at or after it. So it is sufficient to take Λ0(t)=∑tj≤tλj\Lambda_0(t) = \sum_{t_j \le t} \lambda_j. Then

log⁡L=∑iδiβTxi+∑jdjlog⁡λj−∑iwi∑tj≤yiλj=∑iδiβTxi+∑j(djlog⁡λj−λjSj),\log L = \sum_{i} \delta_i \beta^{\mathsf T}x_i + \sum_{j} d_j \log\lambda_j - \sum_i w_i \sum_{t_j \le y_i} \lambda_j = \sum_i \delta_i \beta^{\mathsf T}x_i + \sum_j \bigl(d_j \log\lambda_j - \lambda_j S_j\bigr),

because tj≤yit_j \le y_i is the same as i∈Rji \in R_j. Each term djlog⁡λj−λjSjd_j \log\lambda_j - \lambda_j S_j is strictly concave in λj>0\lambda_j > 0, and its derivative dj/λj−Sjd_j/\lambda_j - S_j is 00 only at λj=dj/Sj\lambda_j = d_j/S_j. Put this value back:

log⁡L=∑iδiβTxi−∑jdjlog⁡Sj+∑jdjlog⁡dj−d.\log L = \sum_i \delta_i \beta^{\mathsf T}x_i - \sum_j d_j \log S_j + \sum_j d_j \log d_j - d.

The first two sums are the log partial likelihood with the Breslow tie rule (see partial likelihood). □\square

So the joint maximizer of LL over (β,Λ0)(\beta, \Lambda_0) is the Breslow-ties Cox estimate together with the Breslow estimator at that estimate.

Claim 4 (residuals). For every β\beta, the Cox-Snell residuals ri=wiH^0(yi)r_i = w_i \hat H_0(y_i) sum to dd, so the martingale residuals δi−ri\delta_i - r_i sum to 00.

Proof. Change the order of summation:

∑iwiH^0(yi)=∑iwi∑tj≤yidjSj=∑jdjSj∑i∈Rjwi=∑jdj=d.□\sum_i w_i \hat H_0(y_i) = \sum_i w_i \sum_{t_j \le y_i} \frac{d_j}{S_j} = \sum_j \frac{d_j}{S_j} \sum_{i \in R_j} w_i = \sum_j d_j = d. \qquad \square

The identity does not need β\beta to be the Cox estimate, and it fails for the Efron rule, whose increment times SjS_j is larger than djd_j when dj≥2d_j \ge 2.

Claim 5 (variance with β\beta fixed). Under the counting process model with intensity Yi(t)wih0(t)Y_i(t) w_i h_0(t) and β\beta known, H^0(t)−∫0t1{S(u)>0} dH0(u)\hat H_0(t) - \int_0^t 1\{S(u) > 0\}\,dH_0(u) is a martingale, and ∑tj≤tdj/Sj2\sum_{t_j \le t} d_j/S_j^2 estimates its variance. This is the argument of the Nelson-Aalen proof with njn_j replaced by SjS_j, and we do not repeat it. When β\beta is replaced by β^\hat\beta, the variance gets an extra term q(t)TI(β^)−1q(t)q(t)^{\mathsf T} \mathcal I(\hat\beta)^{-1} q(t) with q(t)=∑tj≤tdjxˉj/Sjq(t) = \sum_{t_j \le t} d_j \bar x_j / S_j and xˉj\bar x_j the weighted mean of xx over RjR_j (Tsiatis 1981; Andersen and Gill 1982). We cite this result and do not prove it here.

Cost. One sort, Θ(nlog⁡n)\Theta(n \log n), one pass over the subjects, Θ(n)\Theta(n), and one pass over the event times. The Efron rule adds djd_j terms at tjt_j, O(n)O(n) in total. The risk scores cost O(np)O(np) for pp covariates.

Complexity

The risk scores cost Θ(np)\Theta(np). The sort in line L1 costs Θ(nlog⁡n)\Theta(n \log n) comparisons. Lines L3 and L4 visit each subject once, and lines L7 to L9 visit each event time once, so the passes cost Θ(n)\Theta(n) with the Breslow rule. The Efron rule adds djd_j terms at tjt_j, Θ(n)\Theta(n) in total. The extra space is Θ(n)\Theta(n) for the order and the k≤nk \le n rows. A value H^0(t)\hat H_0(t) then costs O(log⁡k)O(\log k) by a binary search, and a whole survival curve for a new xx costs O(k+p)O(k + p).

In floating point, each SjS_j is a sum of positive terms with a relative error of about nn units in the last place, and no cancellation happens. A forward pass that starts from the total and subtracts the scores that leave would give the same values in exact arithmetic but can lose all digits when the late scores are much smaller than the early ones. With rational scores, such as the integer 11 at β=0\beta = 0, the code returns exact Fractions.

Properties

  • Reduces to Nelson-Aalen. At β=0\beta = 0, Sj=njS_j = n_j and the estimate is ∑tj≤tdj/nj\sum_{t_j \le t} d_j/n_j.
  • Profile maximum likelihood. It is the nonparametric maximum likelihood estimate of H0H_0 for fixed β\beta. Profiling it out of the full likelihood gives back the Breslow partial likelihood.
  • Martingale residuals sum to zero. ∑i(δi−wiH^0(yi))=0\sum_i (\delta_i - w_i\hat H_0(y_i)) = 0 for every β\beta, with the Breslow rule.
  • Equivariance. Shifting a covariate, x→x+cx \to x + c, multiplies every wiw_i by eβTce^{\beta^{\mathsf T}c} and divides H^0\hat H_0 by the same factor. H^0\hat H_0 is the cumulative hazard at x=0x = 0, so center the covariates if that value is not meaningful. The survival curve for a given xx does not change.
  • Large-sample behavior. If β^\hat\beta is the Cox estimate and the model holds, n(H^0−H0)\sqrt n(\hat H_0 - H_0) converges on [0,τ][0, \tau] to a Gaussian process whose variance is ∫0tdH0/s(0)\int_0^t dH_0/s^{(0)} plus the term q(t)TΣq(t)q(t)^{\mathsf T}\Sigma q(t) from the uncertainty in β^\hat\beta (Tsiatis 1981; Andersen and Gill 1982). This is cited, not proved here.
  • The curves do not cross. For two covariate values x1,x2x_1, x_2, S^(t∣x2)=S^(t∣x1)exp⁡(βT(x2−x1))\hat S(t \mid x_2) = \hat S(t \mid x_1)^{\exp(\beta^{\mathsf T}(x_2 - x_1))}, so the curves never cross.

Variants and improvements

  • Efron increments. With many tied events, use the Efron rule of line L8 together with the Efron partial likelihood, so the estimate is consistent with the fit.
  • Kalbfleisch-Prentice estimate. Solve, at each tjt_j, for a conditional survival probability αj\alpha_j so that S^0(t)=∏tj≤tαj\hat S_0(t) = \prod_{t_j \le t}\alpha_j is the maximum likelihood estimate under a discrete baseline. It reduces to Kaplan-Meier at β=0\beta = 0, as the Breslow estimate reduces to Nelson-Aalen.
  • Product-limit form. ∏tj≤t(1−dj/Sj)eβTx\prod_{t_j \le t}(1 - d_j/S_j)^{e^{\beta^{\mathsf T}x}}, a Kaplan-Meier style variant, avoids the exponential. It is close to exp⁡(−H^0eβTx)\exp(-\hat H_0 e^{\beta^{\mathsf T}x}) when every dj/Sjd_j/S_j is small.
  • Strata. With a stratified Cox model, run the pass once per stratum to get one H^0s\hat H_{0s} per stratum.
  • Time-dependent covariates and delayed entry. The risk sum must use wi(tj)w_i(t_j) and the subjects under observation at tjt_j. A pass in time order that adds entries and removes exits replaces the backward pass.
  • Weighted versions. Weights in the risk sums give the baseline of the Fine-Gray model, and the frailty-weighted sums in the EM algorithm for the frailty model.

When to use it

Use it after a Cox fit whenever you need absolute risks rather than hazard ratios: predicted survival probabilities, median survival for a covariate profile, the Cox-Snell and martingale residuals, or calibration plots. Use it with the same tie rule as the fit. For one group without covariates use Kaplan-Meier or Nelson-Aalen directly.

Pitfalls

  • The baseline is at x=0x = 0. If x=0x = 0 is far from the data, such as age 0, H^0\hat H_0 is a large extrapolation and its numbers are not meaningful. Center the covariates or report curves for actual covariate profiles.
  • Standard errors with β\beta fixed are too small. The variance VV ignores the uncertainty in β^\hat\beta. Add the Tsiatis term for intervals on S^(t∣x)\hat S(t \mid x).
  • Tie rule mismatch. Breslow increments with an Efron fit give residuals that do not sum exactly to dd and curves that are slightly off.
  • Censored ties. Count a censored subject at tt in the risk sum at tt, as for Kaplan-Meier.
  • Proportional hazards. The curves for different xx are powers of each other. If the hazards are not proportional, the curves are wrong in shape, not only in level. Check with the Schoenfeld residuals, or stratify.
  • The tail. After the last event time with few subjects at risk, the increments are large and unstable, as in the last rows of the table.

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.

breslow_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/breslow-estimator/. The authors are listed in prov/NMKKND.jsonl.
"""Breslow estimator of the cumulative baseline hazard of a Cox model.

Input: times[i] = y_i, events[i] = delta_i (1 event, 0 censored) and the risk
scores w_i = exp(x_i' beta) for a given coefficient vector beta (usually the
Cox estimate). A censored time tied with an event time counts as at risk.
With ints or Fractions as scores the output is exact.
"""

import math
from collections.abc import Sequence
from fractions import Fraction
from typing import NamedTuple


class Step(NamedTuple):
    time: float  # t_j, a distinct event time
    risk_sum: object  # S0_j, the sum of w_i over the risk set {i : y_i >= t_j}
    events: int  # d_j
    increment: object  # the jump of H0-hat at t_j
    cum_hazard: object  # H0-hat(t_j)
    var: object  # sum over t_l <= t_j of d_l / S0_l^2, the variance with beta held fixed


def _div(a, b):
    if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
        return Fraction(a) / b
    return a / b


def breslow(times: Sequence, events: Sequence[int], scores: Sequence, ties: str = "breslow") -> list[Step]:
    """Cumulative baseline hazard H0-hat at each distinct event time.

    ties='breslow' adds d_j / S0_j; ties='efron' adds the sum over r < d_j of
    1 / (S0_j - (r / d_j) D_j), with D_j the sum of w over the d_j events.
    The risk sums are accumulated from the largest time down, so no running
    subtraction loses accuracy. Cost: one sort, O(n log n), and two O(n) passes.
    """
    n = len(times)
    if n == 0 or len(events) != n or len(scores) != n:
        raise ValueError("times, events and scores must have the same positive length")
    if any(e not in (0, 1) for e in events):
        raise ValueError("event flags must be 0 or 1")
    if any(not w > 0 for w in scores):
        raise ValueError("risk scores must be positive")
    if ties not in ("breslow", "efron"):
        raise ValueError("ties must be 'breslow' or 'efron'")
    order = sorted(range(n), key=lambda k: times[k], reverse=True)  # @line L1
    S, rows, i = 0, [], 0  # @line L2
    while i < n:  # @line L3
        t, d, D = times[order[i]], 0, 0
        while i < n and times[order[i]] == t:  # @line L4
            k = order[i]
            S += scores[k]
            if events[k]:
                d += 1
                D += scores[k]
            i += 1
        if d > 0:  # @line L5
            rows.append((t, S, d, D))
    rows.reverse()  # @line L6
    H, V, out = 0, 0, []
    for t, S, d, D in rows:  # @line L7
        if ties == "breslow" or d == 1:
            inc = _div(d, S)  # @line L8
        else:
            inc = sum(_div(1, S - _div(r * D, d)) for r in range(d))
        H += inc  # @line L9
        V += _div(d, S * S)
        out.append(Step(t, S, d, inc, H, V))
    return out


def risk_scores(X: Sequence[Sequence[float]], beta: Sequence[float]) -> list[float]:
    """w_i = exp(x_i' beta); the integer 1 for every i when beta = 0."""
    if all(b == 0 for b in beta):
        return [1] * len(X)
    return [math.exp(sum(a * b for a, b in zip(x, beta))) for x in X]


def evaluate(steps: list[Step], t: float):
    """H0-hat(t): the value at the last event time <= t, and 0 before the first."""
    lo, hi = 0, len(steps)
    while lo < hi:
        mid = (lo + hi) // 2
        if steps[mid].time <= t:
            lo = mid + 1
        else:
            hi = mid
    return steps[lo - 1].cum_hazard if lo else 0


def survival(steps: list[Step], t: float, score: float) -> float:
    """S-hat(t | x) = exp(-H0-hat(t) exp(x' beta)), with score = exp(x' beta)."""
    return math.exp(-float(evaluate(steps, t)) * float(score))


def cox_snell_residuals(times: Sequence, steps: list[Step], scores: Sequence) -> list:
    """r_i = H0-hat(y_i) w_i. With Breslow ties they sum to the number of events, for any beta."""
    return [evaluate(steps, y) * w for y, w in zip(times, scores)]
test_breslow_estimator.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/breslow-estimator/. The authors are listed in prov/NMKKND.jsonl.

import math
import random
from fractions import Fraction

from breslow_estimator import breslow, cox_snell_residuals, evaluate, risk_scores, survival

# Gehan (1965) leukemia remission data: 6-MP arm, then placebo arm (x = 1).
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]
PL_T = [1, 1, 2, 2, 3, 4, 4, 5, 5, 8, 8, 8, 8, 11, 11, 12, 12, 15, 17, 22, 23]
T = MP_T + PL_T
D = MP_D + [1] * 21
X = [0] * 21 + [1] * 21


def random_data(rng, n, ties=True):
    times = [rng.randint(1, 8) if ties else rng.random() for _ in range(n)]
    events = [1 if rng.random() < 0.7 else 0 for _ in range(n)]
    return times, events


def nelson_aalen(times, events):
    out = []
    H = Fraction(0)
    for t in sorted(set(y for y, e in zip(times, events) if e)):
        d = sum(1 for y, e in zip(times, events) if e and y == t)
        n = sum(1 for y in times if y >= t)
        H += Fraction(d, n)
        out.append((t, H))
    return out


def direct(times, events, scores, ties):
    """H0-hat by a fresh sum over the risk set at each event time, O(n) per time."""
    out, H = [], Fraction(0)
    for t in sorted(set(y for y, e in zip(times, events) if e)):
        S = sum(Fraction(w) for y, w in zip(times, scores) if y >= t)
        dead = [Fraction(w) for y, e, w in zip(times, events, scores) if e and y == t]
        d, Dsum = len(dead), sum(dead)
        if ties == "breslow":
            H += Fraction(d) / S
        else:
            H += sum(1 / (S - Fraction(r, d) * Dsum) for r in range(d))
        out.append((t, H))
    return out


def full_loglik(times, events, scores, jumps):
    """Log full likelihood with a baseline hazard that jumps only at event times.

    sum_j d_j log(lam_j) + sum_i delta_i log(w_i) - sum_i w_i Lambda0(y_i).
    """
    ts = sorted(jumps)
    total = 0.0
    for t in ts:
        d = sum(1 for y, e in zip(times, events) if e and y == t)
        total += d * math.log(jumps[t])
    for y, e, w in zip(times, events, scores):
        if e:
            total += math.log(w)
        total -= w * sum(jumps[t] for t in ts if t <= y)
    return total


def test_beta_zero_gives_nelson_aalen_exactly() -> None:
    rng = random.Random(1)
    for _ in range(40):
        times, events = random_data(rng, rng.randint(1, 15))
        if not any(events):
            continue
        steps = breslow(times, events, [1] * len(times))
        assert [(s.time, s.cum_hazard) for s in steps] == nelson_aalen(times, events)
        # Efron at beta = 0 does not reduce to Nelson-Aalen when there are ties.
        efron = breslow(times, events, [1] * len(times), "efron")
        for a, b in zip(steps, efron):
            assert b.increment >= a.increment
            assert (b.increment == a.increment) == (a.events == 1)


def test_matches_direct_summation_with_rational_scores() -> None:
    rng = random.Random(2)
    for _ in range(40):
        n = rng.randint(1, 14)
        times, events = random_data(rng, n)
        if not any(events):
            continue
        scores = [Fraction(rng.randint(1, 9), rng.randint(1, 5)) for _ in range(n)]
        for ties in ("breslow", "efron"):
            steps = breslow(times, events, scores, ties)
            assert [(s.time, s.cum_hazard) for s in steps] == direct(times, events, scores, ties)


def test_efron_increment_formula_by_hand() -> None:
    # Three subjects at risk with scores 1, 2, 3; the last two die together.
    steps = breslow([1, 2, 2], [0, 1, 1], [1, 2, 3], "efron")
    S, Dsum = 5, 5
    assert steps[0].increment == Fraction(1, S) + 1 / (S - Fraction(1, 2) * Dsum)
    assert steps[0].increment == Fraction(1, 5) + Fraction(2, 5)
    assert breslow([1, 2, 2], [0, 1, 1], [1, 2, 3])[0].increment == Fraction(2, 5)


def test_cox_snell_residuals_sum_to_number_of_events_for_any_scores() -> None:
    rng = random.Random(3)
    for _ in range(40):
        n = rng.randint(1, 14)
        times, events = random_data(rng, n)
        if not any(events):
            continue
        scores = [Fraction(rng.randint(1, 20), rng.randint(1, 7)) for _ in range(n)]
        steps = breslow(times, events, scores)
        r = cox_snell_residuals(times, steps, scores)
        assert sum(r) == sum(events)
        # Hence the martingale residuals delta_i - r_i sum to 0.
        assert sum(e - ri for e, ri in zip(events, r)) == 0


def test_profile_maximum_of_the_full_likelihood() -> None:
    rng = random.Random(4)
    for _ in range(20):
        n = rng.randint(2, 12)
        times, events = random_data(rng, n)
        if not any(events):
            continue
        scores = [Fraction(rng.randint(1, 9), rng.randint(1, 4)) for _ in range(n)]
        steps = breslow(times, events, scores)
        # The derivative d_j / lam_j - sum_{y_i >= t_j} w_i is exactly 0 at every jump.
        for s in steps:
            at_risk = sum(w for y, w in zip(times, scores) if y >= s.time)
            assert Fraction(s.events) / s.increment - at_risk == 0
        jumps = {s.time: float(s.increment) for s in steps}
        w = [float(v) for v in scores]
        best = full_loglik(times, events, w, jumps)
        for _ in range(10):
            other = {t: lam * math.exp(rng.uniform(-0.3, 0.3)) for t, lam in jumps.items()}
            assert full_loglik(times, events, w, other) < best + 1e-12


def test_variance_term_and_step_function() -> None:
    steps = breslow([1, 2, 2, 3, 5], [1, 1, 0, 1, 0], [1, 1, 1, 1, 1])
    assert [s.cum_hazard for s in steps] == [Fraction(1, 5), Fraction(1, 5) + Fraction(1, 4), Fraction(1, 5) + Fraction(1, 4) + Fraction(1, 2)]
    assert steps[-1].var == Fraction(1, 25) + Fraction(1, 16) + Fraction(1, 4)
    assert evaluate(steps, 0.5) == 0
    assert evaluate(steps, 2.5) == Fraction(9, 20)
    assert evaluate(steps, 100) == Fraction(19, 20)
    assert abs(survival(steps, 2, 2.0) - math.exp(-0.9)) < 1e-15


def _cox_fit_one_covariate(times, events, x):
    """Newton on the Breslow log partial likelihood for one covariate."""
    b = 0.0
    for _ in range(50):
        U = I = 0.0
        for t in sorted(set(y for y, e in zip(times, events) if e)):
            S0 = S1 = S2 = 0.0
            for y, xi in zip(times, x):
                if y >= t:
                    w = math.exp(b * xi)
                    S0 += w
                    S1 += w * xi
                    S2 += w * xi * xi
            dead = [xi for y, e, xi in zip(times, events, x) if e and y == t]
            U += sum(dead) - len(dead) * S1 / S0
            I += len(dead) * (S2 / S0 - (S1 / S0) ** 2)
        step = U / I
        b += step
        if abs(step) < 1e-13:
            break
    return b


def test_gehan_leukemia_baseline() -> None:
    b = _cox_fit_one_covariate(T, D, X)
    assert abs(b - 1.509191) < 1e-5
    w = risk_scores([[x] for x in X], [b])
    steps = breslow(T, D, w)
    assert len(steps) == 17
    assert sum(s.events for s in steps) == 30
    # Baseline (6-MP arm) at the first event time: 2 / (21 + 21 e^b).
    assert abs(steps[0].cum_hazard - 2 / (21 + 21 * math.exp(b))) < 1e-15
    assert abs(sum(cox_snell_residuals(T, steps, w)) - 30) < 1e-11
    # The fitted survival at t = 10 for each arm.
    s0 = survival(steps, 10, 1.0)
    s1 = survival(steps, 10, math.exp(b))
    assert abs(s1 - s0 ** math.exp(b)) < 1e-14
    assert 0.0 < s1 < s0 < 1.0


def test_float_and_fraction_agree_and_input_checks() -> None:
    rng = random.Random(5)
    times, events = random_data(rng, 30, ties=False)
    events[0] = 1
    scores = [rng.uniform(0.2, 5.0) for _ in range(30)]
    a = breslow(times, events, scores)
    b = breslow(times, events, [Fraction(s) for s in scores])
    for u, v in zip(a, b):
        assert abs(u.cum_hazard - float(v.cum_hazard)) < 1e-12 * max(1.0, float(v.cum_hazard))
    for bad in [([], [], []), ([1], [2], [1]), ([1], [1], [0]), ([1, 2], [1], [1, 1])]:
        try:
            breslow(*bad)
        except ValueError:
            pass
        else:
            raise AssertionError("bad input accepted")

History

Norman Breslow proposed the estimate in his discussion of Cox's 1972 paper and published it in Biometrics in 1974. He took the baseline hazard to be constant between event times and maximized the full likelihood, which gave both the baseline estimate and his approximation for tied times. Kalbfleisch and Prentice (1973) gave the discrete product form. Tsiatis (1981) proved that β^\hat\beta and H^0\hat H_0 are jointly asymptotically normal, and Andersen and Gill (1982) gave the counting process proof, in which the Breslow estimator is the Nelson-Aalen estimator with the number at risk replaced by the risk sum.

References

  1. N. E. Breslow, Covariance analysis of censored survival data, Biometrics 30(1), 1974, pp. 89 to 99 (the estimate of the baseline hazard and its derivation as a maximum likelihood estimate)
  2. Anastasios A. Tsiatis, A large sample study of Cox's regression model, Annals of Statistics 9(1), 1981, pp. 93 to 108 (the joint asymptotic normality of the coefficient estimate and the estimated cumulative baseline hazard, with the variance term from estimating beta)
  3. Per Kragh Andersen and Richard D. Gill, Cox's regression model for counting processes, a large sample study, Annals of Statistics 10(4), 1982, pp. 1100 to 1120 (the martingale proof of the weak convergence of the Breslow estimator)
  4. Bradley Efron, The efficiency of Cox's likelihood function for censored data, Journal of the American Statistical Association 72(359), 1977, pp. 557 to 565 (the approximation for tied times, which gives the Efron form of the increment)
  5. Terry M. Therneau and Patricia M. Grambsch, Modeling Survival Data, Extending the Cox Model, Springer, 2000, Chapters 3 and 4 (estimation of the baseline hazard and survival curves after a Cox fit, and residuals)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example