Skip to content

Commit 3bb7198

Browse files
committed
Add RotterdamDataset, MultiEventSurvivalRotterdam task and MENSA model
1 parent 0181aa2 commit 3bb7198

17 files changed

Lines changed: 5876 additions & 0 deletions

‎docs/api/datasets.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,11 @@ PyHealth does not ship any data: you download each dataset from its source and p
555555
- `GitHub <https://github.com/neheller/kits23>`__ + `Hugging Face <https://huggingface.co/datasets/neheller/KiTS-Challenge-Imaging>`__
556556
- No (``kits23_download_data``)
557557
- Single CTs by URL (``wget``)
558+
* - :doc:`Rotterdam <datasets/pyhealth.datasets.RotterdamDataset>`
559+
- Open
560+
- `R survival <https://stat.ethz.ch/R-manual/R-devel/library/survival/html/rotterdam.html>`__
561+
- No
562+
- —
558563
* - :doc:`TCGA-PRAD <datasets/pyhealth.datasets.TCGAPRADDataset>`
559564
- Open
560565
- `GDC <https://portal.gdc.cancer.gov/projects/TCGA-PRAD>`__
@@ -665,6 +670,7 @@ Available Datasets
665670
datasets/pyhealth.datasets.Support2Dataset
666671
datasets/pyhealth.datasets.MetabricDataset
667672
datasets/pyhealth.datasets.GBSGDataset
673+
datasets/pyhealth.datasets.RotterdamDataset
668674
datasets/pyhealth.datasets.BMDHSDataset
669675
datasets/pyhealth.datasets.COVID19CXRDataset
670676
datasets/pyhealth.datasets.ISIC2019Dataset
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
pyhealth.datasets.RotterdamDataset
2+
==================================
3+
4+
Overview
5+
--------
6+
7+
Load the Rotterdam tumour-bank breast-cancer cohort from a local CSV, keeping
8+
recurrence and death as two separate outcomes. The file has one row per
9+
patient: 2,982 patients with primary breast cancer (surgery 1978-1993), ten
10+
baseline covariates, and for each outcome its own follow-up time in days and
11+
event indicator (``rtime``/``recur`` and ``dtime``/``death``). 1,518 patients
12+
recurred and 1,272 died; 1,077 had both events and 1,269 neither.
13+
14+
This is the full multi-event cohort. It is not the 2,232-row pooled
15+
Rotterdam/GBSG benchmark loaded by :doc:`pyhealth.datasets.GBSGDataset`, which
16+
has seven features and a single recurrence-free survival endpoint in months.
17+
18+
Patient times are kept exactly as recorded. 43 patients died after their
19+
recurrence follow-up had ended without a recorded recurrence (``recur=0``,
20+
``death=1``, ``rtime < dtime``); their recurrence stays censored at ``rtime``
21+
and is not extended to the death time. Tied recurrence and death times are
22+
kept, and tumour ``size`` stays one of its three source categories
23+
(``"<=20"``, ``"20-50"``, ``">50"`` mm); numeric coding belongs to the task.
24+
The whole CSV is validated when the dataset is created, before anything is
25+
cached, and errors name the column and ``pid``. The default task is
26+
:class:`~pyhealth.tasks.MultiEventSurvivalRotterdam`.
27+
28+
Data source
29+
-----------
30+
31+
The cohort is distributed with the R ``survival`` package as
32+
`survival::rotterdam`_, from Royston and Altman, `External validation of a Cox
33+
prognostic model: principles and methods`_ (BMC Medical Research Methodology,
34+
2013). It is open; no account or agreement is needed. The MENSA authors ship
35+
the same table as `data/rotterdam.csv`_ in their repository: download that
36+
file (**Download raw file**) and put it in the folder you pass as ``root``.
37+
Alternatively, export it from R with
38+
``write.csv(survival::rotterdam, "rotterdam.csv", row.names = FALSE)``; the
39+
loader validates whichever file you use. The loader never downloads anything.
40+
41+
The CSV needs these 15 columns: ``pid``, ``year``, ``age``, ``meno``,
42+
``size``, ``grade``, ``nodes``, ``pgr``, ``er``, ``hormon``, ``chemo``,
43+
``rtime``, ``recur``, ``dtime`` and ``death``.
44+
45+
Usage
46+
-----
47+
48+
.. code-block:: python
49+
50+
from pyhealth.datasets import RotterdamDataset, split_by_patient
51+
52+
dataset = RotterdamDataset(root="/path/to/folder") # holds rotterdam.csv
53+
samples = dataset.set_task() # MultiEventSurvivalRotterdam by default
54+
train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=0)
55+
56+
See :doc:`../tasks/pyhealth.tasks.multi_event_survival_rotterdam` for the
57+
sample format and :doc:`../models/pyhealth.models.MENSA` for a model that
58+
uses it.
59+
60+
API reference
61+
-------------
62+
63+
.. autoclass:: pyhealth.datasets.RotterdamDataset
64+
:members:
65+
:show-inheritance:
66+
67+
.. autofunction:: pyhealth.datasets.rotterdam.parse_rotterdam_record
68+
69+
.. _survival::rotterdam: https://stat.ethz.ch/R-manual/R-devel/library/survival/html/rotterdam.html
70+
.. _External validation of a Cox prognostic model\: principles and methods: https://doi.org/10.1186/1471-2288-13-33
71+
.. _data/rotterdam.csv: https://github.com/thecml/mensa/blob/main/data/rotterdam.csv

