Skip to content

Add TPC-style Hourly Length-of-Stay Prediction Task for eICU - #1627

Open
ahling21 wants to merge 44 commits into
sunlabuiuc:masterfrom
EmilyJYN:feature/tpc-eicu-los
Open

ahling21 wants to merge 44 commits into
sunlabuiuc:masterfrom
EmilyJYN:feature/tpc-eicu-los

Conversation

@ahling21

@ahling21 ahling21 commented Nov 27, 2026 •

Copy link
Copy Markdown

Contributors

Name NetID Email
Manling Tan manling4 manling4@illinois.edu
Yining Jin yining34 yining34@illinois.edu
Xiao Luo xiaoluo6 xiaoluo6@illinois.edu

Type of Contribution

Standalone Task (Option 3) for the existing PyHealth eICU dataset.

Original Paper

Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the Intensive Care Unit

Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021).

Paper: https://arxiv.org/abs/2007.09483

Overview

This PR introduces TPCLengthOfStayEICU, an hourly remaining ICU length-of-stay (LOS) prediction task inspired by the original TPC paper.

The implementation extends the existing YAIBLengthOfStayEICU task and reuses PyHealth's eICU data loading, feature extraction, and preprocessing infrastructure.

Our contribution focuses on reproducing the hourly remaining-LOS prediction task rather than implementing the original TPC model architecture. We use PyHealth's existing RNN_V2 with an LSTM architecture to evaluate the task and conduct a novel missingness robustness ablation study.

Implementation Details

The new task supports:

  • Adult ICU patients aged 18 or older with a minimum ICU stay of 5 hours.
  • Hourly prediction of remaining ICU length of stay, starting at hour 5, with a maximum observation horizon of 14 days.
  • 48 dynamic clinical features and 4 static admission features.
  • Hourly aggregation of clinical observations using completed observation windows to prevent future information leakage.
  • Forward-fill imputation, normalization, and missingness indicators through PyHealth's existing processors.
  • Configurable random observation removal through missing_rate, applied before forward-fill imputation.
  • Reproducible, stay-specific missingness generation.
  • Optional exponential decay features through include_decay.
  • Isolation of observations across different ICU stays.
  • Compatibility with PyHealth's current YAIB task and RNN_V2 interfaces.

The 14-day observation horizon limits the prediction timeline rather than truncating the remaining-LOS labels.

Cohort Selection

The task uses its own cohort eligibility criteria to support TPC-style hourly remaining-LOS prediction. It does not inherit all of the original YAIB base-cohort exclusions.

Implementation Dependencies

  • Synthetic data and test fixtures: The synthetic data generator (examples/tpc_support/generate_synthetic.py) and test fixtures (tests/core/tpc_fixtures.py) intentionally read pyhealth/datasets/configs/eicu.yaml to keep the synthetic CSV schema and test columns consistent with PyHealth's eICU dataset configuration.

  • YAIB dependency: The task intentionally reuses YAIB's private preprocessing helpers and _DYNAMIC_FEATURES constant to maintain preprocessing consistency and avoid duplicate implementations. Future changes to these YAIB internals may therefore require corresponding updates to this task.

Ablation Study: Missingness Robustness

We investigate whether introducing additional observation missingness during training improves model robustness to missing observations at inference time.

The experiment follows a 2 × 3 design:

  • Model A: trained with 0% additional observation removal.
  • Model B: trained with 10% additional observation removal.
  • Both models are evaluated under 0%, 10%, and 20% additional observation removal on held-out test patients.

Observation removal is performed before imputation. Both models use identical patient-level splits and deterministic test masking to ensure comparable evaluation conditions.

Each model reuses its own training-fitted preprocessing and normalization processors when evaluating the different test missingness conditions.

This extension investigates training-time observation removal as a robustness intervention, rather than simply repeating the original paper's decay-removal ablation.

Experimental Setup

  • Dataset: 15,000 randomly sampled eICU-CRD patients.
  • Patient-disjoint split: 70% training, 15% validation, and 15% testing.
  • Random seed: 42.
  • Model: PyHealth RNN_V2 (LSTM).
  • Embedding dimension: 64.
  • Hidden dimension: 128.
  • Number of layers: 2.
  • Dropout: 0.2.
  • Learning rate: 0.00129.
  • Batch size: 128.
  • Training epochs: 8.
  • Decay features: enabled.
  • Training objective: MSE loss on normalized remaining-LOS targets.
  • Evaluation metrics: MAD, MAPE, MSE, MSLE, R², and Cohen's linear weighted Kappa.

Evaluation Metrics

LOS targets and predictions are converted from hours to days before evaluation.

