| from __future__ import annotations |
|
|
| import torch |
| from torch import nn |
|
|
|
|
| def patient_burden(lesion_probs: torch.Tensor, patient_index: torch.Tensor | None = None) -> torch.Tensor: |
| """Compute malignant burden as 1 - prod_l(1 - p_l). |
| |
| If ``patient_index`` is omitted, each row is treated as an independent |
| patient. Otherwise rows with the same index are aggregated. |
| """ |
|
|
| lesion_probs = lesion_probs.view(-1).clamp(0.0, 1.0) |
| if patient_index is None: |
| return lesion_probs |
| burdens = [] |
| for idx in torch.unique(patient_index): |
| probs = lesion_probs[patient_index == idx] |
| burdens.append(1.0 - torch.prod(1.0 - probs)) |
| return torch.stack(burdens) |
|
|
|
|
| class DiscreteTimeSurvivalHead(nn.Module): |
| def __init__(self, in_dim: int, num_bins: int = 12) -> None: |
| super().__init__() |
| self.num_bins = num_bins |
| self.net = nn.Sequential( |
| nn.Linear(in_dim, in_dim), |
| nn.SiLU(inplace=True), |
| nn.Linear(in_dim, num_bins), |
| ) |
|
|
| def forward(self, features: torch.Tensor) -> torch.Tensor: |
| if self.num_bins <= 0: |
| raise ValueError("num_bins must be positive for survival prediction") |
| return self.net(features) |
|
|
|
|