Skip to content

Add Deep Cox Mixtures model and SUPPORT2 DCM-protocol survival task - #1641

Open
tracy3057 wants to merge 6 commits into
sunlabuiuc:masterfrom
tracy3057:deep-cox-mixtures
Open

tracy3057 wants to merge 6 commits into
sunlabuiuc:masterfrom
tracy3057:deep-cox-mixtures

Conversation

@tracy3057

Copy link
Copy Markdown

Contributor: Xinyi Liu (NetID: liu323, liu323@illinois.edu)

Contribution type: Model + Task: DeepCoxMixtures (model) and SurvivalTimeToEventSupport2DCM (task), with tests, docs and an example/ablation script.

Original paper: Chirag Nagpal, Steve Yadlowsky, Negar Rostamzadeh, Katherine Heller. Deep Cox Mixtures for Survival Regression. Machine Learning for Healthcare (MLHC), PMLR 149, 2021. https://proceedings.mlr.press/v149/nagpal21a.html

Summary

Deep Cox Mixtures (DCM) model a patient's survival curve as a mixture of K Cox models, S(t|x) = Σ_k π_k(x) S_0k(t)^exp(f_k(x)). A shared MLP encoder feeds a gating head (latent-group probabilities) and per-group log-hazard heads, and each group has its own Breslow baseline. Proportional hazards hold within a group but not across the mixture, which lets the model fit populations whose survival curves cross. The paper reports better calibration than Cox PH and comparable discrimination.

This PR adds:

  • pyhealth.models.DeepCoxMixtures, a self-contained PyTorch BaseModel. fit() implements the paper's Monte Carlo EM (Algorithm 1). For each mini-batch it computes E-step responsibilities from the observed time and censoring status, samples hard assignments, takes an Adam step on Σ γ log π + Σ_k log PL_k (Breslow ties), and refits every group's Breslow baseline on the full training set. Early stopping on validation NLL restores the best weights and baselines. Other methods: predict_survival ([N, T]), predict_latent ([N, K]), predict_log_risk, fit_baselines, negative_log_likelihood. Baselines are saved in state_dict(). K=1 is a neural Cox model and hidden_dims=() the linear "Cox Mixture".
  • pyhealth.tasks.SurvivalTimeToEventSupport2DCM for Support2Dataset. It uses the paper's SUPPORT protocol: all 9,105 patients and 24 covariates one-hot coded into 44 features (NaN for missing numerics, so imputation can be fit on training patients). It also returns a race field for the paper's non-White subgroup. Labels are duration/event, the same contract as the existing SUPPORT2 time-to-event task.
  • examples/support2_survival_deep_cox_mixtures.py, a 5-fold reproduction protocol with a mixture-size ablation (K = 1, 2, 3, 6) and an optional training-censoring stress test. It has a --synthetic mode for a quick run.

Why a new task

The existing SurvivalTimeToEventSupport2 is the DeepSurv benchmark: 8,873 complete cases, 14 covariates, 27 drop-first features. The existing SurvivalPreprocessSupport2 regresses SUPPORT's own surv2m/surv6m estimates. Neither gives the DCM paper's cohort or covariates. With this task the encoded matrix equals the authors' released preprocessing exactly (same missing pattern; max difference 4e-6 from float32).

Design notes

  • label_processors returns {} (mode=None), like the other survival models. forward returns log_risk, mixture_weights, and, once fitted, survival/y_prob at time_grid. With labels it also returns the EM loss, posterior and y_true, so Trainer.inference/evaluate work after fit. Training goes through fit(), because the baselines must be refit between gradient steps and Trainer has no hook for that.
  • Baseline survival between event times: each group's Breslow cumulative hazard is interpolated linearly between its own event times. This keeps survival curves in [0, 1] and non-increasing, and E-step densities non-negative. The paper uses a cubic smoothing spline and the authors' PyTorch release a linear smoothing spline; neither guarantees monotonicity.
  • Numerical safeguards (all documented): log hazard ratios clamped to ±10 (as in auton-survival), per-group likelihood floor 1e-10 in the E-step (the authors' code floors the joint gate × likelihood at the same value), float64 baselines. A group with no assigned patients keeps its previous baseline.

Links between components

  • The task subclasses BaseTask and reads Support2Dataset events. It does not import the helpers of pyhealth/tasks/survival_time_to_event.py; its parsing is self-contained so the two SUPPORT2 tasks can change independently.
  • The model uses only BaseModel and PyTorch. The example and one task test use Support2Dataset/create_sample_dataset and the new model, the intended dataset → task → model pipeline. examples/ additionally needs scikit-survival for the paper's metrics.

File guide

File What to look at
pyhealth/models/deep_cox_mixtures.py model, EM (fit, fit_baselines, _log_posterior, _expected_complete_loss), cox_partial_log_likelihood, breslow_cumulative_hazard
pyhealth/tasks/survival_time_to_event_support2_dcm.py task and feature definitions
tests/core/test_deep_cox_mixtures.py 25 model tests (shapes, gradients, hand-computed Cox/Breslow with ties, E-step, K=1 = neural Cox, edge cases, persistence, validation, fit incl. early stopping/restore and seeding, Trainer)
tests/core/test_survival_time_to_event_support2_dcm.py 5 task tests on synthetic rows
docs/api/models/pyhealth.models.deep_cox_mixtures.rst, docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rst API pages (+ index entries in docs/api/models.rst, docs/api/tasks.rst)
examples/support2_survival_deep_cox_mixtures.py runnable example and ablation, with measured results in its docstring
pyhealth/models/__init__.py, pyhealth/tasks/__init__.py one export each

Tests

python -m pytest tests/core/test_deep_cox_mixtures.py tests/core/test_survival_time_to_event_support2_dcm.py

30 passed locally on CPU (slowest test 0.07 s), using only tiny synthetic data. Coverage is 97% for the model file and 100% for the task file. Doctests pass, ruff check is clean, and tools/check_pr_rules.py passes. The existing SUPPORT2/SurvivalMDN/MoE/metrics tests also pass (93).

Reproduction (SUPPORT, paper's 5 folds, 252-day horizon, ± bootstrap SE)

Model Overall ECE Overall Ctd Non-White ECE Non-White Ctd
Cox PH (paper / ours) 0.0310 / 0.0247 ± 0.0041 0.6686 / 0.6684 ± 0.0042 0.0685 / 0.0604 ± 0.0095 0.6905 / 0.6936 ± 0.0095
RSF (paper / ours) 0.0348 / 0.0349 ± 0.0048 0.6751 / 0.6718 ± 0.0039 0.0603 / 0.0551 ± 0.0096 0.6974 / 0.6987 ± 0.0083
DCM (paper / this PR) 0.0256 / 0.0235 ± 0.0038 0.6753 / 0.6749 ± 0.0040 0.0561 / 0.0401 ± 0.0094 0.6939 / 0.7008 ± 0.0088

Discrimination and Brier scores match the paper closely at 14, 58 and 252 days, and DCM is again the best-calibrated model overall and for non-White patients. In paired bootstrap comparisons, DCM's Brier and Ctd gains over Cox are significant. Its ECE gain over Cox is not significant, and ECE varies by about ±0.006 across training seeds.

Ablation (in the example)

Varying K with everything else fixed (5 folds, seed 0): K ≥ 2 discriminates better than K = 1, the neural Cox model. Ctd at 58 days rises from 0.667 to 0.704–0.706, Ctd at 252 days from 0.665 to 0.670–0.673, and Brier at 252 days improves slightly. ECE differences between K values are small and not consistent. In a separate study with 3 seeds and a paired bootstrap (research code, not part of this PR), the discrimination gain was significant and the calibration differences were within noise. With extra censoring of training patients only (up to +30 points), DCM K=3 keeps an ECE no higher than K=1 in the example run.

Limitations

  • The VAE encoder variant is not implemented.
  • Baselines use linear interpolation instead of the paper's spline.
  • The M-step uses mini-batch risk sets, as in the paper.
  • Only SUPPORT is wrapped as a task.
  • Predictions after a group's last training event time are held constant.

Attribution

This is an independent implementation from the paper. The authors' TensorFlow code (Apache-2.0) and auton-survival (MIT) were consulted to check the update order and defaults; no code was copied. Data: SUPPORT2 (UCI dataset 880). Development used an AI coding assistant; all code, tests and results were run and checked locally.

Xinyi Liu and others added 6 commits November 27, 2026 16:03
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 87.12% (50425 / 57878 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 100 / 100
pyhealth/models/deep_cox_mixtures.py 97.37% 370 / 380
pyhealth/tasks/__init__.py 98.26% 113 / 115
pyhealth/tasks/survival_time_to_event_support2_dcm.py 100.00% 58 / 58

Workflow run · d820c46

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 27, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit d820c46

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Labelled forward draws from the global RNG

When labels are passed, forward() calls _sample_assignment(log_posterior, None), which uses torch's global generator. Each Trainer.inference/evaluate call therefore advances global random state and returns a different loss, and it changes the random stream of unrelated code that runs later. Use a dedicated generator for the loss (for example a fixed-seed generator held by the model), or compute the reported eval loss deterministically, so that evaluation does not touch global RNG state.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Headline reproduction numbers in the description are not produced by the PR

The description's reproduction table reports DCM ECE@​252 of 0.0235 and Cox PH and RSF rows, but this example only runs DCM with seed 0 and prints K=3 ECE@​252 of 0.0142, and the PR contains no Cox PH or RSF code. Either state in the docstring which run and seed produced the headline table, or add the baseline runs to the example, so that a reader can check the calibration claim.

return Patient(rows[0]["sno"] if rows else "0", pl.DataFrame(events))


class TestSupport2DCMTask(unittest.TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] No test runs the task through Support2Dataset

All task tests build Patient objects by hand, and the example's load path (Support2Dataset.set_task with num_workers=1) is not tested, nor is the example itself. tests/core/test_support2_survival.py already writes a temporary support2.csv for dataset-level tests. Add one case that writes a few rows, loads them through Support2Dataset, and checks the 44-feature encoding and the race field.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It adds a Deep Cox Mixtures model with Monte Carlo EM training, a SUPPORT2 task that follows the paper's protocol, API docs, an ablation example and tests.

It looks ready to merge. The model is self-contained: it builds only on BaseModel. The task does not import the existing SUPPORT2 task's helpers. The links between the dataset, task and model are named in the description with a purpose. The paper is cited in the model docstring and on the docs pages. The docs match the code. Coverage meets the bar: 97.4% for the model file, 100% for the task file and 87% for the whole repository. The only edits to existing files are the __init__ exports and docs index entries, which count as registration.

Optional suggestions:

  • The reproduction table in the description lists Cox PH and RSF rows and a DCM ECE@​252 of 0.0235. The example has no Cox or RSF code, and its docstring reports a seed-0 K=3 ECE@​252 of 0.0142. You could note which script or settings produced the table, or add them.
  • A labelled forward call samples assignments from the global RNG, so evaluation changes the random state. You could mention this in the docstring, or pass a generator.
  • The task is only tested on synthetic rows. A small test through Support2Dataset with a tiny CSV would cover the full path.
  • The example has no automated test. A short --synthetic smoke test would help.

Reviewed commit d820c46

@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: four open PRs add a Deep Cox Mixtures model for SUPPORT2: #1579, #1611, #1629 and #1641. PyHealth keeps one implementation per component, so a maintainer has to pick one.

To help the maintainers decide, please comment here with what your PR does that the others don't, such as fidelity to the paper, results or test coverage. Whichever PR isn't picked can still contribute its unique parts on top of the chosen one. The decision is tracked in #1668.

This branch also conflicts with master, only in registration lines; please rebase.

@solarsys

Copy link
Copy Markdown
Collaborator

Picked to merge first. We compared the four Deep Cox Mixtures PRs (#1579, #1611, #1629 and this one). This one has the strongest model:

  • A self-contained fit() that follows the authors' Monte Carlo EM: hard assignments, Breslow baselines refit on the full training set after each batch, and early stopping on validation NLL.
  • A vectorized Cox partial likelihood that handles tied times.
  • A Breslow estimate computed in log space, so it can't overflow.
  • Baselines saved in state_dict.
  • 97% model coverage. The AI review suggests approve.

Before it can merge:

  1. Rebase on master. The only conflicts are registration lines.
  2. Add a test that runs Support2Dataset.set_task(SurvivalTimeToEventSupport2DCM()) on test-resources/core/support2/support2.csv.
  3. Fix the PR description. Its results table lists Cox PH and RSF rows and an ECE@252 of 0.0235, but the code has neither baseline, and the example's docstring reports 0.0142.
  4. Optional:
    • When a group's members have no events, keep that group's previous baseline instead of a zero hazard.
    • Seed or document the random sampling in forward.

Once these fixes are pushed, we'll move this PR to status: automatic and request an AI review. If the review approves, it merges. The other three PRs have been asked to add their unique parts on top of this one after it merges.

@solarsys solarsys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved by a maintainer. The AI review suggests approve on the current commit, and the build passes.

@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Approved by a maintainer, and ready to merge once it no longer conflicts with master. Recent merges touched the same registration lines in docs/api/models.rst and pyhealth/tasks/__init__.py. Please merge master into your branch (or rebase), keep both sides' entries, and push. Once the build passes, comment /review so the AI review runs on the new commit. We'll merge after that.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants