Repository navigation
Conversation
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>
Test CoverageTotal: 87.12% (50425 / 57878 lines)
|
|
/review |
| 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) |
There was a problem hiding this comment.
[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) |
There was a problem hiding this comment.
[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): |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
forwardcall 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
Support2Datasetwith a tiny CSV would cover the full path. - The example has no automated test. A short
--syntheticsmoke test would help.
Reviewed commit d820c46
|
Why this PR has 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. |
|
Picked to merge first. We compared the four Deep Cox Mixtures PRs (#1579, #1611, #1629 and this one). This one has the strongest model:
Before it can merge:
Once these fixes are pushed, we'll move this PR to |
solarsys
left a comment
There was a problem hiding this comment.
Approved by a maintainer. The AI review suggests approve on the current commit, and the build passes.
|
Approved by a maintainer, and ready to merge once it no longer conflicts with master. Recent merges touched the same registration lines in |
Contributor: Xinyi Liu (NetID: liu323, liu323@illinois.edu)
Contribution type: Model + Task:
DeepCoxMixtures(model) andSurvivalTimeToEventSupport2DCM(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 PyTorchBaseModel.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 instate_dict().K=1is a neural Cox model andhidden_dims=()the linear "Cox Mixture".pyhealth.tasks.SurvivalTimeToEventSupport2DCMforSupport2Dataset. 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 aracefield for the paper's non-White subgroup. Labels areduration/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--syntheticmode for a quick run.Why a new task
The existing
SurvivalTimeToEventSupport2is the DeepSurv benchmark: 8,873 complete cases, 14 covariates, 27 drop-first features. The existingSurvivalPreprocessSupport2regresses SUPPORT's ownsurv2m/surv6mestimates. 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_processorsreturns{}(mode=None), like the other survival models.forwardreturnslog_risk,mixture_weights, and, once fitted,survival/y_probattime_grid. With labels it also returns the EMloss,posteriorandy_true, soTrainer.inference/evaluatework afterfit. Training goes throughfit(), because the baselines must be refit between gradient steps andTrainerhas no hook for that.Links between components
BaseTaskand readsSupport2Datasetevents. It does not import the helpers ofpyhealth/tasks/survival_time_to_event.py; its parsing is self-contained so the two SUPPORT2 tasks can change independently.BaseModeland PyTorch. The example and one task test useSupport2Dataset/create_sample_datasetand the new model, the intended dataset → task → model pipeline.examples/additionally needsscikit-survivalfor the paper's metrics.File guide
pyhealth/models/deep_cox_mixtures.pyfit,fit_baselines,_log_posterior,_expected_complete_loss),cox_partial_log_likelihood,breslow_cumulative_hazardpyhealth/tasks/survival_time_to_event_support2_dcm.pytests/core/test_deep_cox_mixtures.pytests/core/test_survival_time_to_event_support2_dcm.pydocs/api/models/pyhealth.models.deep_cox_mixtures.rst,docs/api/tasks/pyhealth.tasks.survival_time_to_event_support2_dcm.rstdocs/api/models.rst,docs/api/tasks.rst)examples/support2_survival_deep_cox_mixtures.pypyhealth/models/__init__.py,pyhealth/tasks/__init__.pyTests
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 checkis clean, andtools/check_pr_rules.pypasses. The existing SUPPORT2/SurvivalMDN/MoE/metrics tests also pass (93).Reproduction (SUPPORT, paper's 5 folds, 252-day horizon, ± bootstrap SE)
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
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.