Skip to content

Add Deep Cox Mixtures for survival prediction - #1748

Open
jzalwan2 wants to merge 26 commits into
sunlabuiuc:masterfrom
lnguyen99:implement-deep-cox-mixtures-model
Open

jzalwan2 wants to merge 26 commits into
sunlabuiuc:masterfrom
lnguyen99:implement-deep-cox-mixtures-model

Conversation

@jzalwan2

Copy link
Copy Markdown

Contributors
Jenny Nguyen (lmn4@illinois.edu), Jordan Alwan (jzalwan2@illinois.edu), and Karthik Pullela (kpull2@illinois.edu)

Contribution Type
Model

Original Paper
Deep Cox Mixtures for Survival Regression by Nagpal et al. (MLHC 2021)

Description
This PR adds DeepCoxMixtures, a PyHealth BaseModel for right-censored time-to-event prediction. A shared neural encoder estimates patient-specific mixture weights and hazard ratios. The model combines those estimates with component-specific Breslow baseline survival curves to predict each patient’s survival probability over time.

The example trains the model with expectation-maximization using PyHealth’s existing SUPPORT2 dataset and survival task. It documents two five-fold ablations that compare one versus three mixture components and evaluate three latent-group assignment strategies. It also includes a synthetic mode for running the training and evaluation pipeline without downloading SUPPORT2.

Files to Review

  • pyhealth/models/deep_cox_mixtures.py — Model, baseline fitting, and survival prediction.
  • pyhealth/models/__init__.py — Public DeepCoxMixtures export.
  • examples/support2_survival_time_to_event_deep_cox_mixtures.py — Training loop, SUPPORT2 ablations, documented results, and synthetic mode.
  • tests/core/test_deep_cox_mixtures.py — Synthetic tests for model initialization, forward pass, output shapes, and gradients.
  • docs/api/models/pyhealth.models.deep_cox_mixtures.rst — API documentation and usage instructions.
  • docs/api/models.rst — Models documentation index entry.
  • pyproject.toml — Optional scikit-survival dependency and test environment configuration.

lnguyen99 and others added 26 commits November 21, 2026 15:38
DeepCoxMixturesScriptEM (pyhealth/models/deep_cox_mixtures_script_em.py):
pure network + helpers (fit_baselines, compute_posteriors, q_loss,
soft_q_loss, predict_survival); the EM loop lives in the example
script, not in Trainer.train. Includes tests
(tests/core/test_deep_cox_mixtures_script_em.py, 9 synthetic tests).
Sync fork master with upstream master (0bdc53a)
Clip spline output to avoid numerical issues.
Clarify the explanation of baseline refitting methods and their impact on calibration and discrimination.
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.34% (58531 / 66257 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 124 / 124
pyhealth/models/deep_cox_mixtures.py 89.21% 248 / 278

Workflow run · c7b378c

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

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual:

What you can contribute instead: after #1641 merges, rebase and keep only what yours adds, as an option on #1641's model or as an example. Please drop the duplicate model and the pyproject.toml change. If you think your implementation is better on a specific point, comment with details.

Copy link
Copy Markdown
Collaborator

/review


Generated by Claude Code

@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 c7b378c

)
val_per_patient = float(val_loss) / x_val.shape[0]
val_losses.append(val_per_patient)
if val_per_patient > best_val:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Early stopping compares against the previous epoch, not the best validation loss

best_val is reassigned to the latest epoch's loss on every iteration (line 371), so waited counts consecutive epoch-over-epoch increases rather than epochs without improvement on the best value. A run that worsens and then recovers slightly never reaches patience in the way the docstring describes, and the reported epochs_run and ablation numbers depend on this. Fix: update best_val only when val_per_patient < best_val (and reset waited there), otherwise increment waited, and stop when waited == patience.


