From 035e53bd6f0ab20e5f695156f378183f895c9a37 Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 1/6] Add DeepCoxMixtures model and SUPPORT2 DCM-protocol survival task Co-Authored-By: Claude Opus 5.5 --- docs/api/models.rst | 1 + .../pyhealth.models.deep_cox_mixtures.rst | 80 ++ docs/api/tasks.rst | 1 + ...ks.survival_time_to_event_support2_dcm.rst | 27 + pyhealth/models/__init__.py | 1 + pyhealth/models/deep_cox_mixtures.py | 898 ++++++++++++++++++ pyhealth/tasks/__init__.py | 3 + .../survival_time_to_event_support2_dcm.py | 187 ++++ tests/core/test_deep_cox_mixtures.py | 388 ++++++++ ...est_survival_time_to_event_support2_dcm.py | 133 +++ 10 files changed, 1719 insertions(+) create mode 100644 docs/api/models/pyhealth.models.deep_cox_mixtures.rst create mode 100644 docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rst create mode 100644 pyhealth/models/deep_cox_mixtures.py create mode 100644 pyhealth/tasks/survival_time_to_event_support2_dcm.py create mode 100644 tests/core/test_deep_cox_mixtures.py create mode 100644 tests/core/test_survival_time_to_event_support2_dcm.py diff --git a/docs/api/models.rst b/docs/api/models.rst index 917d185afe..d05348b86a 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -361,6 +361,7 @@ API Reference models/pyhealth.models.XGBoostModel models/pyhealth.models.survival_mdn models/pyhealth.models.personalized_survival_moe + models/pyhealth.models.deep_cox_mixtures models/pyhealth.models.cet models/pyhealth.models.TrajSurv models/pyhealth.models.KnowRare diff --git a/docs/api/models/pyhealth.models.deep_cox_mixtures.rst b/docs/api/models/pyhealth.models.deep_cox_mixtures.rst new file mode 100644 index 0000000000..1a7f6ce1de --- /dev/null +++ b/docs/api/models/pyhealth.models.deep_cox_mixtures.rst @@ -0,0 +1,80 @@ +pyhealth.models.DeepCoxMixtures +=============================== + +Overview +-------- + +Deep Cox Mixtures (DCM) for right-censored survival regression, following +`Nagpal et al., MLHC 2021 `_. +A patient's survival curve is a mixture of ``K`` Cox models, + +.. math:: + + S(t \mid x) = \sum_{k=1}^{K} \pi_k(x)\, S_{0k}(t)^{\exp f_k(x)}, + +where a shared MLP encoder feeds a gating head (latent-group probabilities +:math:`\pi_k`) and a head of per-group log hazard ratios :math:`f_k`, and each +group has its own Breslow baseline survival :math:`S_{0k}`. Proportional +hazards hold within a group but not across the mixture, so the model can +represent patient groups whose survival curves cross. ``num_components=1`` +gives a neural Cox model (DeepSurv-style) with a Breslow baseline, and +``hidden_dims=()`` gives the paper's linear "Cox Mixture". + +Training +-------- + +:meth:`~pyhealth.models.DeepCoxMixtures.fit` runs the paper's approximate +Monte Carlo EM. For each mini-batch it computes the posterior group +responsibilities from the observed time and censoring status (E-step), samples +hard assignments from them, takes one Adam step on the gate log-likelihood plus +one Cox partial likelihood per sampled group (Breslow ties, mini-batch risk +sets), and then refits every group's Breslow baseline on the full training set. +With validation data it stops early on the validation negative log-likelihood +and restores the best weights and baselines. The generic +:class:`~pyhealth.trainer.Trainer` is not used because the baselines have to be +refit between gradient steps. + +Each group's cumulative baseline hazard is interpolated linearly between its +own event times (a piecewise-constant hazard) and held constant after its last +event time, so survival curves stay in [0, 1], never increase, and event +densities in the E-step are nonnegative. The paper smooths the Breslow curve +with a cubic spline instead. + +Inputs and outputs +------------------ + +Features must be one dense, finite vector per patient (impute and scale them on +training patients first). Labels are ``duration`` (strictly positive) and +``event`` (1 for an event, 0 for censoring); the keys are configurable with +``feature_key``, ``duration_key`` and ``event_key``. ``forward`` returns +``log_risk`` and ``mixture_weights`` (both ``[batch, K]``), survival at +``time_grid`` as ``survival``/``y_prob`` once baselines are fitted, and, with +labels, the EM ``loss``, the responsibilities ``posterior`` and ``y_true``. +:meth:`~pyhealth.models.DeepCoxMixtures.predict_survival` gives ``[N, T]`` +survival at any times, and +:meth:`~pyhealth.models.DeepCoxMixtures.predict_latent` the ``[N, K]`` group +probabilities. Fitted baselines are part of ``state_dict()``. ``mode`` is +``None``; score predictions with censoring-aware survival metrics. + +Example and ablation +-------------------- + +``examples/support2_survival_deep_cox_mixtures.py`` runs SUPPORT2 through +:class:`~pyhealth.datasets.Support2Dataset` and +:class:`~pyhealth.tasks.SurvivalTimeToEventSupport2DCM`, trains DCM with the +paper's settings, compares ``K = 1`` with mixtures of several sizes and +reports calibration and discrimination at the paper's horizons. Use +``--synthetic`` for a quick run without data. Setup, commands and measured +results are documented in the script. + +API +--- + +.. autoclass:: pyhealth.models.DeepCoxMixtures + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.models.deep_cox_mixtures.cox_partial_log_likelihood + +.. autofunction:: pyhealth.models.deep_cox_mixtures.breslow_cumulative_hazard diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 00149a96e0..0e0a0fae3d 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -324,5 +324,6 @@ Available Tasks Value Set Completion (VSAC) Value Set Pair Classification (VSAC) Time-to-event survival (GBSG and SUPPORT) + Time-to-event survival (SUPPORT2, Deep Cox Mixtures protocol) TCGA RNA-seq Survival Prediction Query-Focused EHR Summarization (MIMIC-III) diff --git a/docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rst b/docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rst new file mode 100644 index 0000000000..c73091e099 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rst @@ -0,0 +1,27 @@ +pyhealth.tasks.SurvivalTimeToEventSupport2DCM +============================================= + +Time to death on SUPPORT2 with the covariates of the Deep Cox Mixtures paper +(`Nagpal et al., MLHC 2021 `_). +Use it with :class:`~pyhealth.datasets.Support2Dataset`. + +All 9,105 patients are kept. Each sample has ``features: [44]``: 18 numeric +covariates followed by one-hot codes (every level kept) of sex, disease group, +disease class, income, race and cancer status, named by +``SUPPORT2_DCM_FEATURES``. A missing numeric value is NaN and a missing +category is all zeros, as in the paper's released preprocessing. Labels are +``duration: [d.time]`` in days and ``event: [death]``. Each sample also carries +``race`` (the recorded race or ``"missing"``) for subgroup evaluation; the +paper's minority group is every patient whose race is not ``"white"``. + +The samples are not imputed. As in the paper, impute missing values with the +mean and standardize every column, fitting both on training patients only, +before training a model such as :class:`~pyhealth.models.DeepCoxMixtures`. + +This differs from :class:`~pyhealth.tasks.SurvivalTimeToEventSupport2`, which +keeps the 8,873-patient complete-case DeepSurv cohort with 14 covariates +encoded as 27 features. + +.. autoclass:: pyhealth.tasks.SurvivalTimeToEventSupport2DCM + :members: + :show-inheritance: diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 703b5c9fa8..7abd8603eb 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -128,6 +128,7 @@ from .generators.tardiff import TarDiff as TarDiff from .survival_mdn import SurvivalMDN as SurvivalMDN from .personalized_survival_moe import PersonalizedSurvivalMoE as PersonalizedSurvivalMoE +from .deep_cox_mixtures import DeepCoxMixtures as DeepCoxMixtures from .cet import CET as CET from .trajsurv import TrajSurv as TrajSurv from .knowrare import KnowRare as KnowRare diff --git a/pyhealth/models/deep_cox_mixtures.py b/pyhealth/models/deep_cox_mixtures.py new file mode 100644 index 0000000000..bc0b6f4437 --- /dev/null +++ b/pyhealth/models/deep_cox_mixtures.py @@ -0,0 +1,898 @@ +"""Deep Cox Mixtures for survival regression. + +Contributor: (NetID: liu323) + +Paper: Chirag Nagpal, Steve Yadlowsky, Negar Rostamzadeh and Katherine Heller. +Deep Cox Mixtures for Survival Regression. Machine Learning for Healthcare +(MLHC), PMLR 149, 2021. https://proceedings.mlr.press/v149/nagpal21a.html + +Deep Cox Mixtures (DCM) model the survival function of a patient as a mixture +of K Cox proportional-hazards models. A shared neural encoder feeds a gating +head, which gives the probability of each latent group, and a head with one +log hazard ratio per group. Each group has its own nonparametric (Breslow) +baseline hazard. Training uses the paper's approximate Monte Carlo EM: an +E-step computes posterior group responsibilities from the observed time and +censoring status, hard assignments are sampled from them, a gradient step +maximizes the gate log-likelihood plus one Cox partial likelihood per group, +and the per-group Breslow baselines are re-estimated on the full training set. + +This is an independent PyTorch implementation written from the paper. The +authors' TensorFlow code (Apache-2.0) and the PyTorch DCM in auton-survival +(MIT) were consulted to check update order and defaults; no code was copied. +""" + +import copy +import math +from collections.abc import Mapping, Sequence +from typing import Any + +import torch +from torch import Tensor, nn +from torch.nn import functional as F + +from pyhealth.datasets import SampleDataset +from pyhealth.models.base_model import BaseModel +from pyhealth.processors import LabelProcessor + +_ACTIVATIONS: dict[str, type[nn.Module]] = { + "selu": nn.SELU, + "relu": nn.ReLU, + "relu6": nn.ReLU6, + "tanh": nn.Tanh, +} +# Smallest per-group likelihood used in the E-step. The reference code floors +# probabilities at the same value so that one group with zero density (for +# example an event after that group's last event time) cannot produce NaNs. +_LIKELIHOOD_FLOOR = 1e-10 + + +def _as_vector(value: Any, name: str, device: torch.device) -> Tensor: + """Convert a label field of shape (n,) or (n, 1) to a float64 vector.""" + if isinstance(value, tuple): + value = value[0] + tensor = torch.as_tensor(value, device=device, dtype=torch.float64) + if tensor.ndim == 2 and tensor.shape[1] == 1: + tensor = tensor[:, 0] + if tensor.ndim != 1: + raise ValueError(f"{name} must have shape (batch,) or (batch, 1)") + return tensor + + +def _check_labels(duration: Tensor, event: Tensor) -> None: + """Validate right-censored labels.""" + if duration.shape != event.shape: + raise ValueError("duration and event must have the same number of rows") + if not torch.isfinite(duration).all() or (duration <= 0).any(): + raise ValueError("duration must be finite and strictly positive") + if not torch.all((event == 0) | (event == 1)): + raise ValueError("event must contain only 0 (censored) or 1 (event)") + + +def cox_partial_log_likelihood( + log_risk: Tensor, duration: Tensor, event: Tensor +) -> Tensor: + """Cox partial log-likelihood with Breslow's handling of tied times. + + For each observed event ``i`` the risk set holds every patient with + ``duration >= duration[i]``, so tied event times share one denominator. + + Args: + log_risk: Log hazard ratios, shape ``(n,)``. + duration: Event or censoring times, shape ``(n,)``. + event: 1 for an observed event, 0 for censoring, shape ``(n,)``. + + Returns: + The summed partial log-likelihood (a scalar, 0 if there are no + events). It is differentiable with respect to ``log_risk``. + + Examples: + >>> import torch + >>> ll = cox_partial_log_likelihood( + ... torch.zeros(3), torch.tensor([1.0, 2.0, 3.0]), + ... torch.tensor([1.0, 1.0, 0.0]), + ... ) + >>> round(float(ll), 4) # -(log 3 + log 2) + -1.7918 + """ + if log_risk.numel() == 0: + return log_risk.sum() + order = torch.argsort(duration, descending=True, stable=True) + sorted_time = duration[order] + sorted_risk = log_risk[order] + sorted_event = event[order].to(log_risk.dtype) + log_cumulative = torch.logcumsumexp(sorted_risk, dim=0) + # In descending time order the risk set of a tie group ends at its last + # member, so every member of the group uses that position's denominator. + _, inverse, counts = torch.unique_consecutive( + sorted_time, return_inverse=True, return_counts=True + ) + group_end = torch.cumsum(counts, dim=0) - 1 + log_denominator = log_cumulative[group_end[inverse]] + return ((sorted_risk - log_denominator) * sorted_event).sum() + + +def breslow_cumulative_hazard( + log_risk: Tensor, duration: Tensor, event: Tensor +) -> tuple[Tensor, Tensor]: + """Breslow estimate of the cumulative baseline hazard. + + ``H0(tau_j) = sum_{tau_m <= tau_j} d_m / sum_{l: t_l >= tau_m} exp(f_l)``, + where ``tau`` are the distinct event times and ``d`` their event counts. + + Args: + log_risk: Log hazard ratios, shape ``(n,)``. + duration: Event or censoring times, shape ``(n,)``. + event: 1 for an observed event, 0 for censoring, shape ``(n,)``. + + Returns: + ``(event_times, cumulative_hazard)``, both of shape ``(m,)`` with + ``m`` distinct event times in increasing order. Both are empty when + there is no event. + + Examples: + >>> import torch + >>> times, hazard = breslow_cumulative_hazard( + ... torch.zeros(3), torch.tensor([1.0, 2.0, 3.0]), + ... torch.tensor([1.0, 1.0, 0.0]), + ... ) + >>> times.tolist(), [round(h, 4) for h in hazard.tolist()] + ([1.0, 2.0], [0.3333, 0.8333]) + """ + log_risk = log_risk.detach().to(torch.float64) + duration = duration.detach().to(torch.float64) + observed = event.detach() > 0.5 + if not observed.any(): + empty = duration.new_zeros(0) + return empty, empty + event_times, deaths = torch.unique(duration[observed], return_counts=True) + order = torch.argsort(duration) + sorted_time = duration[order] + # Sum of exp(f) over everyone at or after each position, computed in log + # space so that large hazard ratios cannot overflow. + log_suffix = torch.logcumsumexp(log_risk[order].flip(0), dim=0).flip(0) + first_at_risk = torch.searchsorted(sorted_time, event_times, right=False) + increments = deaths.to(torch.float64) * torch.exp(-log_suffix[first_at_risk]) + return event_times, torch.cumsum(increments, dim=0) + + +class DeepCoxMixtures(BaseModel): + """Deep Cox Mixtures (Nagpal et al., MLHC 2021) for right-censored data. + + The survival function of a patient with features ``x`` is + + ``S(t | x) = sum_k pi_k(x) * S_0k(t) ** exp(f_k(x))``, + + where ``pi(x) = softmax(g(phi(x)))`` are latent-group probabilities, + ``f_k(phi(x))`` is group ``k``'s log hazard ratio, ``phi`` is an MLP + encoder and ``S_0k`` is group ``k``'s Breslow baseline survival. Within a + group the proportional hazards assumption holds; the mixture does not. + + Train with :meth:`fit`, which runs the paper's Monte Carlo EM: for every + mini-batch it computes the posterior group responsibilities ``gamma`` + (E-step), samples hard assignments ``zeta ~ Categorical(gamma)``, takes a + gradient step on ``sum gamma log pi + sum_k log PL_k`` with one Cox + partial likelihood per sampled group, and then re-estimates every + group's Breslow baseline on the full training set using hard assignments + sampled from the full-data posterior. Partial likelihoods use mini-batch + risk sets, as in the paper. The generic :class:`~pyhealth.trainer.Trainer` + is not used because the baselines must be refit between gradient steps. + + Baseline survival between event times: each group's cumulative baseline + hazard is interpolated linearly between its own distinct event times + (a piecewise-constant hazard), starting from 0 at time 0, and held + constant after the group's last event time. This gives survival curves in + [0, 1] that never increase and nonnegative event densities for the + E-step. The paper instead smooths the Breslow survival curve with a cubic + spline, and the authors' later PyTorch release with a linear smoothing + spline; neither is guaranteed monotone. + + Survival outputs have no label processor, so ``mode`` is ``None``. + Features must be dense and finite: impute and scale them first, using + training patients only. + + Args: + dataset: Optional fitted ``SampleDataset`` with a dense feature vector + and ``duration``/``event`` tensor outputs. Use ``None`` together + with ``input_dim`` to build the model without a dataset. + input_dim: Width of the feature vector. Inferred from the first + sample of ``dataset`` when omitted. + num_components: Number of latent groups ``K``. ``K = 1`` is a neural + Cox model (DeepSurv-style) with a Breslow baseline. + hidden_dims: Widths of the encoder's hidden layers. An empty + sequence gives linear gate and risk functions of the raw + features (the paper's "Cox Mixture"). Default ``(100, 100)``. + activation: Encoder activation: ``"selu"`` (the authors' code), + ``"relu"``, ``"relu6"`` or ``"tanh"``. + use_bias: Whether the encoder layers have bias terms. The authors' + code uses none. The risk head never has one, since a constant is + absorbed by the baseline hazard. + log_risk_bound: Log hazard ratios are clamped to + ``[-log_risk_bound, log_risk_bound]`` to keep ``exp(f)`` finite, + as in auton-survival (default 10). ``None`` disables the clamp. + feature_key: Input field with the dense feature vector. + duration_key: Output field with strictly positive times. + event_key: Output field with 1 for an event and 0 for censoring. + time_grid: Times at which ``forward`` returns ``y_prob`` (survival + probabilities) once baselines are fitted. Optional. + + Examples: + >>> import torch + >>> from pyhealth.models import DeepCoxMixtures + >>> torch.manual_seed(0) # doctest: +ELLIPSIS + + >>> x = torch.randn(40, 4) + >>> time = torch.rand(40) * 10 + 0.1 + >>> event = (torch.rand(40) < 0.7).float() + >>> model = DeepCoxMixtures(None, input_dim=4, num_components=2, + ... hidden_dims=(8,)) + >>> history = model.fit((x, time, event), epochs=2, batch_size=16, + ... seed=0) + >>> model.predict_survival(x[:3], [1.0, 5.0]).shape + torch.Size([3, 2]) + >>> bool(torch.allclose(model.predict_latent(x[:3]).sum(dim=1), + ... torch.ones(3))) + True + """ + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """No label processors: survival outputs are scored by the model.""" + return {} + + def __init__( + self, + dataset: SampleDataset | None = None, + input_dim: int | None = None, + num_components: int = 3, + hidden_dims: Sequence[int] = (100, 100), + activation: str = "selu", + use_bias: bool = False, + log_risk_bound: float | None = 10.0, + feature_key: str = "features", + duration_key: str = "duration", + event_key: str = "event", + time_grid: Sequence[float] | Tensor | None = None, + ) -> None: + super().__init__(dataset) + self.feature_key = feature_key + self.duration_key = duration_key + self.event_key = event_key + if dataset is not None: + if feature_key not in dataset.input_schema: + raise ValueError( + f"feature_key {feature_key!r} is not in dataset.input_schema" + ) + for key in (duration_key, event_key): + if key not in dataset.output_schema: + raise ValueError( + f"output key {key!r} is not in dataset.output_schema" + ) + if input_dim is None: + input_dim = self._infer_input_dim(dataset, feature_key) + if input_dim is None: + raise ValueError("input_dim is required when dataset is None") + for name, value in (("input_dim", input_dim), ("num_components", + num_components)): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer") + hidden_dims = tuple(hidden_dims) + if any( + isinstance(h, bool) or not isinstance(h, int) or h < 1 + for h in hidden_dims + ): + raise ValueError("hidden_dims must contain positive integers") + if activation not in _ACTIVATIONS: + raise ValueError(f"activation must be one of {sorted(_ACTIVATIONS)}") + if log_risk_bound is not None and not ( + math.isfinite(log_risk_bound) and log_risk_bound > 0 + ): + raise ValueError("log_risk_bound must be positive and finite, or None") + + self.input_dim = input_dim + self.num_components = num_components + self.hidden_dims = hidden_dims + self.activation = activation + self.log_risk_bound = log_risk_bound + + layers: list[nn.Module] = [] + width = input_dim + for hidden in hidden_dims: + layers += [nn.Linear(width, hidden, bias=use_bias), + _ACTIVATIONS[activation]()] + width = hidden + self.encoder = nn.Sequential(*layers) + self.gate = nn.Linear(width, num_components, bias=False) + self.risk = nn.Linear(width, num_components, bias=False) + + if time_grid is None: + grid = torch.zeros(0) + else: + grid = torch.as_tensor(time_grid, dtype=torch.float32).reshape(-1) + if not torch.isfinite(grid).all() or (grid < 0).any(): + raise ValueError("time_grid must be finite and non-negative") + # Not a persistent buffer: saved through get_extra_state so a model + # built with another (or no) grid can load the checkpoint. + self.register_buffer("time_grid", grid, persistent=False) + # Baselines: per-group knots (0, then the group's event times, then + # +inf padding) and the cumulative hazard there, shape (K, M). + self._knots: Tensor | None = None + self._cumulative_hazard: Tensor | None = None + + # ------------------------------------------------------------------ utils + @staticmethod + def _infer_input_dim(dataset: SampleDataset, feature_key: str) -> int: + """Read the feature width from the first processed sample.""" + value = dataset[0][feature_key] + if isinstance(value, tuple): + value = value[0] + tensor = torch.as_tensor(value) + if tensor.ndim != 1: + raise ValueError( + "DeepCoxMixtures expects a 1D dense feature vector per sample" + ) + return int(tensor.shape[0]) + + def _features(self, value: Any) -> Tensor: + """Validate and move a feature matrix to the model's device.""" + if isinstance(value, tuple): + value = value[0] + x = torch.as_tensor(value, device=self.device, dtype=self.gate.weight.dtype) + if x.ndim != 2 or x.shape[1] != self.input_dim: + raise ValueError( + f"features must have shape (batch, {self.input_dim}), " + f"got {tuple(x.shape)}" + ) + if not torch.isfinite(x).all(): + raise ValueError("features must be finite; impute missing values first") + return x + + def _network(self, x: Tensor) -> tuple[Tensor, Tensor]: + """Return log gate probabilities and log hazard ratios, both (n, K).""" + hidden = self.encoder(x) + log_gate = F.log_softmax(self.gate(hidden), dim=-1) + log_risk = self.risk(hidden) + if self.log_risk_bound is not None: + log_risk = log_risk.clamp(-self.log_risk_bound, self.log_risk_bound) + return log_gate, log_risk + + @property + def is_fitted(self) -> bool: + """Whether the per-group baseline hazards have been estimated.""" + return self._knots is not None + + def _require_fitted(self) -> None: + if not self.is_fitted: + raise RuntimeError( + "Baseline hazards are not fitted; call fit() or fit_baselines()" + ) + + # -------------------------------------------------------- baseline state + def get_extra_state(self) -> dict[str, Tensor | None]: + """Store baselines and ``time_grid`` in ``state_dict``. + + Returns: + The fitted baseline knots and cumulative hazards (``None`` before + fitting) and the time grid. + """ + return { + "knots": self._knots, + "cumulative_hazard": self._cumulative_hazard, + "time_grid": self.time_grid, + } + + def set_extra_state(self, state: Mapping[str, Tensor | None]) -> None: + """Restore baselines saved by :meth:`get_extra_state`. + + Args: + state: Output of :meth:`get_extra_state`. + + Raises: + ValueError: If the saved baselines are incomplete or were fit for + a different number of components. + """ + knots, hazard = state.get("knots"), state.get("cumulative_hazard") + if (knots is None) != (hazard is None): + raise ValueError("Saved baseline state is incomplete") + if knots is not None: + knots = knots.to(device=self.device, dtype=torch.float64) + hazard = hazard.to(device=self.device, dtype=torch.float64) + if knots.shape != hazard.shape or knots.shape[0] != self.num_components: + raise ValueError("Saved baselines do not match num_components") + self._knots, self._cumulative_hazard = knots, hazard + if state.get("time_grid") is not None: + self.time_grid = state["time_grid"].to(self.device) + + def _apply(self, fn: Any, recurse: bool = True) -> "DeepCoxMixtures": + """Move the baseline tensors along with the module (``.to()`` etc.).""" + module = super()._apply(fn, recurse) + if self._knots is not None: + device = self._dummy_param.device + self._knots = self._knots.to(device) + self._cumulative_hazard = self._cumulative_hazard.to(device) + return module + + def _baseline_at(self, times: Tensor) -> tuple[Tensor, Tensor]: + """Interpolated cumulative baseline hazard and hazard rate. + + Args: + times: Query times, shape ``(q,)``. + + Returns: + ``(cumulative_hazard, hazard)``, each of shape ``(q, K)``. + """ + knots, hazard = self._knots, self._cumulative_hazard + k, m = knots.shape + query = times.to(knots).reshape(1, -1).expand(k, -1).contiguous() + upper = torch.searchsorted(knots, query, right=False).clamp(1, m - 1) + lower = upper - 1 + t_lo, t_hi = knots.gather(1, lower), knots.gather(1, upper) + h_lo, h_hi = hazard.gather(1, lower), hazard.gather(1, upper) + inside = torch.isfinite(t_hi) + width = torch.where(inside, t_hi - t_lo, torch.ones_like(t_lo)) + slope = torch.where(inside, (h_hi - h_lo) / width, torch.zeros_like(t_lo)) + fraction = ((query - t_lo) / width).clamp(0.0, 1.0) + value = torch.where(inside, h_lo + fraction * (h_hi - h_lo), h_lo) + return value.T, slope.T + + def _set_baselines(self, curves: list[tuple[Tensor, Tensor]]) -> None: + """Pack per-group ``(event_times, cumulative_hazard)`` into (K, M).""" + width = 2 + max(len(times) for times, _ in curves) + knots = torch.full( + (self.num_components, width), math.inf, dtype=torch.float64, + device=self.device, + ) + hazard = torch.zeros_like(knots) + knots[:, 0] = 0.0 + for k, (times, cumulative) in enumerate(curves): + m = len(times) + knots[k, 1:m + 1] = times + hazard[k, 1:m + 1] = cumulative + hazard[k, m + 1:] = cumulative[-1] if m else 0.0 + self._knots, self._cumulative_hazard = knots, hazard + + # ------------------------------------------------------------- EM pieces + def _component_log_likelihood( + self, log_risk: Tensor, duration: Tensor, event: Tensor + ) -> Tensor: + """Per-group log-likelihood of each observation, shape (n, K). + + Censored rows use ``log S_k(t | x)``; events use the log density + ``f_k + log h_0k(t) + log S_k(t | x)``. Values are floored at + ``log(1e-10)``. + """ + cumulative, rate = self._baseline_at(duration) + log_risk = log_risk.to(torch.float64) + log_survival = -cumulative * torch.exp(log_risk) + with torch.no_grad(): + log_rate = torch.log(rate) + log_density = log_risk + log_rate + log_survival + observed = event.to(torch.bool).unsqueeze(1) + log_likelihood = torch.where(observed, log_density, log_survival) + return log_likelihood.clamp_min(math.log(_LIKELIHOOD_FLOOR)) + + def _log_posterior( + self, log_gate: Tensor, log_risk: Tensor, duration: Tensor, event: Tensor + ) -> Tensor: + """E-step: log responsibilities ``log gamma``, shape (n, K). + + Before any baseline exists (the first mini-batch), the gate + probabilities are used, as in the authors' code. + """ + log_gate = log_gate.detach().to(torch.float64) + if not self.is_fitted: + return log_gate + log_likelihood = self._component_log_likelihood( + log_risk.detach(), duration, event + ) + return torch.log_softmax(log_gate + log_likelihood, dim=-1) + + @staticmethod + def _sample_assignment( + log_posterior: Tensor, generator: torch.Generator | None + ) -> Tensor: + """Draw ``zeta_i ~ Categorical(gamma_i)``; returns (n,) group ids.""" + probs = log_posterior.exp().float().cpu() + draws = torch.multinomial(probs, 1, generator=generator).squeeze(1) + return draws.to(log_posterior.device) + + def _expected_complete_loss( + self, + log_gate: Tensor, + log_risk: Tensor, + duration: Tensor, + event: Tensor, + log_posterior: Tensor, + assignment: Tensor, + ) -> Tensor: + """Negative Monte Carlo Q-function per observation (M-step loss).""" + gate_term = (log_posterior.exp().to(log_gate) * log_gate).sum() + partial = log_gate.new_zeros(()) + for k in range(self.num_components): + members = assignment == k + if members.any(): + partial = partial + cox_partial_log_likelihood( + log_risk[members, k], duration[members], event[members] + ) + return -(gate_term + partial) / len(duration) + + # --------------------------------------------------------------- forward + def forward(self, **kwargs: Any) -> dict[str, Tensor]: + """Run the network and, when labels are given, the EM objective. + + Args: + **kwargs: Batch fields. ``feature_key`` (batch, input_dim) is + required. ``duration_key`` and ``event_key`` (batch,) or + (batch, 1) are optional and must be given together. + + Returns: + Dictionary with ``logit`` and ``log_risk`` (log hazard ratios, + (batch, K)) and ``mixture_weights`` (gate probabilities, + (batch, K)). Once baselines are fitted and ``time_grid`` is set, + also ``survival`` and ``y_prob``: survival at ``time_grid``, + (batch, T). With labels, also ``loss`` (the negative Monte Carlo + EM objective per patient, using responsibilities from the current + baselines), ``posterior`` (responsibilities, (batch, K)) and + ``y_true`` ((batch, 2): duration, event). + """ + if self.feature_key not in kwargs: + raise ValueError(f"Missing required input {self.feature_key!r}") + x = self._features(kwargs[self.feature_key]) + log_gate, log_risk = self._network(x) + result = { + "logit": log_risk, + "log_risk": log_risk, + "mixture_weights": log_gate.exp(), + } + if self.is_fitted and self.time_grid.numel(): + survival = self._mixture_survival(log_gate, log_risk, self.time_grid) + result.update(survival=survival, y_prob=survival) + labeled = [key in kwargs for key in (self.duration_key, self.event_key)] + if any(labeled) and not all(labeled): + raise ValueError( + f"{self.duration_key} and {self.event_key} must be given together" + ) + if all(labeled): + duration = _as_vector(kwargs[self.duration_key], "duration", self.device) + event = _as_vector(kwargs[self.event_key], "event", self.device) + if len(duration) != len(x): + raise ValueError("labels and features have different batch sizes") + _check_labels(duration, event) + log_posterior = self._log_posterior(log_gate, log_risk, duration, event) + assignment = self._sample_assignment(log_posterior, None) + loss = self._expected_complete_loss( + log_gate, log_risk, duration, event, log_posterior, assignment + ) + result.update( + loss=loss, + posterior=log_posterior.exp().to(log_gate), + y_true=torch.stack([duration, event], dim=-1).to(log_gate), + ) + return result + + def _mixture_survival( + self, log_gate: Tensor, log_risk: Tensor, times: Tensor + ) -> Tensor: + """``sum_k pi_k exp(-H_0k(t) exp(f_k))`` for every row and time.""" + cumulative, _ = self._baseline_at(times) # (T, K) + risk = torch.exp(log_risk.to(torch.float64)) # (n, K) + log_terms = log_gate.to(torch.float64).unsqueeze(1) - ( + cumulative.unsqueeze(0) * risk.unsqueeze(1) + ) # (n, T, K) + survival = torch.logsumexp(log_terms, dim=-1).exp().clamp(0.0, 1.0) + return survival.to(log_gate.dtype) + + # -------------------------------------------------------------- training + def _collect(self, data: Any) -> tuple[Tensor, Tensor, Tensor]: + """Turn ``(x, t, e)``, a mapping or a dataset of samples into tensors.""" + if isinstance(data, Mapping): + parts = (data[self.feature_key], data[self.duration_key], + data[self.event_key]) + elif isinstance(data, (tuple, list)) and len(data) == 3 and not ( + isinstance(data[0], Mapping) + ): + parts = tuple(data) + else: + samples = [data[i] for i in range(len(data))] + if not samples: + raise ValueError("data is empty") + + def stack(key: str) -> Tensor: + values = [] + for sample in samples: + value = sample[key] + if isinstance(value, tuple): + value = value[0] + values.append(torch.as_tensor(value, dtype=torch.float64)) + return torch.stack(values) + + parts = (stack(self.feature_key), stack(self.duration_key), + stack(self.event_key)) + x = self._features(parts[0]) + duration = _as_vector(parts[1], "duration", self.device) + event = _as_vector(parts[2], "event", self.device) + if not len(x) == len(duration) == len(event): + raise ValueError("features, duration and event lengths differ") + if not len(x): + raise ValueError("data is empty") + _check_labels(duration, event) + return x, duration, event + + @torch.no_grad() + def fit_baselines( + self, + features: Tensor, + duration: Tensor, + event: Tensor, + generator: torch.Generator | None = None, + ) -> None: + """Re-estimate every group's Breslow baseline on the given data. + + Hard assignments are sampled from the posterior under the current + baselines (from the gate probabilities if none exist yet). A group + with no assigned patient keeps its previous baseline; if it has none, + it is fit on all patients with its own hazard ratios. A group whose + patients have no event gets a zero hazard (survival 1). + + Args: + features: Dense features, shape ``(n, input_dim)``. + duration: Strictly positive times, shape ``(n,)``. + event: 1 for an event, 0 for censoring, shape ``(n,)``. + generator: Optional random generator for the sampled assignments. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=2, num_components=2, + ... hidden_dims=()) + >>> model.fit_baselines(torch.randn(6, 2), torch.arange(1., 7.), + ... torch.ones(6)) + >>> model.is_fitted + True + """ + x = self._features(features) + duration = _as_vector(duration, "duration", self.device) + event = _as_vector(event, "event", self.device) + _check_labels(duration, event) + log_gate, log_risk = self._network(x) + log_posterior = self._log_posterior(log_gate, log_risk, duration, event) + assignment = self._sample_assignment(log_posterior, generator) + previous = None + if self.is_fitted: + previous = (self._knots.clone(), self._cumulative_hazard.clone()) + curves = [] + for k in range(self.num_components): + members = assignment == k + if not members.any() and previous is not None: + finite = torch.isfinite(previous[0][k]) + finite[0] = False # drop the time-0 origin knot + curves.append((previous[0][k][finite], previous[1][k][finite])) + continue + if not members.any(): + members = torch.ones_like(members) + curves.append(breslow_cumulative_hazard( + log_risk[members, k], duration[members], event[members] + )) + self._set_baselines(curves) + + @torch.no_grad() + def negative_log_likelihood( + self, features: Tensor, duration: Tensor, event: Tensor + ) -> float: + """Mean negative log-likelihood of the fitted mixture. + + Uses the interpolated baselines, with each group's likelihood floored + at ``1e-10`` (see the class docstring). :meth:`fit` uses it as the + validation loss for early stopping. + + Args: + features: Dense features, shape ``(n, input_dim)``. + duration: Strictly positive times, shape ``(n,)``. + event: 1 for an event, 0 for censoring, shape ``(n,)``. + + Returns: + The mean negative log-likelihood per patient. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=2, num_components=1, + ... hidden_dims=()) + >>> x, t, e = torch.randn(6, 2), torch.arange(1., 7.), torch.ones(6) + >>> model.fit_baselines(x, t, e) + >>> model.negative_log_likelihood(x, t, e) > 0 + True + """ + self._require_fitted() + x = self._features(features) + duration = _as_vector(duration, "duration", self.device) + event = _as_vector(event, "event", self.device) + _check_labels(duration, event) + log_gate, log_risk = self._network(x) + joint = log_gate.to(torch.float64) + self._component_log_likelihood( + log_risk, duration, event + ) + return float(-torch.logsumexp(joint, dim=-1).mean()) + + def fit( + self, + train_data: Any, + val_data: Any | None = None, + epochs: int = 50, + batch_size: int = 128, + learning_rate: float = 1e-3, + weight_decay: float = 0.0, + patience: int | None = 2, + baseline_update_every: int = 1, + seed: int | None = None, + ) -> dict[str, list[float]]: + """Train with the paper's Monte Carlo EM (Algorithm 1). + + Each epoch shuffles the training data. For every mini-batch: E-step + responsibilities under the current baselines, hard assignments + sampled from them, one Adam step on the negative Q-function, and + (every ``baseline_update_every`` batches) Breslow baselines refit on + the full training set. With ``val_data``, training stops after + ``patience`` epochs without a lower validation negative + log-likelihood, and the best weights and baselines are restored. + + Args: + train_data: ``(features, duration, event)``, a mapping with the + model's keys, or a dataset (for example a ``SampleDataset``) + of samples with those keys. Features must be finite. + val_data: Optional validation data in the same formats. + epochs: Maximum number of epochs (the paper's code uses 50). + batch_size: Mini-batch size (the paper uses 128). + learning_rate: Adam learning rate (the paper uses 1e-3). + weight_decay: Adam weight decay. Default 0, as in the paper. + patience: Early-stopping patience in epochs. ``None`` or no + ``val_data`` trains for all epochs. + baseline_update_every: Refit the baselines after every this many + mini-batches. The authors' code refits after every batch. + seed: Seed for shuffling and the sampled assignments. + + Returns: + History with ``train_loss`` (mean M-step loss per epoch) and, + with validation data, ``val_nll`` per epoch. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=3, num_components=2, + ... hidden_dims=(4,)) + >>> data = (torch.randn(30, 3), torch.rand(30) + 0.1, + ... torch.ones(30)) + >>> sorted(model.fit(data, data, epochs=1, seed=0)) + ['train_loss', 'val_nll'] + """ + for name, value in (("epochs", epochs), ("batch_size", batch_size), + ("baseline_update_every", baseline_update_every)): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if patience is not None and ( + isinstance(patience, bool) or not isinstance(patience, int) + or patience < 1 + ): + raise ValueError("patience must be a positive integer or None") + x, duration, event = self._collect(train_data) + validation = None if val_data is None else self._collect(val_data) + generator = torch.Generator() + if seed is not None: + generator.manual_seed(seed) + torch.manual_seed(seed) + optimizer = torch.optim.Adam( + self.parameters(), lr=learning_rate, weight_decay=weight_decay + ) + self._knots = self._cumulative_hazard = None + history: dict[str, list[float]] = {"train_loss": []} + if validation is not None: + history["val_nll"] = [] + best_loss, best_state, stale = math.inf, None, 0 + n = len(x) + for _ in range(epochs): + self.train() + order = torch.randperm(n, generator=generator).to(self.device) + total = 0.0 + for batch, start in enumerate(range(0, n, batch_size)): + index = order[start:start + batch_size] + xb, tb, eb = x[index], duration[index], event[index] + log_gate, log_risk = self._network(xb) + log_posterior = self._log_posterior(log_gate, log_risk, tb, eb) + assignment = self._sample_assignment(log_posterior, generator) + loss = self._expected_complete_loss( + log_gate, log_risk, tb, eb, log_posterior, assignment + ) + optimizer.zero_grad() + loss.backward() + optimizer.step() + total += float(loss.detach()) * len(index) + if batch % baseline_update_every == 0: + self.fit_baselines(x, duration, event, generator) + history["train_loss"].append(total / n) + self.eval() + if validation is None: + continue + val_loss = self.negative_log_likelihood(*validation) + history["val_nll"].append(val_loss) + if val_loss < best_loss: + best_loss, stale = val_loss, 0 + best_state = copy.deepcopy(self.state_dict()) + else: + stale += 1 + if patience is not None and stale >= patience: + break + if best_state is not None: + self.load_state_dict(best_state) + self.eval() + return history + + # ------------------------------------------------------------- inference + @torch.no_grad() + def predict_survival( + self, features: Tensor, times: Sequence[float] | Tensor + ) -> Tensor: + """Survival probabilities ``S(t | x)`` at the given times. + + Times after a group's last training event time use that group's + last baseline value (no extrapolation). + + Args: + features: Dense features, shape ``(n, input_dim)``. + times: Non-negative times, shape ``(T,)``, in any order. + + Returns: + Survival probabilities in [0, 1], shape ``(n, T)``. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=2, num_components=2, + ... hidden_dims=()) + >>> x, t, e = torch.randn(8, 2), torch.arange(1., 9.), torch.ones(8) + >>> model.fit_baselines(x, t, e) + >>> model.predict_survival(x, [2.0, 4.0]).shape + torch.Size([8, 2]) + """ + self._require_fitted() + x = self._features(features) + times = torch.as_tensor(times, dtype=torch.float64, device=self.device) + times = times.reshape(-1) + if not torch.isfinite(times).all() or (times < 0).any(): + raise ValueError("times must be finite and non-negative") + log_gate, log_risk = self._network(x) + return self._mixture_survival(log_gate, log_risk, times) + + @torch.no_grad() + def predict_latent(self, features: Tensor) -> Tensor: + """Latent-group probabilities ``P(Z = k | x)``. + + Args: + features: Dense features, shape ``(n, input_dim)``. + + Returns: + Probabilities of shape ``(n, K)``; each row sums to 1. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=2, num_components=3, + ... hidden_dims=(4,)) + >>> model.predict_latent(torch.zeros(2, 2)).shape + torch.Size([2, 3]) + """ + log_gate, _ = self._network(self._features(features)) + return log_gate.exp() + + @torch.no_grad() + def predict_log_risk(self, features: Tensor) -> Tensor: + """Per-group log hazard ratios ``f_k(x)``. + + Args: + features: Dense features, shape ``(n, input_dim)``. + + Returns: + Log hazard ratios of shape ``(n, K)``. + + Examples: + >>> import torch + >>> model = DeepCoxMixtures(None, input_dim=2, num_components=3, + ... hidden_dims=(4,)) + >>> model.predict_log_risk(torch.zeros(2, 2)).shape + torch.Size([2, 3]) + """ + _, log_risk = self._network(self._features(features)) + return log_risk diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index e01d41b267..2b3bc19255 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -197,6 +197,9 @@ from .survival_time_to_event import ( SurvivalTimeToEventSupport2 as SurvivalTimeToEventSupport2, ) +from .survival_time_to_event_support2_dcm import ( + SurvivalTimeToEventSupport2DCM as SurvivalTimeToEventSupport2DCM, +) from .mortality_prediction_stagenet_mimic4 import ( MortalityPredictionStageNetMIMIC4, ) diff --git a/pyhealth/tasks/survival_time_to_event_support2_dcm.py b/pyhealth/tasks/survival_time_to_event_support2_dcm.py new file mode 100644 index 0000000000..55c5f9e29f --- /dev/null +++ b/pyhealth/tasks/survival_time_to_event_support2_dcm.py @@ -0,0 +1,187 @@ +"""SUPPORT2 time-to-death task in the Deep Cox Mixtures protocol. + +Contributor: (NetID: liu323) + +Paper: Chirag Nagpal, Steve Yadlowsky, Negar Rostamzadeh and Katherine Heller. +Deep Cox Mixtures for Survival Regression. MLHC 2021. +https://proceedings.mlr.press/v149/nagpal21a.html + +The covariates, one-hot coding and race grouping follow the paper's released +preprocessing for SUPPORT (all 9,105 patients, 44 features). Imputation and +scaling are left to the caller so they can be fit on training patients only. +""" + +import math +from collections.abc import Mapping +from typing import Any, ClassVar + +from pyhealth.data import Patient + +from .base_task import BaseTask + +#: Numeric covariates, in the paper's order. Missing values become NaN. +SUPPORT2_DCM_NUMERIC: tuple[str, ...] = ( + "age", "num.co", "meanbp", "wblc", "hrt", "resp", "temp", "pafi", "alb", + "bili", "crea", "sod", "ph", "glucose", "bun", "urine", "adlp", "adls", +) +#: Categorical covariates and their levels. Every level gets a column (no +#: reference level is dropped) and a missing value gets all zeros, which is +#: what ``pandas.get_dummies`` produces in the paper's code. +SUPPORT2_DCM_CATEGORIES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("sex", ("female", "male")), + ("dzgroup", ( + "ARF/MOSF w/Sepsis", "CHF", "COPD", "Cirrhosis", "Colon Cancer", "Coma", + "Lung Cancer", "MOSF w/Malig", + )), + ("dzclass", ("ARF/MOSF", "COPD/CHF/Cirrhosis", "Cancer", "Coma")), + ("income", ("$11-$25k", "$25-$50k", ">$50k", "under $11k")), + ("race", ("asian", "black", "hispanic", "other", "white")), + ("ca", ("metastatic", "no", "yes")), +) +#: Names of the 44 entries of the ``features`` vector, in order. +SUPPORT2_DCM_FEATURES: tuple[str, ...] = SUPPORT2_DCM_NUMERIC + tuple( + f"{name}={level}" for name, levels in SUPPORT2_DCM_CATEGORIES + for level in levels +) + + +def _blank(value: Any) -> bool: + """Whether a raw CSV value is missing.""" + if value is None: + return True + if isinstance(value, float): + return math.isnan(value) + return isinstance(value, str) and value.strip().lower() in ("", "nan", "none") + + +class SurvivalTimeToEventSupport2DCM(BaseTask): + """Time to death on SUPPORT2 with the Deep Cox Mixtures covariates. + + Use with :class:`~pyhealth.datasets.Support2Dataset`. Unlike + :class:`~pyhealth.tasks.SurvivalTimeToEventSupport2` (the 8,873-patient + complete-case DeepSurv benchmark with 14 covariates), this task keeps + all 9,105 patients and the 24 covariates of the Deep Cox Mixtures paper: + 18 numeric ones, in ``SUPPORT2_DCM_NUMERIC`` order, followed by one-hot + codes of sex, disease group, disease class, income, race and cancer + status (``SUPPORT2_DCM_CATEGORIES``), giving ``features: [44]`` named by + ``SUPPORT2_DCM_FEATURES``. A missing numeric value is NaN and a missing + category is all zeros. The paper imputes missing values with the mean + and standardizes every column; fit both on training patients only before + training a model, since the samples are not imputed here. + + Labels are ``duration: [d.time]`` in days and ``event: [death]`` (1 for + death, 0 for censoring). Each sample also has ``race``: the recorded + race, or ``"missing"``. The paper's minority group is every patient whose + race is not ``"white"``, missing race included. + + Examples: + >>> from pyhealth.tasks import SurvivalTimeToEventSupport2DCM + >>> task = SurvivalTimeToEventSupport2DCM() + >>> task.output_schema + {'duration': 'tensor', 'event': 'tensor'} + >>> from pyhealth.tasks.survival_time_to_event_support2_dcm import ( + ... SUPPORT2_DCM_FEATURES, + ... ) + >>> len(SUPPORT2_DCM_FEATURES), SUPPORT2_DCM_FEATURES[18] + (44, 'sex=female') + """ + + task_name: str = "SurvivalTimeToEventSupport2DCM" + input_schema: ClassVar[dict[str, str]] = {"features": "tensor"} + output_schema: ClassVar[dict[str, str]] = { + "duration": "tensor", + "event": "tensor", + } + + @staticmethod + def encode(record: Mapping[str, Any], source_id: str) -> dict[str, Any]: + """Encode one SUPPORT2 row. + + Args: + record: The row's raw values by column name. + source_id: Identifier used in error messages. + + Returns: + ``features`` (44 floats, NaN where a numeric value is missing), + ``duration``, ``event`` and ``race``. + + Raises: + ValueError: For non-numeric values, unknown categories, a + missing or non-positive ``d.time``, or ``death`` not 0/1. + + Examples: + >>> row = {name: "1" for name in SUPPORT2_DCM_NUMERIC} + >>> row.update({"sex": "male", "dzgroup": "Coma", "dzclass": "Coma", + ... "income": "", "race": "white", "ca": "no", + ... "d.time": "30", "death": "1"}) + >>> sample = SurvivalTimeToEventSupport2DCM.encode(row, "1") + >>> len(sample["features"]), sample["duration"], sample["race"] + (44, [30.0], 'white') + """ + features: list[float] = [] + for name in SUPPORT2_DCM_NUMERIC: + raw = record.get(name) + if _blank(raw): + features.append(math.nan) + continue + try: + value = float(raw) + except (TypeError, ValueError) as exc: + raise ValueError( + f"SUPPORT2 record {source_id}: non-numeric {name} {raw!r}" + ) from exc + if not math.isfinite(value): + raise ValueError(f"SUPPORT2 record {source_id}: {name} not finite") + features.append(value) + race = "missing" + for name, levels in SUPPORT2_DCM_CATEGORIES: + raw = record.get(name) + level = None if _blank(raw) else str(raw).strip() + if level is not None and level not in levels: + raise ValueError( + f"SUPPORT2 record {source_id}: unknown {name} {raw!r}" + ) + features.extend(1.0 if level == option else 0.0 for option in levels) + if name == "race" and level is not None: + race = level + try: + time = float(record["d.time"]) + event = float(record["death"]) + except (KeyError, TypeError, ValueError) as exc: + raise ValueError( + f"SUPPORT2 record {source_id}: missing or non-numeric d.time/death" + ) from exc + if not math.isfinite(time) or time <= 0: + raise ValueError(f"SUPPORT2 record {source_id}: d.time must be > 0") + if event not in (0.0, 1.0): + raise ValueError(f"SUPPORT2 record {source_id}: death must be 0 or 1") + return { + "features": features, + "duration": [time], + "event": [event], + "race": race, + } + + def __call__(self, patient: Patient) -> list[dict[str, Any]]: + """Return the patient's single sample. + + Args: + patient: Patient with exactly one ``support2`` event; the patient + ID is SUPPORT2's patient number (``sno``). + + Returns: + One sample with ``patient_id``, ``features``, ``duration``, + ``event`` and ``race``. + + Raises: + ValueError: If the patient does not have exactly one record or + the record is invalid (see :meth:`encode`). + """ + events = patient.get_events("support2") + if len(events) != 1: + raise ValueError( + f"SUPPORT2 record {patient.patient_id}: expected exactly one " + f"support2 event, got {len(events)}" + ) + sample = self.encode(events[0].attr_dict, patient.patient_id) + return [{"patient_id": patient.patient_id, **sample}] diff --git a/tests/core/test_deep_cox_mixtures.py b/tests/core/test_deep_cox_mixtures.py new file mode 100644 index 0000000000..701e88d0df --- /dev/null +++ b/tests/core/test_deep_cox_mixtures.py @@ -0,0 +1,388 @@ +"""Fast synthetic tests for DeepCoxMixtures; no real data or downloads. + +Contributor: (NetID: liu323) +Paper: Deep Cox Mixtures for Survival Regression (Nagpal et al., MLHC 2021), +https://proceedings.mlr.press/v149/nagpal21a.html +""" + +import math +import os +import tempfile +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import BaseModel, DeepCoxMixtures +from pyhealth.models.deep_cox_mixtures import ( + breslow_cumulative_hazard, + cox_partial_log_likelihood, +) + + +def synthetic(n=24, dim=3, seed=0): + """Tiny right-censored data: times in (0.1, 5.1], ~70% events.""" + g = torch.Generator().manual_seed(seed) + x = torch.randn(n, dim, generator=g) + t = torch.rand(n, generator=g) * 5 + 0.1 + e = (torch.rand(n, generator=g) < 0.7).float() + e[0] = 1.0 + return x, t, e + + +def fitted_model(k=2, hidden=(4,), seed=0): + torch.manual_seed(seed) + model = DeepCoxMixtures(None, input_dim=3, num_components=k, + hidden_dims=hidden, time_grid=[0.5, 1.0, 2.0]) + x, t, e = synthetic() + model.fit_baselines(x, t, e, generator=torch.Generator().manual_seed(seed)) + return model, (x, t, e) + + +class TestInstantiation(unittest.TestCase): + def test_from_sample_dataset(self): + samples = [ + {"patient_id": f"p{i}", "features": [float(i), 1.0, -1.0, 0.5], + "duration": [1.0 + i], "event": [float(i % 2)]} + for i in range(4) + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"features": "tensor"}, + output_schema={"duration": "tensor", "event": "tensor"}, + dataset_name="dcm_test", + ) + model = DeepCoxMixtures(dataset, num_components=2, hidden_dims=(4,)) + self.assertIsInstance(model, BaseModel) + self.assertEqual(model.input_dim, 4) + self.assertIsNone(model.mode) + self.assertEqual(model.label_processors, {}) + self.assertEqual(model.feature_keys, ["features"]) + self.assertFalse(model.is_fitted) + batch = next(iter(get_dataloader(dataset, batch_size=4, shuffle=False))) + out = model(**batch) + self.assertEqual(out["log_risk"].shape, (4, 2)) + self.assertTrue(torch.isfinite(out["loss"])) + + def test_configurations(self): + linear = DeepCoxMixtures(None, input_dim=3, num_components=1, + hidden_dims=()) + self.assertEqual(len(linear.encoder), 0) + deep = DeepCoxMixtures(None, input_dim=3, num_components=4, + hidden_dims=(5, 6), activation="relu", + use_bias=True, log_risk_bound=None) + self.assertEqual(deep.risk.out_features, 4) + self.assertIsNotNone(deep.encoder[0].bias) + self.assertIsNone(deep.risk.bias) + + def test_invalid_configuration(self): + bad = [ + dict(input_dim=None), dict(input_dim=0), dict(input_dim=3, + num_components=0), + dict(input_dim=3, hidden_dims=(0,)), dict(input_dim=3, + activation="gelu"), + dict(input_dim=3, log_risk_bound=-1.0), dict(input_dim=3, + time_grid=[-1.0]), + dict(input_dim=True), + ] + for kwargs in bad: + with self.assertRaises(ValueError, msg=str(kwargs)): + DeepCoxMixtures(None, **kwargs) + + def test_dataset_keys_are_checked(self): + dataset = create_sample_dataset( + samples=[{"patient_id": "p", "features": [1.0], "duration": [1.0], + "event": [1.0]}], + input_schema={"features": "tensor"}, + output_schema={"duration": "tensor", "event": "tensor"}, + dataset_name="dcm_keys", + ) + with self.assertRaises(ValueError): + DeepCoxMixtures(dataset, feature_key="x") + with self.assertRaises(ValueError): + DeepCoxMixtures(dataset, event_key="status") + + +class TestForward(unittest.TestCase): + def test_shapes_probabilities_and_gradients(self): + model, (x, t, e) = fitted_model(k=3) + out = model(features=x[:5], duration=t[:5], event=e[:5]) + self.assertEqual(out["log_risk"].shape, (5, 3)) + self.assertEqual(out["mixture_weights"].shape, (5, 3)) + self.assertEqual(out["posterior"].shape, (5, 3)) + self.assertEqual(out["y_prob"].shape, (5, 3)) + self.assertEqual(out["y_true"].shape, (5, 2)) + self.assertEqual(out["loss"].ndim, 0) + for key in ("mixture_weights", "posterior"): + self.assertTrue(torch.all(out[key] >= 0)) + torch.testing.assert_close(out[key].sum(-1), torch.ones(5)) + out["loss"].backward() + for name, param in model.named_parameters(): + if name == "_dummy_param": + continue + self.assertIsNotNone(param.grad, name) + self.assertTrue(torch.isfinite(param.grad).all(), name) + self.assertGreater(float(param.grad.abs().sum()), 0.0, name) + + def test_singleton_batch_and_unfitted_forward(self): + model = DeepCoxMixtures(None, input_dim=3, num_components=2, + hidden_dims=(4,), time_grid=[1.0]) + out = model(features=torch.zeros(1, 3), duration=[2.0], event=[1.0]) + self.assertNotIn("y_prob", out) # no baselines yet + self.assertEqual(out["mixture_weights"].shape, (1, 2)) + # Before baselines exist the E-step returns the gate probabilities. + torch.testing.assert_close(out["posterior"], out["mixture_weights"]) + + def test_survival_range_and_monotonicity(self): + model, (x, _, _) = fitted_model(k=3) + times = torch.linspace(0.0, 10.0, 25) + surv = model.predict_survival(x, times) + self.assertEqual(surv.shape, (len(x), 25)) + self.assertTrue(torch.isfinite(surv).all()) + self.assertTrue(torch.all((surv >= 0) & (surv <= 1))) + self.assertTrue(torch.all(surv[:, 1:] <= surv[:, :-1] + 1e-7)) + torch.testing.assert_close(surv[:, 0], torch.ones(len(x))) + # unsorted request gives the same values in the requested order + flipped = model.predict_survival(x, times.flip(0)) + torch.testing.assert_close(flipped, surv.flip(1)) + + def test_mixture_formula(self): + model, (x, _, _) = fitted_model(k=2) + times = torch.tensor([0.7, 3.0]) + pi = model.predict_latent(x) + f = model.predict_log_risk(x).double() + cumulative, _ = model._baseline_at(times) # (T, K) + manual = (pi.double().unsqueeze(1) * torch.exp( + -cumulative.unsqueeze(0) * f.exp().unsqueeze(1))).sum(-1) + torch.testing.assert_close(model.predict_survival(x, times).double(), + manual, atol=1e-6, rtol=1e-5) + + +class TestCoxAndBreslow(unittest.TestCase): + def setUp(self): + # Ties at t = 2 (two events) and a censored tie at t = 3. + self.f = torch.tensor([0.1, 0.2, -0.3, 0.4, 0.0], dtype=torch.float64) + self.t = torch.tensor([1.0, 2.0, 2.0, 3.0, 3.0], dtype=torch.float64) + self.e = torch.tensor([1.0, 1.0, 1.0, 1.0, 0.0], dtype=torch.float64) + + def test_partial_likelihood_breslow_ties(self): + r = self.f.exp() + expected = ( + (0.1 - math.log(r.sum())) + + (0.2 - math.log(r[1:].sum())) + + (-0.3 - math.log(r[1:].sum())) + + (0.4 - math.log(r[3:].sum())) + ) + got = cox_partial_log_likelihood(self.f, self.t, self.e) + self.assertAlmostEqual(float(got), expected, places=10) + # order of the rows does not matter + perm = torch.tensor([4, 2, 0, 3, 1]) + self.assertAlmostEqual(float(cox_partial_log_likelihood( + self.f[perm], self.t[perm], self.e[perm])), expected, places=10) + self.assertEqual(float(cox_partial_log_likelihood( + self.f, self.t, torch.zeros(5))), 0.0) + self.assertEqual(float(cox_partial_log_likelihood( + torch.zeros(0), torch.zeros(0), torch.zeros(0))), 0.0) + + def test_breslow_hand_computed(self): + r = self.f.exp() + times, hazard = breslow_cumulative_hazard(self.f, self.t, self.e) + h1 = 1 / r.sum() + h2 = h1 + 2 / r[1:].sum() + h3 = h2 + 1 / r[3:].sum() + self.assertEqual(times.tolist(), [1.0, 2.0, 3.0]) + torch.testing.assert_close(hazard, torch.stack([h1, h2, h3])) + empty_t, empty_h = breslow_cumulative_hazard(self.f, self.t, + torch.zeros(5)) + self.assertEqual(len(empty_t), 0) + self.assertEqual(len(empty_h), 0) + + def test_single_component_is_neural_cox(self): + torch.manual_seed(1) + model = DeepCoxMixtures(None, input_dim=3, num_components=1, + hidden_dims=(4,)) + x, t, e = synthetic() + model.fit_baselines(x, t, e) + out = model(features=x, duration=t, event=e) + torch.testing.assert_close(out["mixture_weights"], torch.ones(len(x), 1)) + expected = -cox_partial_log_likelihood(out["log_risk"][:, 0], t, e) + torch.testing.assert_close(out["loss"].double(), + expected.double() / len(x)) + # baseline is the Breslow estimate with the network's hazard ratios + times, hazard = breslow_cumulative_hazard(out["log_risk"][:, 0], t, e) + f = model.predict_log_risk(x)[:, 0].double() + surv = model.predict_survival(x, times).double() + torch.testing.assert_close( + surv, torch.exp(-hazard.unsqueeze(0) * f.exp().unsqueeze(1)), + atol=1e-6, rtol=1e-5) + + +class TestEStep(unittest.TestCase): + def test_posterior_matches_manual_and_uses_censoring(self): + model, (x, t, e) = fitted_model(k=2) + log_gate, log_risk = model._network(x) + cumulative, rate = model._baseline_at(t) + f = log_risk.double() + log_s = -cumulative * f.exp() + log_d = f + rate.log() + log_s + ll = torch.where(e.bool().unsqueeze(1), log_d, log_s).clamp_min( + math.log(1e-10)) + manual = torch.softmax(log_gate.double() + ll, dim=-1) + got = model._log_posterior(log_gate, log_risk, t.double(), + e.double()).exp() + torch.testing.assert_close(got, manual) + # The same row gets a different posterior as an event or censored. + as_event = model._log_posterior(log_gate[:1], log_risk[:1], + t[:1].double(), torch.ones(1)) + as_censored = model._log_posterior(log_gate[:1], log_risk[:1], + t[:1].double(), torch.zeros(1)) + self.assertFalse(torch.allclose(as_event, as_censored)) + + def test_interpolation_and_support(self): + model = DeepCoxMixtures(None, input_dim=1, num_components=1, + hidden_dims=()) + model._set_baselines([(torch.tensor([1.0, 3.0], dtype=torch.float64), + torch.tensor([0.2, 0.6], dtype=torch.float64))]) + cumulative, rate = model._baseline_at(torch.tensor([0.0, 0.5, 2.0, 3.0, + 9.0])) + torch.testing.assert_close(cumulative[:, 0], torch.tensor( + [0.0, 0.1, 0.4, 0.6, 0.6], dtype=torch.float64)) + torch.testing.assert_close(rate[:, 0], torch.tensor( + [0.2, 0.2, 0.2, 0.2, 0.0], dtype=torch.float64)) + + +class TestEdgeCases(unittest.TestCase): + def test_zero_event_and_empty_components(self): + torch.manual_seed(0) + model = DeepCoxMixtures(None, input_dim=3, num_components=3, + hidden_dims=()) + x, t, _ = synthetic() + model.fit_baselines(x, t, torch.zeros(len(t))) # nobody has an event + surv = model.predict_survival(x, [1.0, 4.0]) + torch.testing.assert_close(surv, torch.ones_like(surv)) + out = model(features=x, duration=t, event=torch.ones(len(t))) + self.assertTrue(torch.isfinite(out["loss"])) + self.assertTrue(torch.isfinite(out["posterior"]).all()) + # Force every patient into group 0: groups 1 and 2 keep old baselines. + before = model._cumulative_hazard[1:, 1:].clone() + with torch.no_grad(): + model.gate.weight.zero_() + model.risk.weight.zero_() + model.gate.weight[0] = 50.0 + x_pos = x.abs() + 1.0 # positive inputs -> group 0 logit dominates + model.fit_baselines(x_pos, t, torch.ones(len(t))) + # groups 1 and 2 still have no event knot and a zero hazard + self.assertTrue(torch.isinf(model._knots[1:, 1:]).all()) + self.assertEqual(float(before.abs().sum()), 0.0) + self.assertEqual(float(model._cumulative_hazard[1:].abs().sum()), 0.0) + self.assertGreater(int(torch.isfinite(model._knots[0]).sum()), 1) + self.assertTrue(torch.isfinite(model.predict_survival(x, [2.0])).all()) + + def test_first_fit_with_empty_component_uses_everyone(self): + model = DeepCoxMixtures(None, input_dim=2, num_components=2, + hidden_dims=()) + with torch.no_grad(): + model.gate.weight.copy_(torch.tensor([[50.0, 0.0], [0.0, 0.0]])) + x = torch.ones(6, 2) + model.fit_baselines(x, torch.arange(1.0, 7.0), torch.ones(6)) + self.assertEqual(int(torch.isfinite(model._knots[1]).sum()), 7) + + +class TestPersistenceAndValidation(unittest.TestCase): + def test_state_dict_round_trip(self): + model, (x, _, _) = fitted_model(k=2) + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "dcm.pt") + torch.save(model.state_dict(), path) + restored = DeepCoxMixtures(None, input_dim=3, num_components=2, + hidden_dims=(4,)) + self.assertFalse(restored.is_fitted) + restored.load_state_dict(torch.load(path)) + self.assertFalse(os.path.exists(root)) + torch.testing.assert_close(restored.predict_survival(x, [0.5, 2.0]), + model.predict_survival(x, [0.5, 2.0])) + torch.testing.assert_close(restored.time_grid, model.time_grid) + torch.testing.assert_close(restored(features=x)["y_prob"], + model(features=x)["y_prob"]) + with self.assertRaises(ValueError): + DeepCoxMixtures(None, input_dim=3, num_components=3, + hidden_dims=(4,)).set_extra_state( + model.get_extra_state()) + + def test_invalid_inputs(self): + model, (x, t, e) = fitted_model(k=2) + with self.assertRaises(ValueError): + model(features=x, duration=-t, event=e) + with self.assertRaises(ValueError): + model(features=x, duration=t, event=e + 1) + with self.assertRaises(ValueError): + model(features=x, duration=t) # event missing + with self.assertRaises(ValueError): + model(features=x[:, :2]) + with self.assertRaises(ValueError): + model(duration=t, event=e) + nan_x = x.clone() + nan_x[0, 0] = float("nan") + with self.assertRaises(ValueError): + model.predict_latent(nan_x) + with self.assertRaises(ValueError): + model.predict_survival(x, [-1.0]) + with self.assertRaises(ValueError): + model(features=x, duration=t[:3], event=e[:3]) + unfitted = DeepCoxMixtures(None, input_dim=3, num_components=2) + with self.assertRaises(RuntimeError): + unfitted.predict_survival(x, [1.0]) + with self.assertRaises(RuntimeError): + unfitted.negative_log_likelihood(x, t, e) + with self.assertRaises(ValueError): + unfitted.fit((x, t, e), epochs=0) + with self.assertRaises(ValueError): + unfitted.fit((x, t, e), patience=0) + + +class TestFit(unittest.TestCase): + def test_fit_tuple_with_validation(self): + torch.manual_seed(0) + model = DeepCoxMixtures(None, input_dim=3, num_components=2, + hidden_dims=(4,), time_grid=[1.0, 2.0]) + x, t, e = synthetic(n=32) + history = model.fit((x, t, e), (x[:8], t[:8], e[:8]), epochs=3, + batch_size=8, patience=1, seed=0) + self.assertLessEqual(len(history["train_loss"]), 3) + self.assertEqual(len(history["val_nll"]), len(history["train_loss"])) + self.assertTrue(all(math.isfinite(v) for v in history["val_nll"])) + self.assertTrue(model.is_fitted) + self.assertFalse(model.training) + self.assertEqual(model(features=x)["y_prob"].shape, (32, 2)) + self.assertGreater(model.negative_log_likelihood(x, t, e), 0) + + def test_fit_is_reproducible_with_seed(self): + x, t, e = synthetic(n=20) + preds = [] + for _ in range(2): + torch.manual_seed(3) + model = DeepCoxMixtures(None, input_dim=3, num_components=2, + hidden_dims=(4,)) + model.fit({"features": x, "duration": t, "event": e}, epochs=2, + batch_size=10, seed=11) + preds.append(model.predict_survival(x, [1.0, 3.0])) + torch.testing.assert_close(preds[0], preds[1]) + + def test_fit_sample_dataset(self): + x, t, e = synthetic(n=12) + samples = [{"patient_id": str(i), "features": x[i].tolist(), + "duration": [float(t[i])], "event": [float(e[i])]} + for i in range(12)] + dataset = create_sample_dataset( + samples=samples, input_schema={"features": "tensor"}, + output_schema={"duration": "tensor", "event": "tensor"}, + dataset_name="dcm_fit", + ) + model = DeepCoxMixtures(dataset, num_components=2, hidden_dims=(4,)) + history = model.fit(dataset, epochs=1, batch_size=6, seed=0) + self.assertEqual(len(history["train_loss"]), 1) + self.assertTrue(model.is_fitted) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_survival_time_to_event_support2_dcm.py b/tests/core/test_survival_time_to_event_support2_dcm.py new file mode 100644 index 0000000000..bf04fb5841 --- /dev/null +++ b/tests/core/test_survival_time_to_event_support2_dcm.py @@ -0,0 +1,133 @@ +"""Fast synthetic tests for SurvivalTimeToEventSupport2DCM; no real data. + +Contributor: (NetID: liu323) +Paper: Deep Cox Mixtures for Survival Regression (Nagpal et al., MLHC 2021), +https://proceedings.mlr.press/v149/nagpal21a.html +""" + +import math +import unittest + +import polars as pl +import torch + +from pyhealth.data import Patient +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import DeepCoxMixtures +from pyhealth.tasks import SurvivalTimeToEventSupport2DCM +from pyhealth.tasks.survival_time_to_event_support2_dcm import ( + SUPPORT2_DCM_CATEGORIES, + SUPPORT2_DCM_FEATURES, + SUPPORT2_DCM_NUMERIC, +) + + +def row(sno, **overrides): + """One synthetic SUPPORT2 row with every column the task reads.""" + values = {"sno": str(sno)} + values.update({name: str(10 + j + sno) for j, name in + enumerate(SUPPORT2_DCM_NUMERIC)}) + values.update(sex="female", dzgroup="CHF", dzclass="COPD/CHF/Cirrhosis", + income="$25-$50k", race="black", ca="no", + **{"d.time": str(5 * sno), "death": str(sno % 2)}) + values.update(overrides) + return values + + +def patient(rows): + events = [ + {"patient_id": r["sno"], "event_type": "support2", "timestamp": None, + **{f"support2/{k}": (v if v != "" else None) + for k, v in r.items() if k != "sno"}} + for r in rows + ] + return Patient(rows[0]["sno"] if rows else "0", pl.DataFrame(events)) + + +class TestSupport2DCMTask(unittest.TestCase): + def test_schema_and_feature_names(self): + task = SurvivalTimeToEventSupport2DCM() + self.assertEqual(task.input_schema, {"features": "tensor"}) + self.assertEqual(task.output_schema, + {"duration": "tensor", "event": "tensor"}) + self.assertEqual(len(SUPPORT2_DCM_NUMERIC), 18) + self.assertEqual(sum(len(v) for _, v in SUPPORT2_DCM_CATEGORIES), 26) + self.assertEqual(len(SUPPORT2_DCM_FEATURES), 44) + self.assertEqual(SUPPORT2_DCM_FEATURES[18:20], + ("sex=female", "sex=male")) + self.assertEqual(len(set(SUPPORT2_DCM_FEATURES)), 44) + + def test_encoding_of_a_patient(self): + r = row(3) + (sample,) = SurvivalTimeToEventSupport2DCM()(patient([r])) + self.assertEqual(sample["patient_id"], "3") + features = sample["features"] + self.assertEqual(features[:18], + [float(r[name]) for name in SUPPORT2_DCM_NUMERIC]) + hot = {SUPPORT2_DCM_FEATURES[j] for j in range(18, 44) + if features[j] == 1.0} + self.assertEqual(hot, {"sex=female", "dzgroup=CHF", + "dzclass=COPD/CHF/Cirrhosis", "income=$25-$50k", + "race=black", "ca=no"}) + self.assertEqual(sum(features[18:]), 6.0) + self.assertEqual(sample["duration"], [15.0]) + self.assertEqual(sample["event"], [1.0]) + self.assertEqual(sample["race"], "black") + + def test_missing_values(self): + r = row(2, alb="", income="", race="") + (sample,) = SurvivalTimeToEventSupport2DCM()(patient([r])) + features = sample["features"] + self.assertTrue(math.isnan(features[SUPPORT2_DCM_FEATURES.index("alb")])) + income = [j for j, n in enumerate(SUPPORT2_DCM_FEATURES) + if n.startswith(("income=", "race="))] + self.assertEqual([features[j] for j in income], [0.0] * 9) + self.assertEqual(sample["race"], "missing") + self.assertEqual(sample["event"], [0.0]) + # encode() also accepts NaN floats for missing values + direct = SurvivalTimeToEventSupport2DCM.encode( + {**row(2), "alb": float("nan")}, "2") + self.assertTrue(math.isnan(direct["features"][8])) + + def test_invalid_records(self): + task = SurvivalTimeToEventSupport2DCM() + bad = [dict(age="old"), dict(dzgroup="Flu"), dict(**{"d.time": "0"}), + dict(**{"d.time": ""}), dict(death="2"), dict(age="inf")] + for overrides in bad: + with self.assertRaises(ValueError, msg=str(overrides)): + task(patient([row(1, **overrides)])) + with self.assertRaises(ValueError): + task(patient([row(1), row(2)])) + + def test_samples_train_deep_cox_mixtures(self): + task = SurvivalTimeToEventSupport2DCM() + samples = [] + for i in range(1, 7): + (s,) = task(patient([row(i, bun="" if i % 2 else "9")])) + samples.append(s) + # Mean-impute and standardize with "training" statistics, as the + # task's documentation asks, before handing samples to the model. + x = torch.tensor([s["features"] for s in samples]) + mean = torch.nanmean(x, dim=0) + x = torch.where(torch.isnan(x), mean, x) + x = (x - x.mean(0)) / x.std(0).clamp_min(1e-6) + for s, features in zip(samples, x.tolist()): + s["features"] = features + dataset = create_sample_dataset( + samples=samples, input_schema=task.input_schema, + output_schema=task.output_schema, dataset_name="support2_dcm", + ) + self.assertEqual(dataset[0]["race"], "black") + torch.manual_seed(0) + model = DeepCoxMixtures(dataset, num_components=2, hidden_dims=(4,), + time_grid=[10.0, 20.0]) + self.assertEqual(model.input_dim, 44) + model.fit(dataset, epochs=1, batch_size=3, seed=0) + batch = next(iter(get_dataloader(dataset, batch_size=6, shuffle=False))) + out = model(**batch) + self.assertEqual(out["y_prob"].shape, (6, 2)) + self.assertTrue(torch.isfinite(out["loss"])) + + +if __name__ == "__main__": + unittest.main() From 42d8c8f9b4d3195fd6a1618a81e9dd59a0aaf6f4 Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 2/6] Add SUPPORT2 DCM example with mixture-size ablation; lint and format Co-Authored-By: Claude Opus 5.5 --- .../support2_survival_deep_cox_mixtures.py | 361 ++++++++++++++++++ pyhealth/models/deep_cox_mixtures.py | 65 ++-- .../survival_time_to_event_support2_dcm.py | 44 ++- tests/core/test_deep_cox_mixtures.py | 220 +++++++---- ...est_survival_time_to_event_support2_dcm.py | 89 +++-- 5 files changed, 635 insertions(+), 144 deletions(-) create mode 100644 examples/support2_survival_deep_cox_mixtures.py diff --git a/examples/support2_survival_deep_cox_mixtures.py b/examples/support2_survival_deep_cox_mixtures.py new file mode 100644 index 0000000000..cafcd95c4b --- /dev/null +++ b/examples/support2_survival_deep_cox_mixtures.py @@ -0,0 +1,361 @@ +"""SUPPORT2 survival with Deep Cox Mixtures: mixture-size ablation. + +Contributor: (NetID: liu323) +Paper: Nagpal, Yadlowsky, Rostamzadeh and Heller. Deep Cox Mixtures for +Survival Regression. MLHC 2021. https://proceedings.mlr.press/v149/nagpal21a.html + +Pipeline +-------- +``Support2Dataset`` -> ``SurvivalTimeToEventSupport2DCM`` (9,105 patients, 44 +features) -> mean imputation and standardization fit on training patients -> +``DeepCoxMixtures.fit`` (Monte Carlo EM) -> survival at the paper's horizons +(14, 58 and 252 days: the 25th/50th/75th event-time quantiles) -> the paper's +metrics: KM-adjusted expected calibration error (ECE, 20 equal-frequency bins, +out-of-fold predictions pooled), IPCW Brier score, IPCW time-dependent +concordance (Ctd, truncated at the horizon) and cumulative/dynamic AUC, the +last three averaged over folds with censoring weights from each fold's +training patients. + +Protocol: the paper's 5 outer folds (row order, ``fold = (sno - 1) % 5``); in +each, a random 15% of the training patients is used for early stopping. The +model uses the paper's settings (Adam, learning rate 1e-3, batch size 128, up +to 50 epochs, SELU encoder without bias). Validation and test patients are +never used to fit preprocessing, baselines or weights. + +Ablation +-------- +The number of latent groups ``K`` is varied with everything else fixed +(encoder ``[100, 100]``, same folds, seed and splits). ``K = 1`` is a neural +Cox model with a Breslow baseline, so the comparison isolates the mixture. +``--train-censoring`` adds the project's extension: extra independent +exponential censoring of the *training* patients only (validation and test +unchanged), with the rate solved so that the training censoring rate rises by +the given number of percentage points. + +Usage +----- +Synthetic data (a two-group population with crossing survival curves, so a +mixture should help; under a minute on a CPU):: + + python examples/support2_survival_deep_cox_mixtures.py --synthetic + +SUPPORT2 (``root`` holds ``support2.csv`` with an ``sno`` column; the UCI file +https://archive.ics.uci.edu/dataset/880/support2 calls it ``id``):: + + pip install scikit-survival + python examples/support2_survival_deep_cox_mixtures.py --root data/support2 + python examples/support2_survival_deep_cox_mixtures.py --root data/support2 \ + --components 1,3 --train-censoring 0,10,20,30 + +Measured results (SUPPORT2, 5 folds, seed 0, CPU, about 1-2 minutes per run) +---------------------------------------------------------------------------- +K ablation (no extra censoring), all patients | non-White: + + K ECE@252 Ctd@252 Brier@252 Ctd@58 | ECE@252 Ctd@252 + 1 0.0173 0.6646 0.2146 0.6665 | 0.0419 0.6887 + 2 0.0214 0.6717 0.2131 0.7053 | 0.0519 0.6990 + 3 0.0142 0.6703 0.2129 0.7041 | 0.0400 0.6915 + 6 0.0151 0.6733 0.2124 0.7063 | 0.0376 0.6977 + +Extra training censoring (one censoring draw), all patients: + + +pp K=1 ECE@252 K=3 ECE@252 K=1 Brier@252 K=3 Brier@252 + 0 0.0173 0.0142 0.2146 0.2129 + 10 0.0201 0.0123 0.2136 0.2130 + 20 0.0182 0.0175 0.2144 0.2130 + 30 0.0192 0.0159 0.2171 0.2144 + +Findings: mixtures (K >= 2) discriminate better than the single-component +neural Cox model, most clearly at 58 days (Ctd 0.667 -> 0.704-0.706) and less +at 252 days (0.665 -> 0.670-0.673), with a slightly lower Brier score. +Calibration differences between K values are small and not consistent across +K (ECE@252 0.014-0.021), so this run does not show that more components +improve calibration. With extra training censoring, K = 3 kept an ECE@252 +no higher than K = 1 at every level in this single draw. In the project's +full study (3 seeds / 3 censoring draws, paired bootstrap), the +discrimination gain of K >= 2 over K = 1 was significant, while ECE +differences were within sampling noise. The synthetic run (two groups with +crossing curves) shows the expected calibration gain of K >= 2 +(ECE@252 0.056 for K = 1 vs 0.029-0.033). +""" + +import argparse +import itertools +import json +import math +import time + +import numpy as np +import torch + +from pyhealth.models import DeepCoxMixtures + +HORIZONS = (14.0, 58.0, 252.0) + + +def load_support2(root: str) -> dict[str, np.ndarray]: + """Load SUPPORT2 through PyHealth's dataset and the DCM-protocol task. + + Args: + root: Folder containing ``support2.csv``. + + Returns: + Raw features (NaN where missing), durations, events, race and the + paper's outer fold of every patient, in ``sno`` order. + """ + from pyhealth.datasets import Support2Dataset + from pyhealth.tasks import SurvivalTimeToEventSupport2DCM + + dataset = Support2Dataset(root=root, tables=["support2"]) + samples = dataset.set_task(SurvivalTimeToEventSupport2DCM(), num_workers=1) + rows = sorted( + (samples[i] for i in range(len(samples))), key=lambda s: int(s["patient_id"]) + ) + sno = np.array([int(s["patient_id"]) for s in rows]) + return { + "x": torch.stack([s["features"] for s in rows]).double().numpy(), + "t": torch.cat([s["duration"] for s in rows]).double().numpy(), + "e": torch.cat([s["event"] for s in rows]).double().numpy(), + "race": np.array([s["race"] for s in rows]), + "folds": (sno - 1) % 5, + } + + +def synthetic(n: int = 3000, seed: int = 0) -> dict[str, np.ndarray]: + """Two latent groups with crossing survival curves (non-PH overall). + + Args: + n: Number of patients. + seed: Random seed. + + Returns: + The same fields as :func:`load_support2`, times in arbitrary units. + """ + rng = np.random.default_rng(seed) + x = rng.normal(size=(n, 6)) + early = x[:, 0] > 0 + shape = np.where(early, 0.5, 3.0) + scale = np.where(early, 60.0, 200.0) + t_event = scale * (-np.log(rng.uniform(size=n)) / np.exp(0.7 * x[:, 1])) ** ( + 1 / shape + ) + t_cens = rng.exponential(300.0, size=n) + return { + "x": x, + "t": np.minimum(t_event, t_cens) + 1e-3, + "e": (t_event <= t_cens).astype(float), + "race": np.where(x[:, 2] > 1, "other", "white"), + "folds": np.arange(n) % 5, + } + + +def standardize(x: np.ndarray, fit: np.ndarray) -> np.ndarray: + """Mean-impute then standardize, with statistics from ``fit`` rows only. + + Args: + x: Raw features, NaN where missing. + fit: Boolean mask of the rows used to estimate the statistics. + + Returns: + Float32 features with no NaN. + """ + mean = np.nanmean(x[fit], axis=0) + x = np.where(np.isnan(x), mean, x) + scale = x[fit].std(axis=0) + scale[scale == 0] = 1.0 + return ((x - mean) / scale).astype(np.float32) + + +def extra_censoring( + t: np.ndarray, e: np.ndarray, points: float, rng: np.random.Generator +) -> tuple[np.ndarray, np.ndarray]: + """Add independent exponential censoring to raise censoring by ``points``. + + The rate solves ``mean(e * exp(-rate * t)) = 1 - (base + points / 100)``. + + Args: + t: Training durations. + e: Training event indicators. + points: Extra censoring in percentage points (0 returns the input). + rng: Random generator for the censoring times. + + Returns: + ``(t', e')`` with ``t' = min(t, C)`` and ``e' = e * 1[t <= C]``. + """ + if points == 0: + return t, e + target = 1.0 - (1.0 - e.mean() + points / 100.0) + lo, hi = 0.0, 1.0 + while np.mean(e * np.exp(-hi * t)) > target: + hi *= 2 + for _ in range(100): + mid = (lo + hi) / 2 + lo, hi = (mid, hi) if np.mean(e * np.exp(-mid * t)) > target else (lo, mid) + c = rng.exponential(1.0 / hi, size=len(t)) + return np.minimum(t, c), e * (t <= c) + + +def km_survival(t: np.ndarray, e: np.ndarray, horizon: float) -> float: + """Kaplan-Meier survival probability at ``horizon``.""" + taus, deaths = np.unique(t[(e == 1) & (t <= horizon)], return_counts=True) + at_risk = len(t) - np.searchsorted(np.sort(t), taus, side="left") + return float(np.prod(1.0 - deaths / at_risk)) if len(taus) else 1.0 + + +def ece( + surv: np.ndarray, t: np.ndarray, e: np.ndarray, horizon: float, bins: int = 20 +) -> float: + """The paper's KM-adjusted ECE at one horizon (equal-frequency bins).""" + edges = np.quantile(surv, np.linspace(0, 1, bins + 1)) + total = 0.0 + for lo, hi in itertools.pairwise(edges): + member = (surv >= lo) & (surv <= hi) + total += member.mean() * abs( + surv[member].mean() - km_survival(t[member], e[member], horizon) + ) + return float(total) + + +def evaluate(surv: np.ndarray, data: dict, subset: np.ndarray) -> dict: + """Paper-protocol metrics for out-of-fold predictions on a subset. + + Args: + surv: Out-of-fold survival at ``HORIZONS``, shape ``(n, 3)``. + data: Output of :func:`load_support2`. + subset: Boolean mask of the patients to score. + + Returns: + ``{"ece@252": ..., "ctd@252": ..., ...}`` for every horizon. + """ + from sksurv.metrics import ( + brier_score, + concordance_index_ipcw, + cumulative_dynamic_auc, + ) + from sksurv.util import Surv + + t, e, folds = data["t"], data["e"], data["folds"] + out = {} + for j, h in enumerate(HORIZONS): + name = f"@{h:g}" + out["ece" + name] = ece(surv[subset, j], t[subset], e[subset], h) + scores = {"brier": [], "ctd": [], "auc": []} + for f in np.unique(folds[subset]): + train = (folds != f) & subset + test = (folds == f) & subset & (t <= t[train].max()) + y_tr = Surv.from_arrays(e[train].astype(bool), t[train]) + y_te = Surv.from_arrays(e[test].astype(bool), t[test]) + s = surv[test, j] + scores["brier"].append(brier_score(y_tr, y_te, s, h)[1][0]) + scores["ctd"].append(concordance_index_ipcw(y_tr, y_te, 1 - s, tau=h)[0]) + scores["auc"].append(cumulative_dynamic_auc(y_tr, y_te, 1 - s, [h])[0][0]) + out.update({k + name: float(np.mean(v)) for k, v in scores.items()}) + return out + + +def cross_validate( + data: dict, k: int, hidden: tuple[int, ...], args, censoring_points: float +) -> np.ndarray: + """Out-of-fold survival predictions of one configuration. + + Args: + data: Output of :func:`load_support2` or :func:`synthetic`. + k: Number of mixture components. + hidden: Encoder hidden layer widths. + args: Parsed command-line arguments. + censoring_points: Extra training censoring (percentage points). + + Returns: + Survival at ``HORIZONS`` for every patient, shape ``(n, 3)``. + """ + n = len(data["t"]) + surv = np.zeros((n, len(HORIZONS))) + for f in range(args.folds): + outer = np.flatnonzero(data["folds"] != f) + rng = np.random.default_rng(10_000 + f) + val = np.zeros(n, bool) + val[rng.choice(outer, size=int(0.15 * len(outer)), replace=False)] = True + train = (data["folds"] != f) & ~val + test = data["folds"] == f + x = standardize(data["x"], train) + t_tr, e_tr = extra_censoring( + data["t"][train], + data["e"][train], + censoring_points, + np.random.default_rng(1_000 + f), + ) + torch.manual_seed(args.seed) + model = DeepCoxMixtures( + None, input_dim=x.shape[1], num_components=k, hidden_dims=hidden + ) + model.fit( + (x[train], t_tr, e_tr), + (x[val], data["t"][val], data["e"][val]), + epochs=args.epochs, + batch_size=128, + learning_rate=1e-3, + patience=3, + seed=args.seed, + ) + surv[test] = model.predict_survival(torch.from_numpy(x[test]), HORIZONS).numpy() + return surv + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--root", help="folder with support2.csv") + parser.add_argument("--synthetic", action="store_true") + parser.add_argument("--components", default="1,2,3,6") + parser.add_argument("--hidden", default="100,100") + parser.add_argument( + "--train-censoring", + default="0", + help="extra training censoring, percentage points", + ) + parser.add_argument( + "--folds", + type=int, + default=5, + help="outer folds to run (5 for the full protocol)", + ) + parser.add_argument("--epochs", type=int, default=50) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--output", default="dcm_support2_results.json") + args = parser.parse_args() + if not args.synthetic and not args.root: + parser.error("pass --root DIR or --synthetic") + data = synthetic() if args.synthetic else load_support2(args.root) + hidden = tuple(int(h) for h in args.hidden.split(",") if h) + scored = np.isin(data["folds"], np.arange(args.folds)) + groups = {"overall": scored, "non-White": scored & (data["race"] != "white")} + results = [] + for points in (float(p) for p in args.train_censoring.split(",")): + for k in (int(c) for c in args.components.split(",")): + start = time.time() + surv = cross_validate(data, k, hidden, args, points) + for name, subset in groups.items(): + metrics = evaluate(surv, data, subset) + results.append( + { + "K": k, + "extra_censoring_pp": points, + "group": name, + **metrics, + "seconds": round(time.time() - start, 1), + } + ) + print( + f"K={k} +{points:g}pp {name:9s} " + + " ".join( + f"{m}={metrics[m]:.4f}" + for m in ("ece@252", "ctd@252", "brier@252", "auc@252") + ) + ) + with open(args.output, "w") as stream: + json.dump(results, stream, indent=1) + print(f"wrote {args.output}") + assert all(math.isfinite(r["ece@252"]) for r in results) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/models/deep_cox_mixtures.py b/pyhealth/models/deep_cox_mixtures.py index bc0b6f4437..d26a16f849 100644 --- a/pyhealth/models/deep_cox_mixtures.py +++ b/pyhealth/models/deep_cox_mixtures.py @@ -271,14 +271,15 @@ def __init__( input_dim = self._infer_input_dim(dataset, feature_key) if input_dim is None: raise ValueError("input_dim is required when dataset is None") - for name, value in (("input_dim", input_dim), ("num_components", - num_components)): + for name, value in ( + ("input_dim", input_dim), + ("num_components", num_components), + ): if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"{name} must be a positive integer") hidden_dims = tuple(hidden_dims) if any( - isinstance(h, bool) or not isinstance(h, int) or h < 1 - for h in hidden_dims + isinstance(h, bool) or not isinstance(h, int) or h < 1 for h in hidden_dims ): raise ValueError("hidden_dims must contain positive integers") if activation not in _ACTIVATIONS: @@ -297,8 +298,10 @@ def __init__( layers: list[nn.Module] = [] width = input_dim for hidden in hidden_dims: - layers += [nn.Linear(width, hidden, bias=use_bias), - _ACTIVATIONS[activation]()] + layers += [ + nn.Linear(width, hidden, bias=use_bias), + _ACTIVATIONS[activation](), + ] width = hidden self.encoder = nn.Sequential(*layers) self.gate = nn.Linear(width, num_components, bias=False) @@ -438,16 +441,18 @@ def _set_baselines(self, curves: list[tuple[Tensor, Tensor]]) -> None: """Pack per-group ``(event_times, cumulative_hazard)`` into (K, M).""" width = 2 + max(len(times) for times, _ in curves) knots = torch.full( - (self.num_components, width), math.inf, dtype=torch.float64, + (self.num_components, width), + math.inf, + dtype=torch.float64, device=self.device, ) hazard = torch.zeros_like(knots) knots[:, 0] = 0.0 for k, (times, cumulative) in enumerate(curves): m = len(times) - knots[k, 1:m + 1] = times - hazard[k, 1:m + 1] = cumulative - hazard[k, m + 1:] = cumulative[-1] if m else 0.0 + knots[k, 1 : m + 1] = times + hazard[k, 1 : m + 1] = cumulative + hazard[k, m + 1 :] = cumulative[-1] if m else 0.0 self._knots, self._cumulative_hazard = knots, hazard # ------------------------------------------------------------- EM pieces @@ -585,10 +590,15 @@ def _mixture_survival( def _collect(self, data: Any) -> tuple[Tensor, Tensor, Tensor]: """Turn ``(x, t, e)``, a mapping or a dataset of samples into tensors.""" if isinstance(data, Mapping): - parts = (data[self.feature_key], data[self.duration_key], - data[self.event_key]) - elif isinstance(data, (tuple, list)) and len(data) == 3 and not ( - isinstance(data[0], Mapping) + parts = ( + data[self.feature_key], + data[self.duration_key], + data[self.event_key], + ) + elif ( + isinstance(data, (tuple, list)) + and len(data) == 3 + and not (isinstance(data[0], Mapping)) ): parts = tuple(data) else: @@ -605,8 +615,11 @@ def stack(key: str) -> Tensor: values.append(torch.as_tensor(value, dtype=torch.float64)) return torch.stack(values) - parts = (stack(self.feature_key), stack(self.duration_key), - stack(self.event_key)) + parts = ( + stack(self.feature_key), + stack(self.duration_key), + stack(self.event_key), + ) x = self._features(parts[0]) duration = _as_vector(parts[1], "duration", self.device) event = _as_vector(parts[2], "event", self.device) @@ -668,9 +681,11 @@ def fit_baselines( continue if not members.any(): members = torch.ones_like(members) - curves.append(breslow_cumulative_hazard( - log_risk[members, k], duration[members], event[members] - )) + curves.append( + breslow_cumulative_hazard( + log_risk[members, k], duration[members], event[members] + ) + ) self._set_baselines(curves) @torch.no_grad() @@ -761,13 +776,15 @@ def fit( >>> sorted(model.fit(data, data, epochs=1, seed=0)) ['train_loss', 'val_nll'] """ - for name, value in (("epochs", epochs), ("batch_size", batch_size), - ("baseline_update_every", baseline_update_every)): + for name, value in ( + ("epochs", epochs), + ("batch_size", batch_size), + ("baseline_update_every", baseline_update_every), + ): if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"{name} must be a positive integer") if patience is not None and ( - isinstance(patience, bool) or not isinstance(patience, int) - or patience < 1 + isinstance(patience, bool) or not isinstance(patience, int) or patience < 1 ): raise ValueError("patience must be a positive integer or None") x, duration, event = self._collect(train_data) @@ -790,7 +807,7 @@ def fit( order = torch.randperm(n, generator=generator).to(self.device) total = 0.0 for batch, start in enumerate(range(0, n, batch_size)): - index = order[start:start + batch_size] + index = order[start : start + batch_size] xb, tb, eb = x[index], duration[index], event[index] log_gate, log_risk = self._network(xb) log_posterior = self._log_posterior(log_gate, log_risk, tb, eb) diff --git a/pyhealth/tasks/survival_time_to_event_support2_dcm.py b/pyhealth/tasks/survival_time_to_event_support2_dcm.py index 55c5f9e29f..600f0f3253 100644 --- a/pyhealth/tasks/survival_time_to_event_support2_dcm.py +++ b/pyhealth/tasks/survival_time_to_event_support2_dcm.py @@ -21,18 +21,43 @@ #: Numeric covariates, in the paper's order. Missing values become NaN. SUPPORT2_DCM_NUMERIC: tuple[str, ...] = ( - "age", "num.co", "meanbp", "wblc", "hrt", "resp", "temp", "pafi", "alb", - "bili", "crea", "sod", "ph", "glucose", "bun", "urine", "adlp", "adls", + "age", + "num.co", + "meanbp", + "wblc", + "hrt", + "resp", + "temp", + "pafi", + "alb", + "bili", + "crea", + "sod", + "ph", + "glucose", + "bun", + "urine", + "adlp", + "adls", ) #: Categorical covariates and their levels. Every level gets a column (no #: reference level is dropped) and a missing value gets all zeros, which is #: what ``pandas.get_dummies`` produces in the paper's code. SUPPORT2_DCM_CATEGORIES: tuple[tuple[str, tuple[str, ...]], ...] = ( ("sex", ("female", "male")), - ("dzgroup", ( - "ARF/MOSF w/Sepsis", "CHF", "COPD", "Cirrhosis", "Colon Cancer", "Coma", - "Lung Cancer", "MOSF w/Malig", - )), + ( + "dzgroup", + ( + "ARF/MOSF w/Sepsis", + "CHF", + "COPD", + "Cirrhosis", + "Colon Cancer", + "Coma", + "Lung Cancer", + "MOSF w/Malig", + ), + ), ("dzclass", ("ARF/MOSF", "COPD/CHF/Cirrhosis", "Cancer", "Coma")), ("income", ("$11-$25k", "$25-$50k", ">$50k", "under $11k")), ("race", ("asian", "black", "hispanic", "other", "white")), @@ -40,8 +65,7 @@ ) #: Names of the 44 entries of the ``features`` vector, in order. SUPPORT2_DCM_FEATURES: tuple[str, ...] = SUPPORT2_DCM_NUMERIC + tuple( - f"{name}={level}" for name, levels in SUPPORT2_DCM_CATEGORIES - for level in levels + f"{name}={level}" for name, levels in SUPPORT2_DCM_CATEGORIES for level in levels ) @@ -138,9 +162,7 @@ def encode(record: Mapping[str, Any], source_id: str) -> dict[str, Any]: raw = record.get(name) level = None if _blank(raw) else str(raw).strip() if level is not None and level not in levels: - raise ValueError( - f"SUPPORT2 record {source_id}: unknown {name} {raw!r}" - ) + raise ValueError(f"SUPPORT2 record {source_id}: unknown {name} {raw!r}") features.extend(1.0 if level == option else 0.0 for option in levels) if name == "race" and level is not None: race = level diff --git a/tests/core/test_deep_cox_mixtures.py b/tests/core/test_deep_cox_mixtures.py index 701e88d0df..b77857e211 100644 --- a/tests/core/test_deep_cox_mixtures.py +++ b/tests/core/test_deep_cox_mixtures.py @@ -32,8 +32,13 @@ def synthetic(n=24, dim=3, seed=0): def fitted_model(k=2, hidden=(4,), seed=0): torch.manual_seed(seed) - model = DeepCoxMixtures(None, input_dim=3, num_components=k, - hidden_dims=hidden, time_grid=[0.5, 1.0, 2.0]) + model = DeepCoxMixtures( + None, + input_dim=3, + num_components=k, + hidden_dims=hidden, + time_grid=[0.5, 1.0, 2.0], + ) x, t, e = synthetic() model.fit_baselines(x, t, e, generator=torch.Generator().manual_seed(seed)) return model, (x, t, e) @@ -42,8 +47,12 @@ def fitted_model(k=2, hidden=(4,), seed=0): class TestInstantiation(unittest.TestCase): def test_from_sample_dataset(self): samples = [ - {"patient_id": f"p{i}", "features": [float(i), 1.0, -1.0, 0.5], - "duration": [1.0 + i], "event": [float(i % 2)]} + { + "patient_id": f"p{i}", + "features": [float(i), 1.0, -1.0, 0.5], + "duration": [1.0 + i], + "event": [float(i % 2)], + } for i in range(4) ] dataset = create_sample_dataset( @@ -65,25 +74,31 @@ def test_from_sample_dataset(self): self.assertTrue(torch.isfinite(out["loss"])) def test_configurations(self): - linear = DeepCoxMixtures(None, input_dim=3, num_components=1, - hidden_dims=()) + linear = DeepCoxMixtures(None, input_dim=3, num_components=1, hidden_dims=()) self.assertEqual(len(linear.encoder), 0) - deep = DeepCoxMixtures(None, input_dim=3, num_components=4, - hidden_dims=(5, 6), activation="relu", - use_bias=True, log_risk_bound=None) + deep = DeepCoxMixtures( + None, + input_dim=3, + num_components=4, + hidden_dims=(5, 6), + activation="relu", + use_bias=True, + log_risk_bound=None, + ) self.assertEqual(deep.risk.out_features, 4) self.assertIsNotNone(deep.encoder[0].bias) self.assertIsNone(deep.risk.bias) def test_invalid_configuration(self): bad = [ - dict(input_dim=None), dict(input_dim=0), dict(input_dim=3, - num_components=0), - dict(input_dim=3, hidden_dims=(0,)), dict(input_dim=3, - activation="gelu"), - dict(input_dim=3, log_risk_bound=-1.0), dict(input_dim=3, - time_grid=[-1.0]), - dict(input_dim=True), + {"input_dim": None}, + {"input_dim": 0}, + {"input_dim": 3, "num_components": 0}, + {"input_dim": 3, "hidden_dims": (0,)}, + {"input_dim": 3, "activation": "gelu"}, + {"input_dim": 3, "log_risk_bound": -1.0}, + {"input_dim": 3, "time_grid": [-1.0]}, + {"input_dim": True}, ] for kwargs in bad: with self.assertRaises(ValueError, msg=str(kwargs)): @@ -91,8 +106,14 @@ def test_invalid_configuration(self): def test_dataset_keys_are_checked(self): dataset = create_sample_dataset( - samples=[{"patient_id": "p", "features": [1.0], "duration": [1.0], - "event": [1.0]}], + samples=[ + { + "patient_id": "p", + "features": [1.0], + "duration": [1.0], + "event": [1.0], + } + ], input_schema={"features": "tensor"}, output_schema={"duration": "tensor", "event": "tensor"}, dataset_name="dcm_keys", @@ -125,8 +146,9 @@ def test_shapes_probabilities_and_gradients(self): self.assertGreater(float(param.grad.abs().sum()), 0.0, name) def test_singleton_batch_and_unfitted_forward(self): - model = DeepCoxMixtures(None, input_dim=3, num_components=2, - hidden_dims=(4,), time_grid=[1.0]) + model = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,), time_grid=[1.0] + ) out = model(features=torch.zeros(1, 3), duration=[2.0], event=[1.0]) self.assertNotIn("y_prob", out) # no baselines yet self.assertEqual(out["mixture_weights"].shape, (1, 2)) @@ -152,10 +174,13 @@ def test_mixture_formula(self): pi = model.predict_latent(x) f = model.predict_log_risk(x).double() cumulative, _ = model._baseline_at(times) # (T, K) - manual = (pi.double().unsqueeze(1) * torch.exp( - -cumulative.unsqueeze(0) * f.exp().unsqueeze(1))).sum(-1) - torch.testing.assert_close(model.predict_survival(x, times).double(), - manual, atol=1e-6, rtol=1e-5) + manual = ( + pi.double().unsqueeze(1) + * torch.exp(-cumulative.unsqueeze(0) * f.exp().unsqueeze(1)) + ).sum(-1) + torch.testing.assert_close( + model.predict_survival(x, times).double(), manual, atol=1e-6, rtol=1e-5 + ) class TestCoxAndBreslow(unittest.TestCase): @@ -177,12 +202,22 @@ def test_partial_likelihood_breslow_ties(self): self.assertAlmostEqual(float(got), expected, places=10) # order of the rows does not matter perm = torch.tensor([4, 2, 0, 3, 1]) - self.assertAlmostEqual(float(cox_partial_log_likelihood( - self.f[perm], self.t[perm], self.e[perm])), expected, places=10) - self.assertEqual(float(cox_partial_log_likelihood( - self.f, self.t, torch.zeros(5))), 0.0) - self.assertEqual(float(cox_partial_log_likelihood( - torch.zeros(0), torch.zeros(0), torch.zeros(0))), 0.0) + self.assertAlmostEqual( + float(cox_partial_log_likelihood(self.f[perm], self.t[perm], self.e[perm])), + expected, + places=10, + ) + self.assertEqual( + float(cox_partial_log_likelihood(self.f, self.t, torch.zeros(5))), 0.0 + ) + self.assertEqual( + float( + cox_partial_log_likelihood( + torch.zeros(0), torch.zeros(0), torch.zeros(0) + ) + ), + 0.0, + ) def test_breslow_hand_computed(self): r = self.f.exp() @@ -192,29 +227,29 @@ def test_breslow_hand_computed(self): h3 = h2 + 1 / r[3:].sum() self.assertEqual(times.tolist(), [1.0, 2.0, 3.0]) torch.testing.assert_close(hazard, torch.stack([h1, h2, h3])) - empty_t, empty_h = breslow_cumulative_hazard(self.f, self.t, - torch.zeros(5)) + empty_t, empty_h = breslow_cumulative_hazard(self.f, self.t, torch.zeros(5)) self.assertEqual(len(empty_t), 0) self.assertEqual(len(empty_h), 0) def test_single_component_is_neural_cox(self): torch.manual_seed(1) - model = DeepCoxMixtures(None, input_dim=3, num_components=1, - hidden_dims=(4,)) + model = DeepCoxMixtures(None, input_dim=3, num_components=1, hidden_dims=(4,)) x, t, e = synthetic() model.fit_baselines(x, t, e) out = model(features=x, duration=t, event=e) torch.testing.assert_close(out["mixture_weights"], torch.ones(len(x), 1)) expected = -cox_partial_log_likelihood(out["log_risk"][:, 0], t, e) - torch.testing.assert_close(out["loss"].double(), - expected.double() / len(x)) + torch.testing.assert_close(out["loss"].double(), expected.double() / len(x)) # baseline is the Breslow estimate with the network's hazard ratios times, hazard = breslow_cumulative_hazard(out["log_risk"][:, 0], t, e) f = model.predict_log_risk(x)[:, 0].double() surv = model.predict_survival(x, times).double() torch.testing.assert_close( - surv, torch.exp(-hazard.unsqueeze(0) * f.exp().unsqueeze(1)), - atol=1e-6, rtol=1e-5) + surv, + torch.exp(-hazard.unsqueeze(0) * f.exp().unsqueeze(1)), + atol=1e-6, + rtol=1e-5, + ) class TestEStep(unittest.TestCase): @@ -225,37 +260,43 @@ def test_posterior_matches_manual_and_uses_censoring(self): f = log_risk.double() log_s = -cumulative * f.exp() log_d = f + rate.log() + log_s - ll = torch.where(e.bool().unsqueeze(1), log_d, log_s).clamp_min( - math.log(1e-10)) + ll = torch.where(e.bool().unsqueeze(1), log_d, log_s).clamp_min(math.log(1e-10)) manual = torch.softmax(log_gate.double() + ll, dim=-1) - got = model._log_posterior(log_gate, log_risk, t.double(), - e.double()).exp() + got = model._log_posterior(log_gate, log_risk, t.double(), e.double()).exp() torch.testing.assert_close(got, manual) # The same row gets a different posterior as an event or censored. - as_event = model._log_posterior(log_gate[:1], log_risk[:1], - t[:1].double(), torch.ones(1)) - as_censored = model._log_posterior(log_gate[:1], log_risk[:1], - t[:1].double(), torch.zeros(1)) + as_event = model._log_posterior( + log_gate[:1], log_risk[:1], t[:1].double(), torch.ones(1) + ) + as_censored = model._log_posterior( + log_gate[:1], log_risk[:1], t[:1].double(), torch.zeros(1) + ) self.assertFalse(torch.allclose(as_event, as_censored)) def test_interpolation_and_support(self): - model = DeepCoxMixtures(None, input_dim=1, num_components=1, - hidden_dims=()) - model._set_baselines([(torch.tensor([1.0, 3.0], dtype=torch.float64), - torch.tensor([0.2, 0.6], dtype=torch.float64))]) - cumulative, rate = model._baseline_at(torch.tensor([0.0, 0.5, 2.0, 3.0, - 9.0])) - torch.testing.assert_close(cumulative[:, 0], torch.tensor( - [0.0, 0.1, 0.4, 0.6, 0.6], dtype=torch.float64)) - torch.testing.assert_close(rate[:, 0], torch.tensor( - [0.2, 0.2, 0.2, 0.2, 0.0], dtype=torch.float64)) + model = DeepCoxMixtures(None, input_dim=1, num_components=1, hidden_dims=()) + model._set_baselines( + [ + ( + torch.tensor([1.0, 3.0], dtype=torch.float64), + torch.tensor([0.2, 0.6], dtype=torch.float64), + ) + ] + ) + cumulative, rate = model._baseline_at(torch.tensor([0.0, 0.5, 2.0, 3.0, 9.0])) + torch.testing.assert_close( + cumulative[:, 0], + torch.tensor([0.0, 0.1, 0.4, 0.6, 0.6], dtype=torch.float64), + ) + torch.testing.assert_close( + rate[:, 0], torch.tensor([0.2, 0.2, 0.2, 0.2, 0.0], dtype=torch.float64) + ) class TestEdgeCases(unittest.TestCase): def test_zero_event_and_empty_components(self): torch.manual_seed(0) - model = DeepCoxMixtures(None, input_dim=3, num_components=3, - hidden_dims=()) + model = DeepCoxMixtures(None, input_dim=3, num_components=3, hidden_dims=()) x, t, _ = synthetic() model.fit_baselines(x, t, torch.zeros(len(t))) # nobody has an event surv = model.predict_survival(x, [1.0, 4.0]) @@ -279,8 +320,7 @@ def test_zero_event_and_empty_components(self): self.assertTrue(torch.isfinite(model.predict_survival(x, [2.0])).all()) def test_first_fit_with_empty_component_uses_everyone(self): - model = DeepCoxMixtures(None, input_dim=2, num_components=2, - hidden_dims=()) + model = DeepCoxMixtures(None, input_dim=2, num_components=2, hidden_dims=()) with torch.no_grad(): model.gate.weight.copy_(torch.tensor([[50.0, 0.0], [0.0, 0.0]])) x = torch.ones(6, 2) @@ -294,20 +334,24 @@ def test_state_dict_round_trip(self): with tempfile.TemporaryDirectory() as root: path = os.path.join(root, "dcm.pt") torch.save(model.state_dict(), path) - restored = DeepCoxMixtures(None, input_dim=3, num_components=2, - hidden_dims=(4,)) + restored = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,) + ) self.assertFalse(restored.is_fitted) restored.load_state_dict(torch.load(path)) self.assertFalse(os.path.exists(root)) - torch.testing.assert_close(restored.predict_survival(x, [0.5, 2.0]), - model.predict_survival(x, [0.5, 2.0])) + torch.testing.assert_close( + restored.predict_survival(x, [0.5, 2.0]), + model.predict_survival(x, [0.5, 2.0]), + ) torch.testing.assert_close(restored.time_grid, model.time_grid) - torch.testing.assert_close(restored(features=x)["y_prob"], - model(features=x)["y_prob"]) + torch.testing.assert_close( + restored(features=x)["y_prob"], model(features=x)["y_prob"] + ) with self.assertRaises(ValueError): - DeepCoxMixtures(None, input_dim=3, num_components=3, - hidden_dims=(4,)).set_extra_state( - model.get_extra_state()) + DeepCoxMixtures( + None, input_dim=3, num_components=3, hidden_dims=(4,) + ).set_extra_state(model.get_extra_state()) def test_invalid_inputs(self): model, (x, t, e) = fitted_model(k=2) @@ -343,11 +387,13 @@ def test_invalid_inputs(self): class TestFit(unittest.TestCase): def test_fit_tuple_with_validation(self): torch.manual_seed(0) - model = DeepCoxMixtures(None, input_dim=3, num_components=2, - hidden_dims=(4,), time_grid=[1.0, 2.0]) + model = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,), time_grid=[1.0, 2.0] + ) x, t, e = synthetic(n=32) - history = model.fit((x, t, e), (x[:8], t[:8], e[:8]), epochs=3, - batch_size=8, patience=1, seed=0) + history = model.fit( + (x, t, e), (x[:8], t[:8], e[:8]), epochs=3, batch_size=8, patience=1, seed=0 + ) self.assertLessEqual(len(history["train_loss"]), 3) self.assertEqual(len(history["val_nll"]), len(history["train_loss"])) self.assertTrue(all(math.isfinite(v) for v in history["val_nll"])) @@ -361,20 +407,32 @@ def test_fit_is_reproducible_with_seed(self): preds = [] for _ in range(2): torch.manual_seed(3) - model = DeepCoxMixtures(None, input_dim=3, num_components=2, - hidden_dims=(4,)) - model.fit({"features": x, "duration": t, "event": e}, epochs=2, - batch_size=10, seed=11) + model = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,) + ) + model.fit( + {"features": x, "duration": t, "event": e}, + epochs=2, + batch_size=10, + seed=11, + ) preds.append(model.predict_survival(x, [1.0, 3.0])) torch.testing.assert_close(preds[0], preds[1]) def test_fit_sample_dataset(self): x, t, e = synthetic(n=12) - samples = [{"patient_id": str(i), "features": x[i].tolist(), - "duration": [float(t[i])], "event": [float(e[i])]} - for i in range(12)] + samples = [ + { + "patient_id": str(i), + "features": x[i].tolist(), + "duration": [float(t[i])], + "event": [float(e[i])], + } + for i in range(12) + ] dataset = create_sample_dataset( - samples=samples, input_schema={"features": "tensor"}, + samples=samples, + input_schema={"features": "tensor"}, output_schema={"duration": "tensor", "event": "tensor"}, dataset_name="dcm_fit", ) diff --git a/tests/core/test_survival_time_to_event_support2_dcm.py b/tests/core/test_survival_time_to_event_support2_dcm.py index bf04fb5841..3b45260b1f 100644 --- a/tests/core/test_survival_time_to_event_support2_dcm.py +++ b/tests/core/test_survival_time_to_event_support2_dcm.py @@ -25,20 +25,34 @@ def row(sno, **overrides): """One synthetic SUPPORT2 row with every column the task reads.""" values = {"sno": str(sno)} - values.update({name: str(10 + j + sno) for j, name in - enumerate(SUPPORT2_DCM_NUMERIC)}) - values.update(sex="female", dzgroup="CHF", dzclass="COPD/CHF/Cirrhosis", - income="$25-$50k", race="black", ca="no", - **{"d.time": str(5 * sno), "death": str(sno % 2)}) + values.update( + {name: str(10 + j + sno) for j, name in enumerate(SUPPORT2_DCM_NUMERIC)} + ) + values.update( + sex="female", + dzgroup="CHF", + dzclass="COPD/CHF/Cirrhosis", + income="$25-$50k", + race="black", + ca="no", + **{"d.time": str(5 * sno), "death": str(sno % 2)}, + ) values.update(overrides) return values def patient(rows): events = [ - {"patient_id": r["sno"], "event_type": "support2", "timestamp": None, - **{f"support2/{k}": (v if v != "" else None) - for k, v in r.items() if k != "sno"}} + { + "patient_id": r["sno"], + "event_type": "support2", + "timestamp": None, + **{ + f"support2/{k}": (v if v != "" else None) + for k, v in r.items() + if k != "sno" + }, + } for r in rows ] return Patient(rows[0]["sno"] if rows else "0", pl.DataFrame(events)) @@ -48,13 +62,11 @@ class TestSupport2DCMTask(unittest.TestCase): def test_schema_and_feature_names(self): task = SurvivalTimeToEventSupport2DCM() self.assertEqual(task.input_schema, {"features": "tensor"}) - self.assertEqual(task.output_schema, - {"duration": "tensor", "event": "tensor"}) + self.assertEqual(task.output_schema, {"duration": "tensor", "event": "tensor"}) self.assertEqual(len(SUPPORT2_DCM_NUMERIC), 18) self.assertEqual(sum(len(v) for _, v in SUPPORT2_DCM_CATEGORIES), 26) self.assertEqual(len(SUPPORT2_DCM_FEATURES), 44) - self.assertEqual(SUPPORT2_DCM_FEATURES[18:20], - ("sex=female", "sex=male")) + self.assertEqual(SUPPORT2_DCM_FEATURES[18:20], ("sex=female", "sex=male")) self.assertEqual(len(set(SUPPORT2_DCM_FEATURES)), 44) def test_encoding_of_a_patient(self): @@ -62,13 +74,21 @@ def test_encoding_of_a_patient(self): (sample,) = SurvivalTimeToEventSupport2DCM()(patient([r])) self.assertEqual(sample["patient_id"], "3") features = sample["features"] - self.assertEqual(features[:18], - [float(r[name]) for name in SUPPORT2_DCM_NUMERIC]) - hot = {SUPPORT2_DCM_FEATURES[j] for j in range(18, 44) - if features[j] == 1.0} - self.assertEqual(hot, {"sex=female", "dzgroup=CHF", - "dzclass=COPD/CHF/Cirrhosis", "income=$25-$50k", - "race=black", "ca=no"}) + self.assertEqual( + features[:18], [float(r[name]) for name in SUPPORT2_DCM_NUMERIC] + ) + hot = {SUPPORT2_DCM_FEATURES[j] for j in range(18, 44) if features[j] == 1.0} + self.assertEqual( + hot, + { + "sex=female", + "dzgroup=CHF", + "dzclass=COPD/CHF/Cirrhosis", + "income=$25-$50k", + "race=black", + "ca=no", + }, + ) self.assertEqual(sum(features[18:]), 6.0) self.assertEqual(sample["duration"], [15.0]) self.assertEqual(sample["event"], [1.0]) @@ -79,20 +99,30 @@ def test_missing_values(self): (sample,) = SurvivalTimeToEventSupport2DCM()(patient([r])) features = sample["features"] self.assertTrue(math.isnan(features[SUPPORT2_DCM_FEATURES.index("alb")])) - income = [j for j, n in enumerate(SUPPORT2_DCM_FEATURES) - if n.startswith(("income=", "race="))] + income = [ + j + for j, n in enumerate(SUPPORT2_DCM_FEATURES) + if n.startswith(("income=", "race=")) + ] self.assertEqual([features[j] for j in income], [0.0] * 9) self.assertEqual(sample["race"], "missing") self.assertEqual(sample["event"], [0.0]) # encode() also accepts NaN floats for missing values direct = SurvivalTimeToEventSupport2DCM.encode( - {**row(2), "alb": float("nan")}, "2") + {**row(2), "alb": float("nan")}, "2" + ) self.assertTrue(math.isnan(direct["features"][8])) def test_invalid_records(self): task = SurvivalTimeToEventSupport2DCM() - bad = [dict(age="old"), dict(dzgroup="Flu"), dict(**{"d.time": "0"}), - dict(**{"d.time": ""}), dict(death="2"), dict(age="inf")] + bad = [ + {"age": "old"}, + {"dzgroup": "Flu"}, + dict(**{"d.time": "0"}), + dict(**{"d.time": ""}), + {"death": "2"}, + {"age": "inf"}, + ] for overrides in bad: with self.assertRaises(ValueError, msg=str(overrides)): task(patient([row(1, **overrides)])) @@ -114,13 +144,16 @@ def test_samples_train_deep_cox_mixtures(self): for s, features in zip(samples, x.tolist()): s["features"] = features dataset = create_sample_dataset( - samples=samples, input_schema=task.input_schema, - output_schema=task.output_schema, dataset_name="support2_dcm", + samples=samples, + input_schema=task.input_schema, + output_schema=task.output_schema, + dataset_name="support2_dcm", ) self.assertEqual(dataset[0]["race"], "black") torch.manual_seed(0) - model = DeepCoxMixtures(dataset, num_components=2, hidden_dims=(4,), - time_grid=[10.0, 20.0]) + model = DeepCoxMixtures( + dataset, num_components=2, hidden_dims=(4,), time_grid=[10.0, 20.0] + ) self.assertEqual(model.input_dim, 44) model.fit(dataset, epochs=1, batch_size=3, seed=0) batch = next(iter(get_dataloader(dataset, batch_size=6, shuffle=False))) From ac5e971ca328c21e64a017012739cab02973d412 Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 3/6] DeepCoxMixtures.fit: use only the local generator (no global seeding) Co-Authored-By: Claude Opus 5.5 --- pyhealth/models/deep_cox_mixtures.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pyhealth/models/deep_cox_mixtures.py b/pyhealth/models/deep_cox_mixtures.py index d26a16f849..3f9b48c63d 100644 --- a/pyhealth/models/deep_cox_mixtures.py +++ b/pyhealth/models/deep_cox_mixtures.py @@ -792,7 +792,6 @@ def fit( generator = torch.Generator() if seed is not None: generator.manual_seed(seed) - torch.manual_seed(seed) optimizer = torch.optim.Adam( self.parameters(), lr=learning_rate, weight_decay=weight_decay ) From dfde5cf9592d70808ef2375bb419be905b058958 Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 4/6] Test Trainer inference after fit; note example metric dependency Co-Authored-By: Claude Opus 5.5 --- .../support2_survival_deep_cox_mixtures.py | 4 ++- tests/core/test_deep_cox_mixtures.py | 30 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/examples/support2_survival_deep_cox_mixtures.py b/examples/support2_survival_deep_cox_mixtures.py index cafcd95c4b..140bebfc1b 100644 --- a/examples/support2_survival_deep_cox_mixtures.py +++ b/examples/support2_survival_deep_cox_mixtures.py @@ -34,6 +34,9 @@ Usage ----- +The paper's metrics use scikit-survival (``pip install scikit-survival``), +which this example needs in both modes. + Synthetic data (a two-group population with crossing survival curves, so a mixture should help; under a minute on a CPU):: @@ -42,7 +45,6 @@ SUPPORT2 (``root`` holds ``support2.csv`` with an ``sno`` column; the UCI file https://archive.ics.uci.edu/dataset/880/support2 calls it ``id``):: - pip install scikit-survival python examples/support2_survival_deep_cox_mixtures.py --root data/support2 python examples/support2_survival_deep_cox_mixtures.py --root data/support2 \ --components 1,3 --train-censoring 0,10,20,30 diff --git a/tests/core/test_deep_cox_mixtures.py b/tests/core/test_deep_cox_mixtures.py index b77857e211..623a70c0b7 100644 --- a/tests/core/test_deep_cox_mixtures.py +++ b/tests/core/test_deep_cox_mixtures.py @@ -419,6 +419,36 @@ def test_fit_is_reproducible_with_seed(self): preds.append(model.predict_survival(x, [1.0, 3.0])) torch.testing.assert_close(preds[0], preds[1]) + def test_trainer_inference_after_fit(self): + from pyhealth.trainer import Trainer + + x, t, e = synthetic(n=12) + samples = [ + { + "patient_id": str(i), + "features": x[i].tolist(), + "duration": [float(t[i])], + "event": [float(e[i])], + } + for i in range(12) + ] + dataset = create_sample_dataset( + samples=samples, + input_schema={"features": "tensor"}, + output_schema={"duration": "tensor", "event": "tensor"}, + dataset_name="dcm_trainer", + ) + model = DeepCoxMixtures( + dataset, num_components=2, hidden_dims=(4,), time_grid=[1.0, 2.0] + ) + model.fit(dataset, epochs=1, batch_size=6, seed=0) + trainer = Trainer(model=model, enable_logging=False) + loader = get_dataloader(dataset, batch_size=6, shuffle=False) + y_true, y_prob, loss = trainer.inference(loader) + self.assertEqual(y_true.shape, (12, 2)) + self.assertEqual(y_prob.shape, (12, 2)) + self.assertTrue(math.isfinite(loss)) + def test_fit_sample_dataset(self): x, t, e = synthetic(n=12) samples = [ From c13e8dbfd7ef9e403ea6d98340fe344408c43ee6 Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 5/6] DeepCoxMixtures: address review findings - fit(seed=None) now draws its generator seed from torch's global RNG - refit baselines after the last batch of each epoch (baseline_update_every > 1) - keep a constructor time_grid when loading a checkpoint; clearer state errors - accept NumPy integers; validate hidden_dims type and input_dim vs dataset - tests for early stopping/restore, sparse refits, seeding, grid loading - example: validate extra-censoring range Co-Authored-By: Claude Opus 5.5 --- .../support2_survival_deep_cox_mixtures.py | 16 ++-- pyhealth/models/deep_cox_mixtures.py | 90 +++++++++++++------ tests/core/test_deep_cox_mixtures.py | 80 +++++++++++++++++ 3 files changed, 154 insertions(+), 32 deletions(-) diff --git a/examples/support2_survival_deep_cox_mixtures.py b/examples/support2_survival_deep_cox_mixtures.py index 140bebfc1b..1a88ac035b 100644 --- a/examples/support2_survival_deep_cox_mixtures.py +++ b/examples/support2_survival_deep_cox_mixtures.py @@ -73,12 +73,9 @@ Calibration differences between K values are small and not consistent across K (ECE@252 0.014-0.021), so this run does not show that more components improve calibration. With extra training censoring, K = 3 kept an ECE@252 -no higher than K = 1 at every level in this single draw. In the project's -full study (3 seeds / 3 censoring draws, paired bootstrap), the -discrimination gain of K >= 2 over K = 1 was significant, while ECE -differences were within sampling noise. The synthetic run (two groups with -crossing curves) shows the expected calibration gain of K >= 2 -(ECE@252 0.056 for K = 1 vs 0.029-0.033). +no higher than K = 1 at every level in this single draw. The synthetic run +(two groups with crossing curves) shows the expected calibration gain of +K >= 2 (ECE@252 0.056 for K = 1 vs 0.029-0.033). """ import argparse @@ -183,9 +180,16 @@ def extra_censoring( Returns: ``(t', e')`` with ``t' = min(t, C)`` and ``e' = e * 1[t <= C]``. + + Raises: + ValueError: If ``points`` is negative or would censor every event. """ if points == 0: return t, e + if not 0 < points < 100.0 * e.mean(): + raise ValueError( + f"extra censoring must be in (0, {100 * e.mean():.1f}) points here" + ) target = 1.0 - (1.0 - e.mean() + points / 100.0) lo, hi = 0.0, 1.0 while np.mean(e * np.exp(-hi * t)) > target: diff --git a/pyhealth/models/deep_cox_mixtures.py b/pyhealth/models/deep_cox_mixtures.py index 3f9b48c63d..728ac2859c 100644 --- a/pyhealth/models/deep_cox_mixtures.py +++ b/pyhealth/models/deep_cox_mixtures.py @@ -23,6 +23,7 @@ import copy import math +import numbers from collections.abc import Mapping, Sequence from typing import Any @@ -40,12 +41,23 @@ "relu6": nn.ReLU6, "tanh": nn.Tanh, } -# Smallest per-group likelihood used in the E-step. The reference code floors -# probabilities at the same value so that one group with zero density (for -# example an event after that group's last event time) cannot produce NaNs. +# Smallest per-group likelihood used in the E-step, so that a group with zero +# density (for example an event after that group's last event time) cannot +# produce NaNs. The authors' code floors the joint gate x likelihood at the +# same value; flooring each group's likelihood instead means a row where every +# group is floored falls back to the gate probabilities. _LIKELIHOOD_FLOOR = 1e-10 +def _is_positive_int(value: Any) -> bool: + """Whether ``value`` is a positive integer (NumPy integers included).""" + return ( + isinstance(value, numbers.Integral) + and not isinstance(value, bool) + and value >= 1 + ) + + def _as_vector(value: Any, name: str, device: torch.device) -> Tensor: """Convert a label field of shape (n,) or (n, 1) to a float64 vector.""" if isinstance(value, tuple): @@ -213,7 +225,9 @@ class DeepCoxMixtures(BaseModel): duration_key: Output field with strictly positive times. event_key: Output field with 1 for an event and 0 for censoring. time_grid: Times at which ``forward`` returns ``y_prob`` (survival - probabilities) once baselines are fitted. Optional. + probabilities) once baselines are fitted. Optional. It is saved + in ``state_dict``; loading a checkpoint keeps a grid given here + and otherwise adopts the checkpoint's grid. Examples: >>> import torch @@ -267,20 +281,27 @@ def __init__( raise ValueError( f"output key {key!r} is not in dataset.output_schema" ) - if input_dim is None: - input_dim = self._infer_input_dim(dataset, feature_key) + inferred = self._infer_input_dim(dataset, feature_key) + if input_dim is not None and input_dim != inferred: + raise ValueError( + f"input_dim={input_dim} but the dataset's features have " + f"width {inferred}" + ) + input_dim = inferred if input_dim is None: raise ValueError("input_dim is required when dataset is None") for name, value in ( ("input_dim", input_dim), ("num_components", num_components), ): - if isinstance(value, bool) or not isinstance(value, int) or value < 1: + if not _is_positive_int(value): raise ValueError(f"{name} must be a positive integer") - hidden_dims = tuple(hidden_dims) - if any( - isinstance(h, bool) or not isinstance(h, int) or h < 1 for h in hidden_dims + if isinstance(hidden_dims, (str, bytes)) or not isinstance( + hidden_dims, Sequence ): + raise TypeError("hidden_dims must be a sequence of positive integers") + hidden_dims = tuple(int(h) if _is_positive_int(h) else h for h in hidden_dims) + if not all(_is_positive_int(h) for h in hidden_dims): raise ValueError("hidden_dims must contain positive integers") if activation not in _ACTIVATIONS: raise ValueError(f"activation must be one of {sorted(_ACTIVATIONS)}") @@ -289,8 +310,8 @@ def __init__( ): raise ValueError("log_risk_bound must be positive and finite, or None") - self.input_dim = input_dim - self.num_components = num_components + self.input_dim = int(input_dim) + self.num_components = int(num_components) self.hidden_dims = hidden_dims self.activation = activation self.log_risk_bound = log_risk_bound @@ -389,9 +410,12 @@ def set_extra_state(self, state: Mapping[str, Tensor | None]) -> None: Args: state: Output of :meth:`get_extra_state`. + A ``time_grid`` given to the constructor is kept; a model built + without one adopts the saved grid. + Raises: - ValueError: If the saved baselines are incomplete or were fit for - a different number of components. + ValueError: If the saved baselines are incomplete, malformed, or + were fit for a different number of components. """ knots, hazard = state.get("knots"), state.get("cumulative_hazard") if (knots is None) != (hazard is None): @@ -399,11 +423,17 @@ def set_extra_state(self, state: Mapping[str, Tensor | None]) -> None: if knots is not None: knots = knots.to(device=self.device, dtype=torch.float64) hazard = hazard.to(device=self.device, dtype=torch.float64) - if knots.shape != hazard.shape or knots.shape[0] != self.num_components: - raise ValueError("Saved baselines do not match num_components") + if knots.ndim != 2 or knots.shape != hazard.shape: + raise ValueError("Saved knots and cumulative hazards differ in shape") + if knots.shape[0] != self.num_components: + raise ValueError( + f"Saved baselines have {knots.shape[0]} components, " + f"the model has {self.num_components}" + ) self._knots, self._cumulative_hazard = knots, hazard - if state.get("time_grid") is not None: - self.time_grid = state["time_grid"].to(self.device) + saved_grid = state.get("time_grid") + if saved_grid is not None and saved_grid.numel() and not self.time_grid.numel(): + self.time_grid = saved_grid.to(self.device) def _apply(self, fn: Any, recurse: bool = True) -> "DeepCoxMixtures": """Move the baseline tensors along with the module (``.to()`` etc.).""" @@ -536,7 +566,8 @@ def forward(self, **kwargs: Any) -> dict[str, Tensor]: also ``survival`` and ``y_prob``: survival at ``time_grid``, (batch, T). With labels, also ``loss`` (the negative Monte Carlo EM objective per patient, using responsibilities from the current - baselines), ``posterior`` (responsibilities, (batch, K)) and + baselines; it uses sampled assignments, so it varies between + calls), ``posterior`` (responsibilities, (batch, K)) and ``y_true`` ((batch, 2): duration, event). """ if self.feature_key not in kwargs: @@ -743,8 +774,10 @@ def fit( Each epoch shuffles the training data. For every mini-batch: E-step responsibilities under the current baselines, hard assignments sampled from them, one Adam step on the negative Q-function, and - (every ``baseline_update_every`` batches) Breslow baselines refit on - the full training set. With ``val_data``, training stops after + Breslow baselines refit on the full training set (after every + ``baseline_update_every``-th batch of the epoch and always after its + last batch, so validation and predictions use baselines estimated + with the current weights). With ``val_data``, training stops after ``patience`` epochs without a lower validation negative log-likelihood, and the best weights and baselines are restored. @@ -760,8 +793,11 @@ def fit( patience: Early-stopping patience in epochs. ``None`` or no ``val_data`` trains for all epochs. baseline_update_every: Refit the baselines after every this many - mini-batches. The authors' code refits after every batch. - seed: Seed for shuffling and the sampled assignments. + mini-batches (and after the last batch of each epoch). The + authors' code refits after every batch. + seed: Seed for shuffling and the sampled assignments. With + ``None`` they are drawn from torch's global random state, so + ``torch.manual_seed`` controls them. Returns: History with ``train_loss`` (mean M-step loss per epoch) and, @@ -790,8 +826,9 @@ def fit( x, duration, event = self._collect(train_data) validation = None if val_data is None else self._collect(val_data) generator = torch.Generator() - if seed is not None: - generator.manual_seed(seed) + if seed is None: + seed = int(torch.randint(2**62, (1,))) + generator.manual_seed(seed) optimizer = torch.optim.Adam( self.parameters(), lr=learning_rate, weight_decay=weight_decay ) @@ -805,6 +842,7 @@ def fit( self.train() order = torch.randperm(n, generator=generator).to(self.device) total = 0.0 + last_batch = (n - 1) // batch_size for batch, start in enumerate(range(0, n, batch_size)): index = order[start : start + batch_size] xb, tb, eb = x[index], duration[index], event[index] @@ -818,7 +856,7 @@ def fit( loss.backward() optimizer.step() total += float(loss.detach()) * len(index) - if batch % baseline_update_every == 0: + if batch % baseline_update_every == 0 or batch == last_batch: self.fit_baselines(x, duration, event, generator) history["train_loss"].append(total / n) self.eval() diff --git a/tests/core/test_deep_cox_mixtures.py b/tests/core/test_deep_cox_mixtures.py index 623a70c0b7..fb8e45da0c 100644 --- a/tests/core/test_deep_cox_mixtures.py +++ b/tests/core/test_deep_cox_mixtures.py @@ -10,6 +10,7 @@ import tempfile import unittest +import numpy as np import torch from pyhealth.datasets import create_sample_dataset, get_dataloader @@ -103,6 +104,16 @@ def test_invalid_configuration(self): for kwargs in bad: with self.assertRaises(ValueError, msg=str(kwargs)): DeepCoxMixtures(None, **kwargs) + for hidden in (100, "64"): + with self.assertRaises(TypeError): + DeepCoxMixtures(None, input_dim=3, hidden_dims=hidden) + model = DeepCoxMixtures( + None, + input_dim=np.int64(3), + num_components=np.int64(2), + hidden_dims=[np.int64(4)], + ) + self.assertEqual((model.input_dim, model.num_components), (3, 2)) def test_dataset_keys_are_checked(self): dataset = create_sample_dataset( @@ -122,6 +133,8 @@ def test_dataset_keys_are_checked(self): DeepCoxMixtures(dataset, feature_key="x") with self.assertRaises(ValueError): DeepCoxMixtures(dataset, event_key="status") + with self.assertRaises(ValueError): + DeepCoxMixtures(dataset, input_dim=5) # dataset width is 1 class TestForward(unittest.TestCase): @@ -353,6 +366,26 @@ def test_state_dict_round_trip(self): None, input_dim=3, num_components=3, hidden_dims=(4,) ).set_extra_state(model.get_extra_state()) + def test_time_grid_rules_when_loading(self): + model, _ = fitted_model(k=2) # built with time_grid [0.5, 1, 2] + state = model.state_dict() + other = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,), time_grid=[7.0] + ) + other.load_state_dict(state) + torch.testing.assert_close(other.time_grid, torch.tensor([7.0])) + no_grid = DeepCoxMixtures(None, input_dim=3, num_components=2, hidden_dims=(4,)) + keeps = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,), time_grid=[3.0] + ) + keeps.load_state_dict(no_grid.state_dict()) + torch.testing.assert_close(keeps.time_grid, torch.tensor([3.0])) + bad = model.get_extra_state() + with self.assertRaises(ValueError): + model.set_extra_state({**bad, "cumulative_hazard": None}) + with self.assertRaises(ValueError): + model.set_extra_state({**bad, "knots": bad["knots"][:, :2]}) + def test_invalid_inputs(self): model, (x, t, e) = fitted_model(k=2) with self.assertRaises(ValueError): @@ -449,6 +482,53 @@ def test_trainer_inference_after_fit(self): self.assertEqual(y_prob.shape, (12, 2)) self.assertTrue(math.isfinite(loss)) + def test_unseeded_fit_follows_global_seed(self): + x, t, e = synthetic(n=20) + + def run(global_seed): + torch.manual_seed(0) + model = DeepCoxMixtures( + None, input_dim=3, num_components=2, hidden_dims=(4,) + ) + torch.manual_seed(global_seed) + model.fit((x, t, e), epochs=2, batch_size=5) + return model.predict_survival(x, [1.0, 3.0]) + + torch.testing.assert_close(run(1), run(1)) + self.assertFalse(torch.allclose(run(1), run(2))) + + def test_early_stopping_restores_best_epoch(self): + x, t, e = synthetic(n=40, seed=1) + xv, tv, ev = synthetic(n=20, seed=2) + torch.manual_seed(0) + model = DeepCoxMixtures(None, input_dim=3, num_components=2, hidden_dims=(8,)) + history = model.fit( + (x, t, e), + (xv, tv, -ev + 1), # unrelated validation labels + epochs=30, + batch_size=10, + learning_rate=0.05, + patience=1, + seed=0, + ) + self.assertLess(len(history["val_nll"]), 30) # stopped early + self.assertAlmostEqual( + model.negative_log_likelihood(xv, tv, -ev + 1), + min(history["val_nll"]), + places=6, + ) + + def test_baselines_match_final_weights_with_sparse_refits(self): + x, t, e = synthetic(n=25) + torch.manual_seed(0) + model = DeepCoxMixtures(None, input_dim=3, num_components=1, hidden_dims=(4,)) + # 5 batches per epoch, refit every 3rd: the last batch must still refit. + model.fit((x, t, e), epochs=2, batch_size=5, baseline_update_every=3, seed=0) + times, hazard = breslow_cumulative_hazard(model.predict_log_risk(x)[:, 0], t, e) + m = len(times) + torch.testing.assert_close(model._knots[0, 1 : m + 1], times.double()) + torch.testing.assert_close(model._cumulative_hazard[0, 1 : m + 1], hazard) + def test_fit_sample_dataset(self): x, t, e = synthetic(n=12) samples = [ From d820c46d26bb94d968881fe06496f6a1311cd26c Mon Sep 17 00:00:00 2001 From: Xinyi Liu Date: Fri, 27 Nov 2026 16:03:16 -0600 Subject: [PATCH 6/6] Add contributor name Co-Authored-By: Claude Opus 5.5 --- examples/support2_survival_deep_cox_mixtures.py | 2 +- pyhealth/models/deep_cox_mixtures.py | 2 +- pyhealth/tasks/survival_time_to_event_support2_dcm.py | 2 +- tests/core/test_deep_cox_mixtures.py | 2 +- tests/core/test_survival_time_to_event_support2_dcm.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/support2_survival_deep_cox_mixtures.py b/examples/support2_survival_deep_cox_mixtures.py index 1a88ac035b..8fe3e48a3f 100644 --- a/examples/support2_survival_deep_cox_mixtures.py +++ b/examples/support2_survival_deep_cox_mixtures.py @@ -1,6 +1,6 @@ """SUPPORT2 survival with Deep Cox Mixtures: mixture-size ablation. -Contributor: (NetID: liu323) +Contributor: Xinyi Liu (NetID: liu323) Paper: Nagpal, Yadlowsky, Rostamzadeh and Heller. Deep Cox Mixtures for Survival Regression. MLHC 2021. https://proceedings.mlr.press/v149/nagpal21a.html diff --git a/pyhealth/models/deep_cox_mixtures.py b/pyhealth/models/deep_cox_mixtures.py index 728ac2859c..903fe35479 100644 --- a/pyhealth/models/deep_cox_mixtures.py +++ b/pyhealth/models/deep_cox_mixtures.py @@ -1,6 +1,6 @@ """Deep Cox Mixtures for survival regression. -Contributor: (NetID: liu323) +Contributor: Xinyi Liu (NetID: liu323) Paper: Chirag Nagpal, Steve Yadlowsky, Negar Rostamzadeh and Katherine Heller. Deep Cox Mixtures for Survival Regression. Machine Learning for Healthcare diff --git a/pyhealth/tasks/survival_time_to_event_support2_dcm.py b/pyhealth/tasks/survival_time_to_event_support2_dcm.py index 600f0f3253..d6dc1dac41 100644 --- a/pyhealth/tasks/survival_time_to_event_support2_dcm.py +++ b/pyhealth/tasks/survival_time_to_event_support2_dcm.py @@ -1,6 +1,6 @@ """SUPPORT2 time-to-death task in the Deep Cox Mixtures protocol. -Contributor: (NetID: liu323) +Contributor: Xinyi Liu (NetID: liu323) Paper: Chirag Nagpal, Steve Yadlowsky, Negar Rostamzadeh and Katherine Heller. Deep Cox Mixtures for Survival Regression. MLHC 2021. diff --git a/tests/core/test_deep_cox_mixtures.py b/tests/core/test_deep_cox_mixtures.py index fb8e45da0c..094c692dde 100644 --- a/tests/core/test_deep_cox_mixtures.py +++ b/tests/core/test_deep_cox_mixtures.py @@ -1,6 +1,6 @@ """Fast synthetic tests for DeepCoxMixtures; no real data or downloads. -Contributor: (NetID: liu323) +Contributor: Xinyi Liu (NetID: liu323) Paper: Deep Cox Mixtures for Survival Regression (Nagpal et al., MLHC 2021), https://proceedings.mlr.press/v149/nagpal21a.html """ diff --git a/tests/core/test_survival_time_to_event_support2_dcm.py b/tests/core/test_survival_time_to_event_support2_dcm.py index 3b45260b1f..b520f43d43 100644 --- a/tests/core/test_survival_time_to_event_support2_dcm.py +++ b/tests/core/test_survival_time_to_event_support2_dcm.py @@ -1,6 +1,6 @@ """Fast synthetic tests for SurvivalTimeToEventSupport2DCM; no real data. -Contributor: (NetID: liu323) +Contributor: Xinyi Liu (NetID: liu323) Paper: Deep Cox Mixtures for Survival Regression (Nagpal et al., MLHC 2021), https://proceedings.mlr.press/v149/nagpal21a.html """