-
Notifications
You must be signed in to change notification settings - Fork 782
Add MEDS dataset support (MEDSDataset + typed Parquet scan path) #1179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AxelNoun
wants to merge
13
commits into
sunlabuiuc:master
Choose a base branch
from
AxelNoun:feat/meds-dataset
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,526
−11
Open
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
074d144
feat(datasets): add Parquet scan path to BaseDataset
AxelNoun 84c1d73
feat(datasets): add MEDSDataset for the Medical Event Data Standard
AxelNoun 7be9547
test(datasets): add MEDS synthetic and demo smoke tests
AxelNoun d8bac4a
docs(examples): add MEDS example and API docs
AxelNoun 7daa754
feat(tasks): add InHospitalMortalityMEDS
AxelNoun 8d75571
fix(tasks): re-export InHospitalMortalityMEDS with explicit alias
AxelNoun 7bebb45
docs: link MEDS schema docs for subject_splits mapping
AxelNoun 070caa1
refactor: rename _reconstruct_stays to _group_stays and clarify summa…
AxelNoun 9032e3d
docs: add end-to-end RNN training to MEDS demo
AxelNoun fea8659
docs: link subject_splits in MEDSDataset API page; qualify demo metri…
AxelNoun 141ba2f
refactor: drop summarize helper from InHospitalMortalityMEDS
AxelNoun 336dc35
style: modernize typing annotations, drop unused noqa (UP006/UP035/UP…
AxelNoun 86bb15a
Merge remote-tracking branch 'upstream/master' into feat/meds-dataset
AxelNoun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| pyhealth.datasets.MEDSDataset | ||
| =================================== | ||
|
|
||
| Dataset class for data in the `Medical Event Data Standard (MEDS) <https://github.com/Medical-Event-Data-Standard/meds>`_, a minimal event-based schema for machine learning over EHR data (Arnrich et al., ICLR 2024 Workshop on Learning from Time Series For Health). Sharded Parquet event files are read with their native types, and standard MEDS splits (train / tuning / held_out) can be selected directly via the ``subset`` argument. | ||
|
|
||
| .. autoclass:: pyhealth.datasets.MEDSDataset | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| pyhealth.tasks.InHospitalMortalityMEDS | ||
| ====================================== | ||
|
|
||
| .. autoclass:: pyhealth.tasks.in_hospital_mortality_meds.InHospitalMortalityMEDS | ||
| :members: | ||
| :undoc-members: | ||
| :show-inheritance: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| """End-to-end example: loading a MEDS dataset with PyHealth. | ||
|
|
||
| This example uses the public *MIMIC-IV demo data in the Medical Event Data | ||
| Standard (MEDS)* (PhysioNet, v0.0.1, ODbL v1.0, ~100 subjects): | ||
| https://doi.org/10.13026/t2y8-ea41 | ||
|
|
||
| Download it once (open access, ~a few MB): | ||
|
|
||
| wget -r -N -c -np https://physionet.org/files/mimic-iv-demo-meds/0.0.1/ | ||
|
|
||
| Then run: | ||
|
|
||
| python examples/meds_demo.py \\ | ||
| --root physionet.org/files/mimic-iv-demo-meds/0.0.1 | ||
|
|
||
| Any dataset following the MEDS layout (``data/**.parquet`` + | ||
| ``metadata/subject_splits.parquet``) works the same way. See the MEDS | ||
| specification: https://github.com/Medical-Event-Data-Standard/meds | ||
| """ | ||
|
|
||
| import argparse | ||
|
|
||
| import polars as pl | ||
|
|
||
| from pyhealth.datasets import MEDSDataset | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument( | ||
| "--root", | ||
| required=True, | ||
| help="Root of the MEDS dataset (directory containing data/ and " | ||
| "metadata/)", | ||
| ) | ||
| parser.add_argument( | ||
| "--subset", | ||
| default="train", | ||
| help="Split to load as a subset (default: train)", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| # 1) Load the full dataset: every Parquet shard under data/ is read, | ||
| # including nested split directories (data/<split>/<shard>.parquet). | ||
| dataset = MEDSDataset(root=args.root) | ||
| dataset.stats() | ||
|
|
||
| # 2) Peek at the canonical event frame (typed straight from Parquet: | ||
| # string patient ids, datetime64[ms] timestamps, float values). | ||
| events = dataset.global_event_df | ||
| print(events.head(5).collect()) | ||
|
|
||
| # 3) Load a split-restricted subset. Subjects are selected through the | ||
| # metadata/subject_splits.parquet assignment; each subset uses its | ||
| # own processing cache. | ||
| subset = MEDSDataset(root=args.root, subset=args.subset) | ||
| n_subset = len(subset.unique_patient_ids) | ||
| n_total = len(dataset.unique_patient_ids) | ||
| print(f"Subjects in subset '{args.subset}': {n_subset} / {n_total}") | ||
|
|
||
| # 4) Static (null-time) MEDS events, e.g. demographics, are preserved. | ||
| n_static = ( | ||
| events.filter(pl.col("timestamp").is_null()) | ||
| .select(pl.len()) | ||
| .collect() | ||
| .item() | ||
| ) | ||
| print(f"Static (null-time) events: {n_static}") | ||
|
|
||
| # From here, the dataset behaves like any other PyHealth dataset: use | ||
| # `dataset.set_task(...)` with an existing task to build samples. | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # BaseDataset spawns Dask worker processes; keep the main-module guard. | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Standalone verification of the MEDS in-hospital mortality cohort. | ||
|
|
||
| Prints the cohort summary produced by ``InHospitalMortalityMEDS`` on a MEDS | ||
| dataset, so the positive rate (expected ~12/238 on the public MIMIC-IV demo) | ||
| can be confirmed through the actual task pipeline rather than only at the raw | ||
| Parquet level. | ||
|
|
||
| Usage: | ||
| # Download the public demo once (open access, ODbL v1.0): | ||
| # wget -r -N -c -np https://physionet.org/files/mimic-iv-demo-meds/0.0.1/ | ||
| python verify_meds_mortality.py \\ | ||
| --root physionet.org/files/mimic-iv-demo-meds/0.0.1 | ||
|
|
||
| The task needs hadm_id; this script uses the bundled | ||
| ``configs/meds_with_hadm.yaml`` automatically. | ||
| """ | ||
|
|
||
| import argparse | ||
| from pathlib import Path | ||
|
|
||
| import pyhealth.datasets.configs as meds_configs | ||
| from pyhealth.datasets import MEDSDataset | ||
| from pyhealth.tasks import InHospitalMortalityMEDS | ||
|
|
||
|
|
||
| def main() -> None: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument( | ||
| "--root", | ||
| required=True, | ||
| help="Root of the MEDS dataset (contains data/ and metadata/).", | ||
| ) | ||
| parser.add_argument( | ||
| "--observation-window", | ||
| default="full_stay", | ||
| choices=["full_stay", "first_hours"], | ||
| ) | ||
| parser.add_argument("--window-hours", type=float, default=48.0) | ||
| args = parser.parse_args() | ||
|
|
||
| cfg = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" | ||
| dataset = MEDSDataset(root=args.root, config_path=str(cfg)) | ||
| task = InHospitalMortalityMEDS( | ||
| observation_window=args.observation_window, | ||
| window_hours=args.window_hours, | ||
| ) | ||
|
|
||
| # Apply per patient to keep raw (untokenized) samples, so the label | ||
| # counts are directly inspectable. set_task would tokenize the codes. | ||
| samples = [] | ||
| for patient_id in dataset.unique_patient_ids: | ||
| samples.extend(task(dataset.get_patient(patient_id))) | ||
|
|
||
| summary = InHospitalMortalityMEDS.summarize(samples) | ||
| print(f"root : {args.root}") | ||
| print(f"observation_window : {args.observation_window}") | ||
| print(f"n_samples (stays) : {summary['n_samples']}") | ||
| print(f"n_patients : {summary['n_patients']}") | ||
| print(f"n_positive (died) : {summary['n_positive']}") | ||
| print(f"positive_rate : {summary['positive_rate']:.4f}") | ||
| print(f"mean_sequence_length : {summary['mean_sequence_length']:.1f}") | ||
|
|
||
| # Cross-check the intended user path returns the same sample count. | ||
| sample_dataset = dataset.set_task(task) | ||
| print(f"set_task sample count : {len(sample_dataset)} (should equal n_samples)") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # MEDS (Medical Event Data Standard) tables. | ||
| # | ||
| # MEDS is already flat (one row per measurement), so a single event table | ||
| # covers the data shards. The canonical subject-to-split mapping is exposed | ||
| # as a second, ordinary event table -- the same pattern as the `splits` | ||
| # table in ehrshot.yaml. TableConfig has no format field: Parquet reading is | ||
| # handled by BaseDataset._scan_table / _scan_parquet, so no config-schema | ||
| # change is needed for the 21 existing datasets. | ||
| # | ||
| # Paths match mimic-iv-demo-meds: data/<split>/*.parquet + | ||
| # metadata/subject_splits.parquet. | ||
| version: "1.0" | ||
| tables: | ||
| meds: | ||
| # Directory of shards; dd.read_parquet reads the nested tree whole. | ||
| file_path: "data" | ||
| patient_id: "subject_id" | ||
| # Native datetime64[us] in MEDS Parquet, narrowed to [ms] by the | ||
| # BaseDataset typed-timestamp fast-path. No timestamp_format: that | ||
| # would imply text parsing. MEDSDataset rejects non-timestamp / | ||
| # tz-aware columns at construction (footer schema guard). | ||
| timestamp: "time" | ||
| attributes: | ||
| - "code" | ||
| - "numeric_value" | ||
|
|
||
| # Canonical split map as events (attribute `subject_splits/split`). | ||
| # Opt-in: tables=["meds", "subject_splits"]. | ||
| subject_splits: | ||
| file_path: "metadata/subject_splits.parquet" | ||
| patient_id: "subject_id" | ||
| timestamp: null | ||
| attributes: | ||
| - "split" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we try training an RNN model at all on this? from pyhealth.models. That would help us showcase it works.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added: set_task(InHospitalMortalityMEDS()) → pyhealth.models.RNN → Trainer, on the full demo cohort (238 stays, 80/10/10). Full-stay sequences run ~3k codes, so the demo truncates to the last 256 per stay via a local wrapper task API unchanged. ~2.5 min on CPU, mostly dataset loading rather than training. It's a smoke test that the MEDS path works with the existing stack, not a benchmark. Happy to expose the cap as a task parameter if that'd be generally useful.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Follow-up with a local run on the PhysioNet demo (CPU, ~2.5 min total):
(Metrics are noise on this tiny demo; included only to show the path runs end-to-end.)