Following the metric conventions described in the original paper:

  • MAD measures mean absolute prediction error.
  • MAPE uses a minimum target denominator of 4 hours to prevent numerical instability near discharge.
  • MSE measures squared prediction error.
  • MSLE clips targets and predictions to the interval [1/48, 100] days before computing squared log-space error.
  • R² measures the coefficient of determination.
  • Cohen's linear weighted Kappa uses 10 ordered LOS categories: 0–1, 1–2, 2–3, 3–4, 4–5, 5–6, 6–7, 7–8, 8–14, and 14+ days.

Experimental Results (Pre-Rebase)

The following numerical results were obtained before rebasing onto upstream PyHealth, using a batch size of 128. The full 15,000-patient experiment has not been rerun after the rebase.

Model Train Drop Test Drop MAD MAPE (%) MSE MSLE R² Kappa
Mean Baseline 0% 0% 3.336 413.3 28.24 2.750 -0.002 0.000
Median Baseline 0% 0% 2.837 187.8 31.32 2.008 -0.111 0.000
LSTM A 0% 0% 2.859 260.7 24.72 2.266 0.123 0.253
LSTM A 0% 10% 2.839 255.6 24.79 2.256 0.120 0.247
LSTM A 0% 20% 2.819 251.1 24.84 2.223 0.118 0.243
LSTM B 10% 0% 2.893 271.6 24.74 2.205 0.122 0.252
LSTM B 10% 10% 2.869 266.3 24.76 2.189 0.121 0.247
LSTM B 10% 20% 2.844 261.1 24.77 2.153 0.121 0.243

Findings

  • The mean and median baselines are reasonably consistent with those reported in the original paper.
  • Under the 0% additional missingness condition, our standard LSTM achieves an MSE of 24.72, compared with 24.5 for the standard LSTM (MSE) reported in the original paper.
  • When test missingness increases from 0% to 20%, Model A's MSE increases by 0.12, whereas Model B's MSE increases by only 0.03.
  • Under the same increase in test missingness, Model A's R² decreases by 0.005, whereas Model B's R² decreases by only 0.001.
  • Model B demonstrates improved MSE, R², and MSLE relative to Model A under the 10% and 20% additional missingness conditions, although the improvement is not consistent across all metrics.

These results suggest that training with additional observation removal may improve robustness under increased test-time missingness.

Differences from the original paper include the smaller patient subset, different feature sets, and the use of PyHealth's existing LSTM implementation instead of the original TPC architecture.

File Guide

Core Implementation

  • pyhealth/tasks/tpc_eicu.py — Implements the hourly remaining-LOS task, cohort selection, temporal alignment, missingness simulation, and optional decay features.
  • pyhealth/tasks/__init__.py — Exports the new task.

Documentation

  • docs/api/tasks/pyhealth.tasks.tpc_eicu.rst — API documentation, task description, usage instructions, and experimental overview.
  • docs/api/tasks.rst — Registers the task in the API documentation index.

Example and Supporting Utilities

  • examples/eicu_hourly_los_lstm.py — LSTM training, baseline evaluation, six evaluation metrics, and the 2 × 3 missingness robustness ablation study.
  • examples/tpc_support/checkpoint.py — Synthetic data validation checkpoint.
  • examples/tpc_support/generate_synthetic.py — Synthetic eICU data generator.
  • examples/tpc_support/synthetic_eicu/ — Seven synthetic CSV files representing the required eICU clinical tables. These files provide inspectable examples of the synthetic data format. The generator regenerates the synthetic CSV files during execution.

Tests

  • tests/core/test_tpc_eicu.py — Unit tests covering cohort eligibility, static features, hourly aggregation, remaining-LOS labels, observation removal, decay, temporal leakage prevention, stay isolation, and timeline configuration.
  • tests/core/tpc_fixtures.py — Reusable synthetic patient fixtures.
  • tests/integration/test_tpc_checkpoint.py — Opt-in synthetic CSV-to-task integration test.

Usage Examples

Run the Synthetic-Data Example

python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2

Run the Full Missingness Ablation Study

python examples/eicu_hourly_los_lstm.py --root /path/to/eicu-crd --batch-size 128 --epochs 8 --lr 0.00129 --embedding-dim 64 --hidden-dim 128 --num-layers 2 --dropout 0.2 --seed 42

To reproduce the reported experimental setup, use the same 15,000-patient eICU subset. Running this command on a different patient cohort may produce different numerical results.

Run the Unit Tests

python -m pytest tests/core/test_tpc_eicu.py -q

Run the Unit and Integration Tests

Linux/macOS:

PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/core/test_tpc_eicu.py tests/integration/test_tpc_checkpoint.py -q

