unknownBrain's picture
Backup full source code, Step 1 results CSVs, logs, and README
232c308 verified
Raw History Blame Contribute Delete
2.34 kB
"""
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")