Repository navigation
[BTY-72] TPC Length of Stay Prediction - Model Implementation - CS598DLH Final Project - #1412
Conversation
b0742f6 to
eb3935b
Compare
Status — MIMIC-IV 2.2 demo measured; full clinical replication pendingThe MIMIC-IV Clinical Database Demo 2.2 baseline and complete three-seed This PR contributes the TPC model, extensions, synthetic tests/feasibility Contributors
Contribution Type: Model (Option 2), UIUC CS 598 DLH. Paper: Rocheteau et al., CHIL 2021, ImplementationAdds Supports Adds Reviewer file guide
Measured MIMIC-IV demo results — not full clinical reproduction
Demo source: 100 patients / Negative R2 and negative bias show poor squared-error performance and Full-dataset cohorts, experiments, benchmark-comparable scores, and comparison Executed demo protocolThe demo sweep contains 45 matched one-factor labels and three seeds The compute-constrained baseline is N=3, k=4, Y=Z=4, main dropout=0.2, Linear is identical to the paper schedule, not a separate novelty. Existing synthetic evidence (not clinical reproduction)The synthetic example already embeds its measured 47-configuration, UsagePreparation without dataset access or training: python -m examples.eicu_los_tpc --prepare-only --all-configs \
--output-dir output/tpc_clinical_planFuture training, only after authorized eICU data are available locally: python -m examples.eicu_los_tpc --run --dataset eicu \
--root /AUTHORIZED/PATH/eicu-crd/2.0 --data-version 2.0 \
--configs baseline --seeds 0 1 2 --epochs 8 --batch-size 32 \
--output-dir output/tpc_eicu_baselineUse Validation and limitations
Remaining work
|
Test CoverageTotal: 87.60% (53249 / 60788 lines)
|
|
/review Generated by Claude Code |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds a TPC model (with TPCLayer), a day-one continuous length-of-stay task (TPCDayOne), a clinical runner, synthetic and MIMIC-IV demo experiments, and docs. The tests are thorough, and coverage meets the bar: 86.13% for the whole repository, 99.56% for tpc.py and 95.24% for tpc_day_one.py. The work is close to ready.
To get this merged:
- The sharing between
examples/eicu_los_tpc.pyandexamples/synthetic_icu_los_tpc.pyisn't explained. The clinical runner importsBASE,METRICS,ablation_configsandlos_metricsfrom the synthetic example. Please say in the description why it reuses them (for example, to keep the protocol and metrics identical). Or make the runner self-contained by copying them in. Either is fine. - The docs for
pyhealth/models/tpc.pydon't match the code. Thevalue_keydocstring says the input is forward-filled. Whenobserved_keyis set, which is howTPCDayOneand the runner use it, the input is raw and may contain NaNs, and the model fills it itself. Please update the docstring to describe both cases.
Optional suggestions:
TPCDayOnecalls underscore-prefixed YAIB internals (_stays,_base_cohort,_dynamic,_features_read,_DYNAMIC_FEATURES). The description should name this link and give a reason, as in item 1.- With
kernel_size=1, the official dilation schedule gives dilation 0 for layers after the first. Consider validating this case or documenting it. - The
toctreeintasks.rstsits apart from the existing task index. You could place it more consistently. - The task API page carries demo-status text that will go stale. You could point to the README instead.
Reviewed commit fe2213b
104feb2 to
fe2213b
Compare
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Completed both requested documentation fixes in e1f53d5. The clinical runner intentionally reuses BASE, METRICS, ablation_configs, and los_metrics from the synthetic example to keep baseline settings, one-factor ablations, and metric definitions identical across runners. Clinical runs exclude synthetic dataset-size experiments; importing the helpers does not generate data or run experiments. This rationale is now in the runner module description and examples/tpc/README.md. The TPC value_key documentation now distinguishes finite, pre-filled input without observed_key from raw input with observed_key, where unobserved values may be NaN and the model fills them internally. The decay_key documentation also clarifies when decay is recomputed. Committed and pushed as Aditya Ramesh adityaramesh15@gmail.com. The current account cannot edit this PR description, so the explanation is recorded here and in the committed documentation. |
Reject kernel_size < 2 for the official multi-layer dilation schedule, move the TPC task into the existing tasks toctree, and keep run status out of the task API page. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
/review Generated by Claude Code |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds a TPC model for ICU length-of-stay prediction, a day-one TPCDayOne task built on the existing YAIB extraction, a synthetic sweep, a clinical runner, tests, docs and measured MIMIC-IV demo results. It is thorough and close to ready. Coverage is well above the bar: 86.4% for the repository, 99.6% for tpc.py and 95.2% for tpc_day_one.py.
To get this merged:
- Name the link between components in the PR description.
examples/eicu_los_tpc.pyimportsBASE,METRICS,ablation_configsandlos_metricsfromexamples/synthetic_icu_los_tpc.py. The module docstring and the README explain this, but the PR description does not. Please either confirm in the description that the sharing is intended and say why, or make the clinical runner self-contained by copying those helpers. - Name the other new link too.
TPCDayOnecalls the private YAIB helpers_stays,_base_cohort,_dynamicand_DYNAMIC_FEATURES, and instantiates the YAIB task classes. The description mentions reusing the YAIB extraction, but please state explicitly that it depends on these private helpers and why. Alternatively, keep the task self-contained.
Optional suggestions:
- In the demo table, LongBias equals -LongMAD in every row. That means every stay of 5 days or more is underpredicted in every run. A sentence on this in the findings would help readers.
- The README is long. The 45-row table could be trimmed to the key rows, with the full table linked or placed in a separate file.
- The tests mock the real
set_tasksplit path. A tiny synthetic test of that path would add confidence.
Reviewed commit b0d2360
|
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. Separately, the AI review's open point is to name, in the description, why |
|
Picked as PyHealth's TPC model. We compared the three TPC models (#1412, #1428, #1574) and the two eICU tasks (#1428, #1627). Yours fits PyHealth best and keeps the paper's layer:
Sizes come from the processors, it runs with the standard Trainer, and coverage is 99.6%. It was also opened first, so it's the primary BTY-72 claimant. Before it can merge:
Next, for fidelity: Once these fixes are pushed, we'll move this PR to |
Added copyright and licensing information for TPCLayer.
|
/review |
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for the TPC contribution. It adds a TPC model with TPCLayer, a TPCDayOne task built on the YAIB extraction, synthetic and clinical runners, docs, and measured MIMIC-IV demo results. The work is thorough and close to ready. Coverage is well above the bar: tpc.py is at 99.6%, tpc_day_one.py at 95.2%, and the whole repository at 87.6%.
To get this merged:
- In
pyhealth/models/tpc.py, the diagnosis encoder usesnn.BatchNorm1d. A training batch with a single stay then raises an error wheneverdiag_keyis used. The default DataLoader can produce such a batch as the last, smaller batch. Please make the encoder safe for batch size 1. For example, use LayerNorm or drop that normalization. Alternatively, document the restriction clearly, validate it, and add a test withdiag_keyand a one-sample batch.
Optional suggestions:
- The clinical runner marks a run FAILED only for ValueError, RuntimeError or OSError. A broader
except Exceptionwould record other failures as well. - Add a direct test of the
set_taskandPatientSplitpath ofTPCDayOne. tests/core/test_tpc.pyimports fixtures from the YAIB test files. Copying the few helpers would keep the tests self-contained.- The description explains the reuse of YAIB private helpers and of the synthetic example's helpers, which is good.
Reviewed commit e2d333c
|
/review |
| stays = source._stays(patient) | ||
| if stays.height == 0: | ||
| return [] | ||
| stays, hourly, static = source._base_cohort(patient, stays) |
There was a problem hiding this comment.
[low] Day-one cohort eligibility uses data after hour 24
The call to source._base_cohort applies YAIB's exclusions over the whole stay. The observation-count rule counts bins outside the first 24 hours, and the gap rule is measured over the stay's first 7 days. A stay's inclusion therefore depends on measurements taken after the prediction time, which a deployed day-one model would not have. The docstring and README disclose this as retrospective. Consider stating in the TPCDayOne docstring that reported metrics are on a cohort selected with future data, or restricting the exclusions to hours 0-23 for a true day-one cohort.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for contributing TPC. It adds the TPC model, a day-one length-of-stay task for eICU and MIMIC-IV, a synthetic ablation example, a local-data clinical runner, API docs, and measured MIMIC-IV demo results. It looks ready to merge.
Why it looks ready
- The model, losses, dilation schedules, decay and no-forward-fill preprocessing, and the adapter's day-one window and label logic match the description and docs. The limitations (running-statistics BatchNorm, YAIB cohort differences, no mortality head) are stated clearly.
- Coverage meets the bar. The whole repository is at 87.6%,
pyhealth/models/tpc.pyis at 99.6%, andpyhealth/tasks/tpc_day_one.pyis at 95.2%. - The links between components are named in the description with reasons.
TPCDayOnereuses YAIB's private extraction helpers to keep the existing cohort and feature definitions. The clinical runner importsBASE,METRICS,ablation_configsandlos_metricsfrom the synthetic example to keep baselines and metrics identical. - The new components are only registered through exports in the package
__init__.pyfiles. No existing export is removed, renamed or rebound.
Optional suggestions
tests/core/test_tpc.pyimports private helpers (_lab,_patient,T0,_admission) from the YAIB test modules. A short note in the description would make that link explicit. Copying the small fixtures would also keep the tests self-contained.tpc_day_one.pydepends on YAIB internals (_features_read,_stays,_base_cohort,_dynamic,_DYNAMIC_FEATURES). A short comment there, or a test that fails clearly if those helpers change, would make future breakage easier to diagnose.- The README and the example docstring each hold the full 45-row table. Keeping the table in one place and linking to it from the other would shorten the docs.
- The blank line you added in
pyhealth/tasks/__init__.pyafter theTPCDayOneimport is unnecessary.
Reviewed commit 00cfc60
Status — MIMIC-IV 2.2 demo measured; full clinical replication pending
The MIMIC-IV Clinical Database Demo 2.2 baseline and complete three-seed
sweep have RUN locally. Full-dataset eICU/MIMIC-IV experiments and
benchmark-comparable results remain PENDING.
This PR contributes the TPC model, extensions, synthetic tests/feasibility
evidence, a clinical runner, and measured small-demo results. It does not
reproduce the paper's eICU/MIMIC benchmark scores. The already-present public
demo was used locally; datasets, patient records, and checkpoints are excluded.
Contributors
Contribution Type: Model (Option 2), UIUC CS 598 DLH.
The supporting adapter reuses existing datasets/extraction; this is not a
claim of full-pipeline extra credit.
Paper: Rocheteau et al., CHIL 2021,
Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the
Intensive Care Unit.
Implementation
Adds TPC(BaseModel) and TPCLayer, implementing grouped temporal convolutions, pointwise feature mixing, and growing skip connections. Supports optional static, time, and diagnosis inputs, with positive remaining-LoS predictions bounded to 30 minutes–100 days.
Includes five dilation schedules (official, paper, constant, linear, exponential), four loss options (MSLE, MSE, asymmetric MSLE, and Huber log-loss), measurement-decay bases, and optional lab no-forward-fill preprocessing. Log losses operate on log(days); normalized labels are rejected. forward returns standard PyHealth regression outputs at the final time step, while forward_sequence exposes predictions across all time steps.
Adds TPCDayOne, a YAIB-based adapter for eICU and MIMIC-IV. It retains the first 24 hourly bins and predicts remaining ICU days at hour 24. Patient splits precede processor fitting to prevent data leakage. The adapter reuses private YAIB extraction helpers to preserve existing cohort and feature definitions, introducing a dependency on YAIB internals.
The clinical runner supports local datasets only, performs validation-MSLE checkpoint selection, and exports per-seed metrics and aggregate tables. Preparation is the default; training requires explicit --run, a local data root, and a documented dataset version. No datasets are downloaded. The synthetic and clinical runners share their baseline, ablation configurations, and metric definitions.
Reviewer file guide
pyhealth/models/tpc.pypyhealth/models/__init__.pyTPC/TPCLayerexportspyhealth/tasks/tpc_day_one.pypyhealth/tasks/__init__.pyTPCDayOneexporttests/core/test_tpc.pyexamples/synthetic_icu_los_tpc.pyexamples/eicu_los_tpc.pyexamples/tpc/README.mddocs/api/models/pyhealth.models.tpc.rstanddocs/api/models.rstdocs/api/tasks/pyhealth.tasks.tpc_day_one.rstanddocs/api/tasks.rstMeasured MIMIC-IV demo results — not full clinical reproduction
Demo source: 100 patients /
140 source ICU stays; the day-one YAIB-based cohort retains 88 patients /
117 stays. Values are mean +/- sample standard deviation over seeds 0/1/2.
Patient counts per seed: train/validation/test = 61/13/14; stay counts =
85/14/18, 80/17/20, and 75/21/21. Baseline selected epochs = 3/4/3.
Long-stay test counts = 3/3/4. The complete 135-training sweep took 149.51
seconds on an Apple M4 Pro with one PyTorch CPU thread, using warm caches.
The seven source files matched the supplied SHA256 checksums. A separate
three-seed baseline exactly reproduced the sweep baseline.
Negative R2 and negative bias show poor squared-error performance and
underprediction, particularly on long stays. The small loss/decay differences
are not compelling relative to seed variation. Asymmetric MSLE's synthetic
benefit did not clearly transfer. Temporal width 13 had the lowest observed
mean MSLE (1.834 +/- 0.434), but this is descriptive, not independently
validated selection across 45 test-evaluated rows. All rows have negative mean
R2. Different seeds also change patient partitions; subgroup counts are tiny.
No hyperparameters were retuned after inspecting test performance.
In every row, long-stay bias equals the negative of long-stay MAD, so every test stay of 5 days or more was underpredicted in every seed. With only 3/3/4 such stays per seed, this shows a consistent direction of error, not a precise estimate of its size.
Full-dataset cohorts, experiments, benchmark-comparable scores, and comparison
with published paper performance remain PENDING. Different feature/cohort and
day-one training definitions prevent a like-for-like benchmark comparison.
Executed demo protocol
The demo sweep contains 45 matched one-factor labels and three seeds
(paper/linear are identical aliases). Sweeps cover layers 1/3/5/9, kernels 2–5, each integer temporal
and pointwise channel count 4–16, dropout 0/0.2/0.45, and learning rates
0.001/0.0023/0.01. Baseline values cover unchanged settings. Extensions cover
alternative dilation, asymmetric/Huber losses, decay 0.5/0.75/0.9, and lab
no-forward-fill. Report MAD, MAPE, MSLE, R2, bias, >=5-day long-stay MAD/bias,
and subgroup counts as three-seed mean +/- sample standard deviation.
The compute-constrained baseline is N=3, k=4, Y=Z=4, main dropout=0.2,
temporal dropout=0.05, official dilation, MSLE, Adam learning rate 0.0023,
batch size 32, and eight epochs. Use 70/15/15 patient splits independently
for seeds 0/1/2, sharing each seed's partition across all configurations.
Select on validation MSLE and evaluate the selected checkpoint once on test.
Linear is identical to the paper schedule, not a separate novelty.
MSE vs. MSLE is explicitly a Sanity Check. Dataset-size comparisons in
the synthetic example are a Compute-Constraint Demonstration, not novel
credit. Hyperparameter sweeps are sensitivity analyses.
Existing synthetic evidence (not clinical reproduction)
The synthetic example already embeds its measured 47-configuration,
three-seed feasibility sweep. These numbers remain clearly labelled synthetic
and are not substituted into clinical placeholders or compared numerically
with another team's clinical scores. The demo findings above are separate
from synthetic evidence; full-cohort clinical extension findings remain PENDING.
Usage
Preparation without dataset access or training:
Future training, only after authorized eICU data are available locally:
Use
--dataset mimic4with the actual MIMIC-IV release/root as appropriate.See the README for full-sweep execution and dataset-file requirements.
Each output directory must be new. No patient IDs or predictions are written
into the aggregate result tables; data/caches/checkpoints stay local and ignored.
Validation and Limitations
-46 focused tests/doctests pass, with 17 subtests. Tests use synthetic fixtures.
-The MIMIC-IV 2.2 demo ran end to end. Full MIMIC-IV and eICU execution remain unverified.
-The YAIB cohort differs from the original TPC paper's cohort. This implementation trains at day one rather than every hour and uses 48 dynamic and four static features, without diagnosis or additional time inputs.
-Standard BatchNorm uses running statistics during inference rather than the original implementation's batch-statistics inference. Causality is enforced during evaluation.
-No mortality head, multitask objective, or variable-length masked loss is implemented.
-Full-dataset clinical experiments and comparisons against published TPC results remain pending.