Windows CMD:

set PYHEALTH_RUN_TPC_INTEGRATION=1
python -m pytest tests/core/test_tpc_eicu.py tests/integration/test_tpc_checkpoint.py -q

Testing and Validation

All committed tests use synthetic or pseudo-patient data. No real patient records are included in this PR.

Following the rebase and compatibility updates, the following checks were completed:

  • 29 unit tests passed.
  • 1 synthetic CSV integration test passed.
  • Total: 30 passed, 0 failed, 0 skipped.
  • Independent RNN_V2 smoke test passed.
  • Git diff whitespace and conflict-marker checks passed.

The independent RNN_V2 smoke test successfully verified:

  • Synthetic patient and sample generation.
  • SampleDataset construction.
  • Model initialization with dynamic, static, and decay features.
  • Forward propagation.
  • Finite loss computation.
  • Backward propagation.
  • Optimizer parameter updates.
  • Model prediction.

The CSV integration test is opt-in to avoid unnecessary data-loading overhead during routine unit testing.

Post-Rebase Validation Scope

The full synthetic training example was also attempted after rebasing but was interrupted during event-dataframe cache construction in the local Windows environment.

An independent in-memory smoke test was subsequently used to verify the core model training and prediction functionality.

The post-rebase tests validate the task implementation and its compatibility with RNN_V2. They do not constitute a complete rerun of the pre-rebase 15,000-patient experiment.

Upstream Compatibility

This contribution has been rebased onto the upstream PyHealth master branch.

To accommodate the recent YAIB and RNN_V2 changes introduced in PR #1461:

  • Updated the task to use _static_record instead of _static_series.
  • Adopted the inherited single ordering for static features.
  • Explicitly included optional decay features in the prediction timeline when enabled.
  • Added a regression test to ensure that optional timeline configuration does not affect other task instances.

These changes preserve the intended temporal alignment and prevent optional decay features from being treated as whole-stay information during hourly prediction.

Checklist

  • Standalone task implemented using an existing PyHealth dataset.
  • Existing PyHealth model used for evaluation.
  • API documentation and documentation index updated.
  • Example script and missingness ablation study included.
  • Synthetic data and comprehensive task tests included.
  • Original paper referenced.
  • Rebased onto the upstream master branch.
  • Upstream API compatibility addressed.
  • Implementation dependencies documented.
  • Experimental configuration and pre-rebase results documented.
  • All 30 unit and integration tests passed after the rebase.
  • Independent RNN_V2 training and prediction smoke test passed after the rebase.

Thank you for reviewing our contribution. We welcome feedback and suggestions from the PyHealth maintainers.

ahling21 and others added 30 commits November 26, 2026 15:30
Add complete docstring
Add docstring
Add docstring and apply black
Added header for paper title, authors, URL, and team mates name
Added team mates name, paper title, author and URL
Added paper title, author, URL and team mates name
Update TPC eICU tests for missingness and decay
Change heading for formatting
Changed headers
Changed headers
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.76% (48483 / 55882 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 83 / 83
pyhealth/datasets/cardiology.py 98.61% 71 / 72
pyhealth/datasets/cdc_covid.py 92.59% 25 / 27
pyhealth/datasets/mimic3.py 100.00% 21 / 21
pyhealth/datasets/mimic4.py 95.80% 114 / 119
pyhealth/datasets/omop.py 96.88% 31 / 32
pyhealth/models/__init__.py 100.00% 96 / 96
pyhealth/models/clip_stress.py 91.67% 154 / 168
pyhealth/models/clip_stress_layers.py 98.39% 61 / 62
pyhealth/models/clip_stress_utils.py 86.86% 119 / 137
pyhealth/models/concare.py 77.09% 286 / 371
pyhealth/models/ecg_jepa.py 100.00% 121 / 121
pyhealth/models/stagenet.py 96.10% 197 / 205
pyhealth/models/stagenet_mha.py 94.33% 266 / 282
pyhealth/models/text_embedding.py 95.70% 89 / 93
pyhealth/processors/nested_sequence_processor.py 93.75% 165 / 176
pyhealth/processors/utils.py 96.61% 57 / 59
pyhealth/tasks/__init__.py 98.18% 108 / 110
pyhealth/tasks/cdc_covid_mortality.py 91.55% 65 / 71
pyhealth/tasks/climb_ecg.py 98.59% 70 / 71
pyhealth/tasks/cpsc2018_heartlang.py 97.98% 97 / 99
pyhealth/tasks/length_of_stay_prediction.py 77.30% 109 / 141
pyhealth/tasks/mortality_prediction.py 90.29% 400 / 443
pyhealth/tasks/readmission_prediction.py 94.69% 214 / 226
pyhealth/tasks/tpc_eicu.py 97.30% 72 / 74
pyhealth/tasks/variant_classification.py 89.29% 50 / 56
pyhealth/utils.py 83.70% 77 / 92

Workflow run · d7f644f

@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 4af6fe2

Comment thread examples/eicu_hourly_los_lstm.py Outdated
)
parser.set_defaults(include_decay=True)
parser.add_argument("--epochs", type=int, default=8)
parser.add_argument("--batch-size", type=int, default=64)

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] Default batch size contradicts documented setting

