Modelresearch
Fine-Gray model
Also called subdistribution hazard model, proportional subdistribution hazards.
A proportional hazards model for the subdistribution hazard of one cause, so covariate effects act directly on its cumulative incidence.
The Fine-Gray model is a regression model for the cumulative incidence of one cause in a competing risks problem. A Cox model on the cause-specific hazard tells how a covariate changes the rate of cause 1 among event-free subjects, but the risk of cause 1, , also depends on the other causes. Fine and Gray (1999) put the proportional hazards form on the subdistribution hazard of Gray (1988),
so that : a positive raises the cumulative incidence of cause 1 at every time. The model is fitted by a weighted partial likelihood in which subjects who had another cause stay in the risk set, with weights from the censoring distribution.
The machine
The data. For subject we observe , the cause , with for censored, and covariates . Censoring is independent of the event process, and in the basic form also of the covariates.
The subdistribution time. Let if the cause is and otherwise. Then , an improper distribution with mass at infinity, and its hazard is . The risk set of at is
the subjects still event-free and the subjects that already had another cause. The second group is not at risk of anything in reality, but it is at risk in the arithmetic of .
The conditions.
- Proportional subdistribution hazards. with an unspecified , for the cause of interest only. The other causes are left unmodeled.
- Independent censoring, independent of in the basic form. Covariate-dependent censoring needs censoring weights that depend on .
- Independent subjects.
Equivalent form. , with . Proof. Integrate the definition: .
The estimating equation with censoring. Subjects with another cause are not followed after their event, so whether they would have been censored later is unknown. Fine and Gray give them the weight
and weight while , where is the Kaplan-Meier estimate of the censoring distribution, with events leaving before censorings at tied times. The weight is the estimated probability that the subject would still be uncensored at given that it was at , a form of inverse probability weighting. The weighted log partial likelihood is
over the distinct times of cause 1, with events of cause 1 and covariate sum , using the Breslow rule for ties. It is concave by the argument of the partial likelihood page, since the weights do not depend on .
Computation. The reference code splits the weighted risk sums into a backward running sum over and times a forward running sum of over the subjects with another cause before . After one sort, a Newton step costs , as for the Cox model. The baseline is a Breslow-type sum of .
What it counts
- The subdistribution hazard ratio . It is the factor on , and so it orders the cumulative incidence curves: means at every . It is not the ratio of the rates of cause 1 among event-free subjects. That is the cause-specific hazard ratio.
- Predicted risks. for any . This is what the model is for.
- Only one cause. Each cause needs its own model. The models of different causes are not linked, and they cannot all hold, as proved below.
Relation to other models
- Cox model on . Without censoring, every weight is , and the fit is exactly a Cox model in which the subjects with another cause get the time . The tests check this against a direct Cox fit.
- Cause-specific hazards. , where is the all-cause survival. Proof. , and because . The two hazards agree as long as no other cause has happened. Proportional cause-specific hazards for all causes do not give proportional subdistribution hazards in general, and the converse fails too, so the two models are different assumptions, not two fits of one model.
- The Aalen-Johansen estimator. With no covariates, or at , the weighted product-limit estimate of is exactly the Aalen-Johansen estimate. This is proved below.
- Direct binomial and pseudo-observation models. Other models for use other links, such as the logit, with censoring weights or jackknife pseudo-values. The Fine-Gray model is the case of the complementary log-log link, .
Known results in the model
A censoring identity. Let be the all-cause Kaplan-Meier estimate and the Kaplan-Meier estimate of the censoring distribution, with events leaving before censorings at tied times, and let . Then for every time .
Proof. At a distinct observed time with at risk, events and censorings, has the factor and the factor , or if . Their product is , the ratio of the numbers at risk just after and at . The product over all telescopes to . (If , then and both sides are .)
So the Aalen-Johansen increment equals , and : the Aalen-Johansen estimate is an inverse probability of censoring weighted proportion.
At the model reproduces Aalen-Johansen. With all , let be the baseline jump at a time of cause 1. Then , the Aalen-Johansen estimate.
Proof. By the identity, the subjects still at risk contribute , and the subjects with cause before contribute . So
using . The Aalen-Johansen increment at is , so , which is . Multiply over .
The tests check both results in exact fractions on random data with ties.
The models of two causes cannot both hold for all covariates. Suppose cause 1 and cause 2 both follow Fine-Gray models with one covariate and coefficients , with at some . Then as for both , so for large , which is impossible. With a bounded covariate the contradiction may not appear, but the two models remain separate approximations.
Large samples. Under the model and independent censoring, is consistent and asymptotically normal. Its variance is not the inverse of the weighted information, because is estimated and the weighted terms are not martingale increments. Fine and Gray (1999) give a sandwich variance with an extra term for . We cite these results and do not prove them. The reference code reports only the inverse information, which is labeled naive. Use the Fine-Gray variance, or the bootstrap, for inference.
A simulation. The tests use the design of Fine and Gray: a binary , with and , cause 2 given that cause 1 does not happen exponential with rate , , and censoring uniform on . The numbers are measured.
| fit (one data set, : 950 cause 1, 386 cause 2, 664 censored) | coefficient of |
|---|---|
| Fine-Gray, cause 1 (truth 0.5) | 0.452 (naive standard error 0.066) |
| Cox on the cause-specific hazard of cause 1 | 0.298 (standard error 0.066) |
| Cox on the cause-specific hazard of cause 2 | -0.746 |
| Fine-Gray, cause 2 (not a true model in this design) | -0.871 |
Over 40 data sets of 200 subjects (seed 6, as in the tests) the Fine-Gray estimates had mean 0.480 and standard deviation 0.209, so the mean is within one standard error () of 0.5. The cause-specific coefficient of cause 1 is a different quantity: in this design the cause-specific hazards are not proportional, and its value is not an estimate of . The predicted from a fit to 2000 subjects is within 0.04 of the truth.
Checks in code. The tests compare the weighted risk sums with a direct sum, the fit without censoring with a direct Cox fit with the competing times set to infinity, the score and information with numerical derivatives, the censoring identity and the Aalen-Johansen identity in exact fractions, and the simulation above.
Code
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/fine-gray-model/. The authors are listed in prov/YSYJCC.jsonl.
"""Fine-Gray proportional subdistribution hazards model, fitted by weighted Cox Newton steps.
Input: times[i] = y_i, causes[i] = 0 (censored) or k >= 1 (event of cause k)
and covariate rows X[i]. For the cause of interest, a subject with another
cause stays in the risk set after its event time y_i with the weight
G(t-) / G(y_i-), where G is the Kaplan-Meier estimate of the censoring
distribution (censorings at a tied time come after the events). Ties of the
cause of interest use the Breslow rule. The weighted sums of a Newton step
are a backward cumulative sum (subjects still at risk) plus G(t-) times a
forward cumulative sum (subjects with another cause before t), so a step
costs O(n p^2) after one sort, plus O(p^3) for the solve.
"""
import math
from collections.abc import Sequence
from fractions import Fraction
from typing import NamedTuple
def censoring_survival(times: Sequence, causes: Sequence[int]) -> list[tuple]:
"""Kaplan-Meier (u, G(u)) of the censoring time; events at u leave before the censorings at u."""
out, G = [], Fraction(1)
order = sorted(range(len(times)), key=lambda i: times[i])
at_risk, i, n = len(times), 0, len(times)
while i < n:
u, c, d = times[order[i]], 0, 0
while i < n and times[order[i]] == u:
if causes[order[i]] == 0:
c += 1
else:
d += 1
i += 1
if c:
G *= Fraction(at_risk - d - c, at_risk - d)
out.append((u, G))
at_risk -= c + d
return out
def _left_limit(steps: list[tuple], t):
"""G(t-): the value at the last censoring time strictly before t, and 1 before the first."""
value = Fraction(1)
for u, g in steps:
if u >= t:
break
value = g
return value
class Design(NamedTuple):
order: list # subjects by increasing time
event_times: list # distinct times of the cause of interest, increasing
g_event: list # G(t_j-) at each of them
g_subject: list # G(y_i-) for every subject (used for the other causes)
def _design(times, causes, cause):
n = len(times)
if n == 0 or len(causes) != n:
raise ValueError("times and causes must have the same positive length")
if any(not isinstance(c, int) or c < 0 for c in causes):
raise ValueError("causes must be integers >= 0 (0 = censored)")
G = censoring_survival(times, causes)
order = sorted(range(n), key=lambda i: times[i])
ev = sorted(set(times[i] for i in range(n) if causes[i] == cause))
return Design(order, ev, [_left_limit(G, t) for t in ev], [_left_limit(G, times[i]) for i in range(n)])
class Sums(NamedTuple):
loglik: float
score: list
information: list
risk_sums: list # S0_j, the weighted risk set sums at the event times of interest
def weighted_sums(times, causes, X, beta, cause=1, design=None, exact=False) -> Sums:
"""The weighted log partial likelihood, its score and information at beta.
With exact=True and beta = 0 everything is computed in Fractions (the
log-likelihood is then None).
"""
n, p = len(times), len(beta)
des = design or _design(times, causes, cause)
if exact:
if any(b != 0 for b in beta):
raise ValueError("exact arithmetic needs beta = 0")
w = [1] * n
conv = Fraction
else:
eta = [sum(a * b for a, b in zip(X[i], beta)) for i in range(n)]
m = max(eta)
w = [math.exp(e - m) for e in eta]
conv = float
zero = conv(0)
def blank():
return [zero, [zero] * p, [[zero] * p for _ in range(p)]]
def add(acc, i, scale):
ws = w[i] * scale
acc[0] += ws
for a in range(p):
acc[1][a] += ws * X[i][a]
for b in range(p):
acc[2][a][b] += ws * X[i][a] * X[i][b]
# Forward: subjects with another cause before t_j, each scaled by 1 / G(y_i-).
# Backward: subjects with y_i >= t_j.
k = len(des.event_times)
fwd, back = [None] * k, [None] * k
acc, pos = blank(), 0
for j, t in enumerate(des.event_times):
while pos < n and times[des.order[pos]] < t:
i = des.order[pos]
if causes[i] not in (0, cause):
add(acc, i, conv(1) / conv(des.g_subject[i]))
pos += 1
fwd[j] = [acc[0], acc[1][:], [row[:] for row in acc[2]]]
acc, pos = blank(), n - 1
for j in range(k - 1, -1, -1):
t = des.event_times[j]
while pos >= 0 and times[des.order[pos]] >= t:
add(acc, des.order[pos], conv(1))
pos -= 1
back[j] = [acc[0], acc[1][:], [row[:] for row in acc[2]]]
ll = zero if not exact else None
U = [zero] * p
I = [[zero] * p for _ in range(p)]
S0s = []
dead = {}
for i in range(n):
if causes[i] == cause:
dead.setdefault(times[i], []).append(i)
for j, t in enumerate(des.event_times):
g = conv(des.g_event[j])
S0 = back[j][0] + g * fwd[j][0]
S1 = [back[j][1][a] + g * fwd[j][1][a] for a in range(p)]
S2 = [[back[j][2][a][b] + g * fwd[j][2][a][b] for b in range(p)] for a in range(p)]
S0s.append(S0)
d = len(dead[t])
mean = [s / S0 for s in S1]
for i in dead[t]:
for a in range(p):
U[a] += X[i][a] - mean[a]
if not exact:
ll += eta[i] - m - math.log(S0)
for a in range(p):
for b in range(p):
I[a][b] += d * (S2[a][b] / S0 - mean[a] * mean[b])
return Sums(ll, U, I, S0s)
def solve(A, b):
"""Gaussian elimination with partial pivoting; ZeroDivisionError if A is singular."""
p = len(b)
M = [list(map(float, A[r])) + [float(b[r])] for r in range(p)]
for c in range(p):
r = max(range(c, p), key=lambda q: abs(M[q][c]))
if M[r][c] == 0.0:
raise ZeroDivisionError("singular information matrix")
M[c], M[r] = M[r], M[c]
for q in range(c + 1, p):
f = M[q][c] / M[c][c]
for s in range(c, p + 1):
M[q][s] -= f * M[c][s]
x = [0.0] * p
for c in range(p - 1, -1, -1):
x[c] = (M[c][p] - sum(M[c][s] * x[s] for s in range(c + 1, p))) / M[c][c]
return x
class FineGrayResult(NamedTuple):
beta: list
loglik: float
information: list
iterations: int
converged: bool
def fit(times, causes, X, cause=1, beta0=None, tol=1e-10, max_iter=60) -> FineGrayResult:
"""Newton's method with step halving on the weighted log partial likelihood."""
p = len(X[0])
des = _design(times, causes, cause)
if not des.event_times:
raise ValueError("no event of the cause of interest")
beta = list(beta0) if beta0 is not None else [0.0] * p
cur = weighted_sums(times, causes, X, beta, cause, des)
for it in range(1, max_iter + 1):
try:
step = solve(cur.information, cur.score)
except ZeroDivisionError:
return FineGrayResult(beta, cur.loglik, cur.information, it, False)
scale = 1.0
while True:
trial = [b + scale * s for b, s in zip(beta, step)]
new = weighted_sums(times, causes, X, trial, cause, des)
if new.loglik >= cur.loglik - 1e-12 or scale < 1e-8:
break
scale /= 2.0 # step halving
beta, cur = trial, new
if max(abs(scale * s) for s in step) < tol:
return FineGrayResult(beta, cur.loglik, cur.information, it, True)
return FineGrayResult(beta, cur.loglik, cur.information, max_iter, False)
def baseline(times, causes, X, beta, cause=1) -> list[tuple]:
"""Breslow-type jumps of the baseline cumulative subdistribution hazard: (t_j, d_j / S0_j, cumulative).
The weights use exp(x' beta) itself, not the shifted values of weighted_sums.
"""
des = _design(times, causes, cause)
exact = all(b == 0 for b in beta)
sums = weighted_sums(times, causes, X, beta, cause, des, exact=exact)
if not exact:
m = max(sum(a * b for a, b in zip(x, beta)) for x in X)
sums = sums._replace(risk_sums=[s * math.exp(m) for s in sums.risk_sums])
out, H = [], 0
for t, S0 in zip(des.event_times, sums.risk_sums):
d = sum(1 for y, c in zip(times, causes) if c == cause and y == t)
jump = Fraction(d) / S0 if exact else d / S0
H += jump
out.append((t, jump, H))
return out
def predict_cif(steps: list[tuple], x: Sequence[float], beta: Sequence[float], t) -> float:
"""F_k(t | x) = 1 - exp(-Lambda0(t) exp(x' beta))."""
H = 0.0
for u, _, cum in steps:
if u > t:
break
H = float(cum)
return 1.0 - math.exp(-H * math.exp(sum(a * b for a, b in zip(x, beta))))
test_fine_gray_model.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fine-gray-model/. The authors are listed in prov/YSYJCC.jsonl.
import math
import random
from fractions import Fraction
from fine_gray_model import (
_left_limit, baseline, censoring_survival, fit, predict_cif, weighted_sums,
)
def random_data(rng, n, p, censor=0.3, ties=True):
times = [rng.randint(1, 8) if ties else rng.random() for _ in range(n)]
causes = [0 if rng.random() < censor else rng.randint(1, 2) for _ in range(n)]
X = [[rng.choice([0, 1, 2]) if ties else rng.gauss(0, 1) for _ in range(p)] for _ in range(n)]
return times, causes, X
def direct_terms(times, causes, X, beta, cause=1):
"""Weighted risk set sums by a fresh O(n) loop at every event time."""
G = censoring_survival(times, causes)
exact = all(b == 0 for b in beta)
out = []
for t in sorted(set(y for y, c in zip(times, causes) if c == cause)):
S0 = 0
for y, c, x in zip(times, causes, X):
w = 1 if exact else math.exp(sum(a * b for a, b in zip(x, beta)))
if y >= t:
S0 += w
elif c not in (0, cause):
S0 += w * _left_limit(G, t) / _left_limit(G, y)
out.append(S0)
return out
def cox_direct(times, events, X):
"""Breslow-ties Cox fit by Newton with O(n^2) direct sums; infinite times never die."""
p = len(X[0])
beta = [0.0] * p
for _ in range(100):
U = [0.0] * p
I = [[0.0] * p for _ in range(p)]
for t, e, x in zip(times, events, X):
if not e:
continue
S0, S1, S2 = 0.0, [0.0] * p, [[0.0] * p for _ in range(p)]
for y, z in zip(times, X):
if y >= t:
w = math.exp(sum(a * b for a, b in zip(z, beta)))
S0 += w
for a in range(p):
S1[a] += w * z[a]
for b in range(p):
S2[a][b] += w * z[a] * z[b]
for a in range(p):
U[a] += x[a] - S1[a] / S0
for b in range(p):
I[a][b] += S2[a][b] / S0 - S1[a] * S1[b] / S0 ** 2
if p == 1:
step = [U[0] / I[0][0]]
else:
det = I[0][0] * I[1][1] - I[0][1] * I[1][0]
step = [(I[1][1] * U[0] - I[0][1] * U[1]) / det, (I[0][0] * U[1] - I[1][0] * U[0]) / det]
beta = [b + s for b, s in zip(beta, step)]
if max(abs(s) for s in step) < 1e-13:
break
return beta
def aalen_johansen(times, causes, cause=1):
out, S, F = [], Fraction(1), Fraction(0)
for t in sorted(set(y for y, c in zip(times, causes) if c)):
n_j = sum(1 for y in times if y >= t)
d = sum(1 for y, c in zip(times, causes) if y == t and c)
dk = sum(1 for y, c in zip(times, causes) if y == t and c == cause)
F += S * Fraction(dk, n_j)
S *= Fraction(n_j - d, n_j)
out.append((t, F))
return out
def test_risk_sums_match_direct_summation() -> None:
rng = random.Random(1)
for trial in range(30):
times, causes, X = random_data(rng, rng.randint(2, 15), 2)
if 1 not in causes:
continue
exact = weighted_sums(times, causes, X, [0, 0], exact=True)
assert exact.risk_sums == direct_terms(times, causes, X, [0, 0])
beta = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
got = weighted_sums(times, causes, X, beta)
m = max(sum(a * b for a, b in zip(x, beta)) for x in X)
for a, b in zip(got.risk_sums, direct_terms(times, causes, X, beta)):
assert abs(a * math.exp(m) - float(b)) < 1e-10 * float(b)
def test_without_censoring_equals_cox_with_competing_times_at_infinity() -> None:
rng = random.Random(2)
for _ in range(10):
n = rng.randint(15, 40)
times, causes, X = random_data(rng, n, 2, censor=0.0, ties=False)
if causes.count(1) < 3 or causes.count(2) < 1:
continue
r = fit(times, causes, X)
assert r.converged
t2 = [y if c == 1 else math.inf for y, c in zip(times, causes)]
b = cox_direct(t2, [int(c == 1) for c in causes], X)
assert max(abs(u - v) for u, v in zip(r.beta, b)) < 1e-8
def test_score_and_information_are_derivatives() -> None:
rng = random.Random(3)
times, causes, X = random_data(rng, 30, 2, ties=False)
beta = [0.3, -0.4]
s = weighted_sums(times, causes, X, beta)
h = 1e-6
for a in range(2):
up = beta[:]
up[a] += h
dn = beta[:]
dn[a] -= h
su, sd = weighted_sums(times, causes, X, up), weighted_sums(times, causes, X, dn)
assert abs((su.loglik - sd.loglik) / (2 * h) - s.score[a]) < 1e-6
for b in range(2):
assert abs(-(su.score[b] - sd.score[b]) / (2 * h) - s.information[a][b]) < 1e-5
r = fit(times, causes, X)
assert r.converged and max(abs(u) for u in weighted_sums(times, causes, X, r.beta).score) < 1e-9
def test_censoring_km_factorizes_the_risk_set() -> None:
# n_j / n = S(t_j-) G(t_j-) exactly, where S is the all-cause Kaplan-Meier estimate.
rng = random.Random(4)
for _ in range(40):
times, causes, _ = random_data(rng, rng.randint(1, 20), 1, censor=0.4)
n = len(times)
G = censoring_survival(times, causes)
S = Fraction(1)
for t in sorted(set(times)):
n_t = sum(1 for y in times if y >= t)
assert Fraction(n_t, n) == S * _left_limit(G, t)
d = sum(1 for y, c in zip(times, causes) if y == t and c)
S *= Fraction(n_t - d, n_t)
def test_weighted_product_limit_at_beta_zero_is_aalen_johansen() -> None:
rng = random.Random(5)
for _ in range(40):
times, causes, X = random_data(rng, rng.randint(1, 20), 1, censor=0.35)
if 1 not in causes:
continue
steps = baseline(times, causes, X, [0])
aj = dict(aalen_johansen(times, causes))
prod = Fraction(1)
for t, jump, _ in steps:
prod *= 1 - jump
assert 1 - prod == aj[t]
def simulate(rng, n, b1, b2, p):
"""The design of Fine and Gray (1999): F_1(t | x) = 1 - (1 - p (1 - e^(-t)))^exp(x b1)."""
times, causes, X = [], [], []
for _ in range(n):
x = rng.choice([0.0, 1.0])
r1 = math.exp(b1 * x)
u = rng.random()
if u < 1 - (1 - p) ** r1:
t = -math.log(1 - (1 - (1 - u) ** (1 / r1)) / p)
c = 1
else:
t = rng.expovariate(math.exp(b2 * x))
c = 2
cens = rng.uniform(0, 3)
if cens < t:
t, c = cens, 0
times.append(t)
causes.append(c)
X.append([x])
return times, causes, X
def test_simulation_recovers_beta() -> None:
rng = random.Random(6)
b1, b2, p = 0.5, -0.5, 0.6
est = []
for _ in range(40):
times, causes, X = simulate(rng, 200, b1, b2, p)
est.append(fit(times, causes, X).beta[0])
mean = sum(est) / len(est)
sd = math.sqrt(sum((e - mean) ** 2 for e in est) / (len(est) - 1))
assert abs(mean - b1) < 4 * sd / math.sqrt(len(est)) + 0.02
# The predicted cumulative incidence at t = 1 for x = 1 against the truth.
times, causes, X = simulate(rng, 2000, b1, b2, p)
r = fit(times, causes, X)
steps = baseline(times, causes, X, r.beta)
true = 1 - (1 - p * (1 - math.exp(-1.0))) ** math.exp(b1)
assert abs(predict_cif(steps, [1.0], r.beta, 1.0) - true) < 0.04
References
- Jason P. Fine and Robert J. Gray, A proportional hazards model for the subdistribution of a competing risk, Journal of the American Statistical Association 94(446), 1999, pp. 496 to 509 (the model, the risk set with inverse probability of censoring weights, the estimating equation, its asymptotic normality and the robust variance, and the simulation design used here)
- Robert J. Gray, A class of K-sample tests for comparing the cumulative incidence of a competing risk, Annals of Statistics 16(3), 1988, pp. 1141 to 1154 (the subdistribution hazard and its risk set, and the K-sample test)
- H. Putter, M. Fiocco and R. B. Geskus, Tutorial in biostatistics, competing risks and multi-state models, Statistics in Medicine 26(11), 2007, pp. 2389 to 2430 (the interpretation of subdistribution hazard ratios next to cause-specific hazard ratios)
- John D. Kalbfleisch and Ross L. Prentice, The Statistical Analysis of Failure Time Data, 2nd edition, Wiley, 2002, Chapter 8 (competing risks, cause-specific hazards and cumulative incidence)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag YSYJCC Edit this page History Report an error Markdown