‎docs/api/models.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ API Reference
361361
models/pyhealth.models.XGBoostModel
362362
models/pyhealth.models.survival_mdn
363363
models/pyhealth.models.personalized_survival_moe
364+
models/pyhealth.models.MENSA
364365
models/pyhealth.models.cet
365366
models/pyhealth.models.TrajSurv
366367
models/pyhealth.models.KnowRare
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
pyhealth.models.MENSA
2+
=====================
3+
4+
Overview
5+
--------
6+
7+
MENSA (Multi-Event Network for Survival Analysis) predicts a survival curve
8+
for each of several events from one shared network. Each event, plus an
9+
event-free state used only in training, gets a mixture of Weibull
10+
distributions and its own residual adapter on a shared trunk. Training
11+
minimizes ``(1 - lambda) * L_surv + lambda * L_traj``: a weighted censored
12+
likelihood over all states, plus a trajectory term that penalizes predicting
13+
the later event (death) before the earlier one (recurrence) for patients who
14+
had both. ``trajectory_variant="paper"`` follows the paper's Eq. 1;
15+
``"reference"`` follows the authors' code.
16+
17+
Paper
18+
-----
19+
20+
Lillelund, Gharari Foomani, Sun, Qi and Greiner, `MENSA: A Multi-Event Network
21+
for Survival Analysis with Trajectory-based Likelihood Estimation`_, Machine
22+
Learning for Health (ML4H) 2025, PMLR 297 (`arXiv:2409.06525`_). This
23+
implementation is adapted from the authors' `reference code`_ (MIT License,
24+
commit 6b219cd).
25+
26+
Inputs and outputs
27+
------------------
28+
29+
MENSA works with the ``"tensor"`` outputs of
30+
:doc:`../tasks/pyhealth.tasks.multi_event_survival_rotterdam`: ``features
31+
[F]``, ``event_times [K]`` and ``event_indicators [K]``, in source time units.
32+
It has no label processor, so ``mode`` is ``None`` and PyHealth's Trainer
33+
tracks only the loss; compute survival metrics from survival curves.
34+
35+
Call ``fit_preprocessing`` with the **training split only** before training.
36+
It fits the feature standardization, the per-state loss weights and the time
37+
grid used for ``y_prob``, and stores them as buffers, so they are saved with
38+
the model. ``forward`` returns ``loss``, ``y_prob`` (survival probabilities,
39+
``[batch, K, T]`` on that grid) and ``y_true`` (times and indicators).
40+
``predict_survival(features, times)`` returns ``[batch, K, len(times)]``
41+
curves on any time grid; it runs in evaluation mode without gradients and
42+
restores each module's previous mode.
43+
44+
Defaults are one hidden layer of 32, dropout 0.25, three Weibull components
45+
and ``lambda = 0.25``, trained with batch size 32, learning rate 1e-3, weight
46+
decay 1e-3 and gradient clipping at norm 1.0. The training loader drops its
47+
last incomplete batch (``drop_last=True``), because BatchNorm cannot train on
48+
a batch of one. The reference code's Rotterdam config uses
49+
``hidden_dims=(16,)``, ``dropout=0.5`` and weight decay 1e-4 instead.
50+
51+
Usage
52+
-----
53+
54+
.. code-block:: python
55+
56+
import torch
57+
from pyhealth.datasets import RotterdamDataset, get_dataloader, split_by_patient
58+
from pyhealth.models import MENSA
59+
from pyhealth.trainer import Trainer
60+
61+
samples = RotterdamDataset(root="/path/to/folder").set_task()
62+
train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=0)
63+
64+
model = MENSA(samples)
65+
model.fit_preprocessing(train) # training split only
66+
trainer = Trainer(model=model)
67+
trainer.train(
68+
train_dataloader=get_dataloader(
69+
train, batch_size=32, shuffle=True, drop_last=True
70+
),
71+
val_dataloader=get_dataloader(val, batch_size=1024),
72+
epochs=1000,
73+
optimizer_params={"lr": 1e-3},
74+
weight_decay=1e-3,
75+
max_grad_norm=1.0,
76+
monitor="loss",
77+
monitor_criterion="min",
78+
patience=20,
79+
)
80+
81+
batch = next(iter(get_dataloader(test, batch_size=len(test))))
82+
times = torch.linspace(0, 7000, 50) # days
83+
curves = model.predict_survival(batch["features"], times) # [N, 2, 50]
84+
85+
Example and results
86+
-------------------
87+
88+
``examples/rotterdam_multi_event_survival_mensa.py`` reproduces the paper's
89+
Rotterdam protocol: the authors' stratified 70/10/20 split, CoxPH and
90+
DeepSurv baselines, and global/local C-index, AUC, IBS, MAE and
91+
D-calibration. It also runs a learning curve (E2) and ablations (E3, E4).
92+
To run the whole pipeline on synthetic data (no download)::
93+
94+
python examples/rotterdam_multi_event_survival_mensa.py --synthetic
95+
96+
With the real CSV in ``../data``::
97+
98+
python examples/rotterdam_multi_event_survival_mensa.py --data-root ../data \
99+
--experiment main --seeds 0-9 --output-dir ../runs/e1
100+
101+
Over seeds 0-9, MENSA reaches a global C-index of 69.3 and a local C-index of
102+
90.9 (x100; paper 69.4 and 90.1). Most of the local C-index comes from the
103+
event order: predicting recurrence before death for every patient, with no
104+
model, gives 91.0. MENSA equals that on 8 of 10 seeds and is below it on 2.
105+
This reference is not an upper bound. The example's module docstring records
106+
all results, including why the default IBS varies widely across splits.
107+
108+
API reference
109+
-------------
110+
111+
.. autoclass:: pyhealth.models.MENSA
112+
:members:
113+
:show-inheritance:
114+
115+
Loss and distribution functions
116+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
117+
118+
Stateless tensor functions used by :class:`~pyhealth.models.MENSA`.
119+
120+
.. autofunction:: pyhealth.models.mensa.mensa_loss
121+
.. autofunction:: pyhealth.models.mensa.survival_nll
122+
.. autofunction:: pyhealth.models.mensa.trajectory_nll
123+
.. autofunction:: pyhealth.models.mensa.extend_labels
124+
.. autofunction:: pyhealth.models.mensa.compute_state_weights
125+
.. autofunction:: pyhealth.models.mensa.mixture_log_weights
126+
.. autofunction:: pyhealth.models.mensa.mixture_log_survival
127+
.. autofunction:: pyhealth.models.mensa.mixture_log_density
128+
.. autofunction:: pyhealth.models.mensa.weibull_log_survival
129+
.. autofunction:: pyhealth.models.mensa.weibull_log_density
130+
131+
.. _MENSA\: A Multi-Event Network for Survival Analysis with Trajectory-based Likelihood Estimation: https://proceedings.mlr.press/v297/lillelund26a.html
132+
.. _arXiv:2409.06525: https://arxiv.org/abs/2409.06525
133+
.. _reference code: https://github.com/thecml/mensa