The documented setting is batch_size=128 (module docstring, line 49, and the PR description), but the CLI default here is 64 (train_and_evaluate also defaults to 64 at line 357). The documented command python examples/eicu_hourly_los_lstm.py --root /path/to/eicu-crd therefore trains with a different batch size and does not reproduce the reported table. Set the default to 128 in both places, or correct the documented setting.

from pyhealth.data import Patient

# Every column of the eICU config, as in the dataset's event dataframe.
_CONFIG = yaml.safe_load(

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] Test fixtures read the eICU dataset config, which the description does not explain

The fixture loads pyhealth/datasets/configs/eicu.yaml to derive its column list. examples/tpc_support/generate_synthetic.py:38 does the same. This makes the tests and synthetic data depend on another component's config, and that link is not mentioned in the description. Either explain the link in the description and say why, or keep these helpers self-contained by listing the columns they need directly.

DEFAULT_TEST_RATES = (0.0, 0.1, 0.2)


def compute_los_metrics(

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] New LOS metrics are untested and partly duplicate existing metrics

compute_los_metrics implements MAD and MSE, which pyhealth/metrics/regression.py already provides through regression_metrics_fn and timeseries_regression_metrics_fn. The MAPE floor, MSLE clipping and kappa binning are untested, yet they produce the reported table. A few unit tests for this function would cover them, and the MAE/MSE part could reuse the existing metric functions.

@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: need change
decision: human review

Thank you for this contribution. It adds an hourly remaining-LOS task for eICU (TPCLengthOfStayEICU) that extends the YAIB task. It also adds a missingness-robustness example, synthetic data and tests. Coverage is good: tpc_eicu.py is at 97.3% and the whole repository is at 86.65%, which is above the bar. The task is self-contained, and the only shared-file edit is its export in tasks/init.py.

To get this merged:

  1. The example's --batch-size defaults to 64 (and so does train_and_evaluate). The docstring, the description and the reported results all use 128. Please change the default to 128, or say in the docs which setting produced the table, so that the documented command reproduces the results.
  2. examples/tpc_support/generate_synthetic.py and tests/core/tpc_fixtures.py both read pyhealth/datasets/configs/eicu.yaml. The description doesn't mention this. Please either confirm in the description that this coupling is intended and say why (for example, to keep the CSV schema in sync with the dataset config), or make those files self-contained.
  3. The description says the task reuses YAIB's private helpers and the _DYNAMIC_FEATURES constant, and it also says the task "extends" YAIB. Please add one sentence saying why these private internals are reused. For example, say that they're reused so the preprocessing matches YAIB, and note that changes to YAIB will therefore affect this task.

Optional suggestions:

  • Add tests for the example's MAPE, MSLE and Kappa code. You could also reuse pyhealth.metrics.regression for MAE and MSE, but only if you choose to share that code and explain why.
  • The committed synthetic_eicu/ CSVs aren't used by any code, because the generator rewrites them. Consider removing them or documenting their purpose.
  • The task's cohort drops YAIB's base-cohort exclusions. A short note in the docs would help.
  • The reported numbers were produced before the rebase. Rerunning the full experiment, or stating this prominently in the docs, would help.
  • The description text is duplicated (an HTML copy and a Markdown copy). Please tidy it.
  • Move the from .tpc_eicu import ... line in tasks/__init__.py up with the other imports.

Reviewed commit 4af6fe2

@ahling21

Copy link
Copy Markdown
Author

Thank you for the helpful review.

We have addressed all three main review comments:

  1. Updated the default batch size to 128 in both train_and_evaluate() and the CLI argument parser.
  2. Clarified the intentional dependency on the eICU dataset configuration.
  3. Explained the rationale for reusing YAIB's private preprocessing helpers and dynamic feature definitions.

We also cleaned up the duplicated PR description, clarified cohort selection and synthetic CSV usage, and prominently identified the experimental results as pre-rebase results.

All 30 unit and integration tests passed after the update, and git diff --check reported no issues.

Updated commit: d7f644f5.

Thank you for your feedback.

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.

4 participants