Repository navigation
Conversation
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).
Add Deep Cox Mixtures model (option b)
…-deep-cox-mixtures branch)
…-cox-mixtures branch)
…d-deep-cox-mixtures branch)
Sync fork master with upstream master (0bdc53a)
Clip spline output to avoid numerical issues.
…implement-deep-cox-mixtures-model
Clarify the explanation of baseline refitting methods and their impact on calibration and discrimination.
Test CoverageTotal: 88.34% (58531 / 66257 lines)
|
|
Why this PR has
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 |
|
/review Generated by Claude Code |
| ) | ||
| val_per_patient = float(val_loss) / x_val.shape[0] | ||
| val_losses.append(val_per_patient) | ||
| if val_per_patient > best_val: |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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") |
There was a problem hiding this comment.
[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]: |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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_emcompares 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. forwardraises until baselines are fitted, soTrainer.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_gridis not checked for sorted order, but the monotonic clamp inpredict_survivalassumes 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_baselineskey 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
|
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. |
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 PyHealthBaseModelfor 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— PublicDeepCoxMixturesexport.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.