root = Path(__file__).resolve().parents[2]
path = root / "examples" / "support2_survival_time_to_event_deep_cox_mixtures.py"
spec = importlib.util.spec_from_file_location("dcm_example", path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Model tests import and run the example script's EM loop, which the description does not mention

_load_example_module loads examples/support2_survival_time_to_event_deep_cox_mixtures.py and the two train_em tests call its training function. This is a new link from the model's test suite to a concrete example component, and the description only says the EM loop lives in the example. Either describe this dependency in the PR description and explain why the loop is not in the library, or keep the component self-contained by giving the tests their own training loop.

or not torch.isfinite(time_grid).all()
or torch.any(time_grid <= 0)
):
raise ValueError("time_grid must contain finite strictly positive values")

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] time_grid order is not validated, so unsorted grids silently give wrong curves

The constructor checks only that time_grid is finite and positive. predict_survival applies np.minimum.accumulate along the time axis (line 831), which is only a valid monotone guard when times are nondecreasing. An unsorted time_grid therefore returns incorrect y_prob without error. Reject unsorted grids here, or sort the grid and document that.

)

# -- PyHealth forward -------------------------------------------------
def forward(self, **kwargs: Tensor | tuple[Tensor, ...]) -> dict[str, Tensor]:

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] forward cannot be used by Trainer, which the PR description does not state

forward raises RuntimeError until fit_baselines has run (line 871), so Trainer.train/evaluate cannot drive this BaseModel. The class and module docstrings say so, but the PR description presents it as a trainable BaseModel with an EM example. Add this limitation to the PR description.

occur: a failed baseline refit logs a warning and reuses the old splines
instead of failing silently (the reference has a bare ``try/except``);
survival ECE is implemented here from scratch (20 bins, Kaplan-Meier per
bin) because neither PyHealth nor auton-survival has one; the script is

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] Claim that PyHealth has no survival calibration measure is incomplete

The docstring says survival ECE is implemented here because neither PyHealth nor auton-survival has one. PyHealth does have d_calibration in pyhealth/metrics/survival_curve.py:380, a different survival calibration measure. Mention it and state that this ECE is a separate measure.

@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 adding Deep Cox Mixtures. It brings a mixture-of-Cox survival model to PyHealth, with an EM training example on SUPPORT2, two documented ablations, docs, and an optional scikit-survival extra. It looks ready to merge.

The change is self-contained. It only registers the new class in pyhealth/models/__init__.py and adds an optional extra in pyproject.toml. The description names the reuse of the existing SUPPORT2 dataset and task. Coverage is 89.2% for deep_cox_mixtures.py (new file) and 88.3% for the whole repository. Both are above the bar.

Optional suggestions:

  • The early-stopping check in train_em compares each epoch's validation loss with the previous epoch's, not the best so far. This matches the reference implementation you ported, but the docstring could say so. Tracking the best loss would be a small change if you prefer it.
  • forward raises until baselines are fitted, so Trainer.train() can't train this model. This is clearly documented in the docstrings and the API page. You could add one sentence about it to the PR description too.
  • time_grid is not checked for sorted order, but the monotonic clamp in predict_survival assumes it. A short validation would help.
  • The tests load the example script to run train_em. Mention that in the description if it's intentional.
  • Tests for set_baselines key validation and for early stopping would be nice additions.
  • The example docstring says PyHealth has no survival calibration metric. You may want to check that against the existing d_calibration.

Reviewed commit c7b378c

@jhnwu3

jhnwu3 commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Duplicate: Deep Cox Mixtures is also added by #1579, which was opened earlier (open PRs adding it: #1579, #1611, #1629, #1641, #1681, #1748).

We're keeping this PR open for now, and it may already have an AI review for feedback on your code, but we're unlikely to merge a second implementation. If your version adds something the existing one lacks (for example a different dataset, task or ablation), a focused follow-up PR that builds on it is very welcome; please link this PR from it. Before opening a PR, please check master and open PRs for the same component.

@jhnwu3 jhnwu3 added the duplicate Duplicates an existing PR or a component already on master label Dec 1, 2026

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

duplicate Duplicates an existing PR or a component already on master status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants