File size: 2,341 Bytes
232c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
Cox partial likelihood loss (Breslow approximation for ties).

Usage:
    risk = model(x)                      # shape (B,), higher = higher risk
    loss = cox_ph_loss(risk, time, event)

Notes:
- Needs a reasonably large batch (16-32+) so the risk set at each event
  time actually contains multiple samples. Tiny batches (2-4) make this
  loss nearly meaningless.
- `time` should be a float tensor, `event` a 0/1 float or long tensor.
- This computes loss over the WHOLE batch as one risk set ordering, which
  is the standard DeepSurv-style approximation (not exact per-stratum Cox,
  but works fine in practice for this use case).
"""

import torch


def cox_ph_loss(risk: torch.Tensor, time: torch.Tensor, event: torch.Tensor, eps: float = 1e-7):
    """
    risk:  (B,) raw model output (log-risk score), unbounded
    time:  (B,) survival/censoring time
    event: (B,) 1 if event observed, 0 if censored
    """
    # sort by descending time so that risk set for sample i is samples 0..i
    order = torch.argsort(time, descending=True)
    risk = risk[order]
    event = event[order].float()

    # log-sum-exp of risk over the risk set (cumulative from the top since sorted desc)
    log_cumsum = torch.logcumsumexp(risk, dim=0)

    # only events contribute to the likelihood (censored samples just stay in risk sets)
    diff = risk - log_cumsum
    loss = -(diff * event).sum() / (event.sum() + eps)
    return loss


def concordance_index(risk: torch.Tensor, time: torch.Tensor, event: torch.Tensor) -> float:
    """
    Simple O(n^2) C-index, fine for val-set sizes in the hundreds.
    For large datasets, swap for lifelines.utils.concordance_index.
    """
    risk = risk.detach().cpu().numpy()
    time = time.detach().cpu().numpy()
    event = event.detach().cpu().numpy()

    n = len(time)
    concordant = 0
    permissible = 0
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            # pair is comparable only if i has an earlier event time than j
            if time[i] < time[j] and event[i] == 1:
                permissible += 1
                if risk[i] > risk[j]:
                    concordant += 1
                elif risk[i] == risk[j]:
                    concordant += 0.5
    return concordant / permissible if permissible > 0 else float("nan")