‎docs/api/tasks.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,3 +326,4 @@ Available Tasks
326326
Time-to-event survival (GBSG and SUPPORT) <tasks/pyhealth.tasks.survival_time_to_event>
327327
TCGA RNA-seq Survival Prediction <tasks/pyhealth.tasks.TCGASurvivalPrediction>
328328
Query-Focused EHR Summarization (MIMIC-III) <tasks/pyhealth.tasks.QueryFocusedEHRTask>
329+
Multi-event survival (Rotterdam) <tasks/pyhealth.tasks.multi_event_survival_rotterdam>
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
Multi-event survival (Rotterdam)
2+
================================
3+
4+
Overview
5+
--------
6+
7+
:class:`~pyhealth.tasks.MultiEventSurvivalRotterdam` turns each patient of
8+
:doc:`../datasets/pyhealth.datasets.RotterdamDataset` into one sample with a
9+
dense feature vector and two events, recurrence then death:
10+
11+
- ``features``: ten values in this order: ``year``, ``age``, ``meno``,
12+
``grade``, ``nodes``, ``pgr``, ``er``, ``hormon``, ``chemo`` and
13+
``size_mm``, with tumour size coded as 10, 35 or 75 mm for ``"<=20"``,
14+
``"20-50"`` and ``">50"``. With ``use_treatment=False`` the treatment
15+
indicators ``hormon`` and ``chemo`` are dropped, leaving eight features in
16+
the same order; the labels do not change.
17+
- ``event_times``: ``[rtime, dtime]`` in days, exactly as recorded. A
18+
recurrence censored before a later death keeps its own ``rtime``, and tied
19+
times are kept.
20+
- ``event_indicators``: ``[recur, death]``, 1 for an observed event and 0 for
21+
censoring at that time.
22+
23+
Every value is validated by
24+
:func:`~pyhealth.datasets.rotterdam.parse_rotterdam_record`. Features are not
25+
standardized here: fit any standardization on training patients only, after
26+
splitting. Like PyHealth's other duration/event survival tasks, the labels use
27+
the ``"tensor"`` processor, so a model consuming them sets ``mode=None`` and
28+
supplies its own censored likelihood to the standard Trainer, as
29+
:doc:`../models/pyhealth.models.MENSA` does.
30+
31+
Paper
32+
-----
33+
34+
The features, size coding and event order follow the Rotterdam setup of
35+
Lillelund et al., `MENSA: A Multi-Event Network for Survival Analysis with
36+
Trajectory-based Likelihood Estimation`_ (ML4H 2025, PMLR 297), and its
37+
`reference code`_.
38+
39+
Usage
40+
-----
41+
42+
.. code-block:: python
43+
44+
from pyhealth.datasets import RotterdamDataset
45+
from pyhealth.tasks import MultiEventSurvivalRotterdam
46+
47+
dataset = RotterdamDataset(root="/path/to/folder")
48+
samples = dataset.set_task(MultiEventSurvivalRotterdam()) # ten features
49+
sample = samples[0]
50+
sample["features"].shape # torch.Size([10])
51+
sample["event_times"] # tensor([rtime, dtime]), days
52+
sample["event_indicators"] # tensor([recur, death])
53+
54+
# Without the treatment indicators (eight features):
55+
samples_8 = dataset.set_task(MultiEventSurvivalRotterdam(use_treatment=False))
56+
57+
API reference
58+
-------------
59+
60+
.. autoclass:: pyhealth.tasks.MultiEventSurvivalRotterdam
61+
:members:
62+
:show-inheritance:
63+
64+
.. _MENSA\: A Multi-Event Network for Survival Analysis with Trajectory-based Likelihood Estimation: https://proceedings.mlr.press/v297/lillelund26a.html
65+
.. _reference code: https://github.com/thecml/mensa

0 commit comments

Comments
 (0)