Skill Tracer
Skills › Scientific Agent Skills › pyhealth › datasets.md

datasets.md

114 lines · skills/pyhealth/references/datasets.md at 5f2bc03

Open on GitHub
1# Datasets and event access
2
3Contracts below were checked in the released PyHealth 2.0.2 wheel and
4[dataset documentation](https://pyhealth.readthedocs.io/en/latest/api/datasets.html).
5Constructors are not interchangeable across modalities.
6

Datasets and event access

Contracts below were checked in the released PyHealth 2.0.2 wheel and dataset documentation. Constructors are not interchangeable across modalities.

Raw lines 1 to 6
7## Two dataset layers
8
9`BaseDataset` exposes a lazy, table-backed event registry. `get_patient(id)` and
10`iter_patients()` return `Patient` objects; `set_task(task)` builds a processed,
11indexable sample dataset. Use those samples with models, splitters and data loaders.
12`create_sample_dataset(records, input_schema=..., output_schema=...)` is the public
13helper for in-memory dictionaries; `SampleDataset(...)` itself takes a cache path,
14not `samples=`.
16```python
17from pyhealth.datasets import MIMIC3Dataset
18base = MIMIC3Dataset(
19 root="https://storage.googleapis.com/pyhealth/Synthetic_MIMIC-III/",
20 tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
21 cache_dir="./cache/mimic3", num_workers=1, dev=True,
23```
25The MIMIC-III constructor automatically adds `patients`, `admissions`, `icustays`.
26All selectors above are lowercase; the bundled config translates them to uppercase
27CSV filenames. `labevents` additionally needs `D_LABITEMS`; note events have their own
28recording-time and availability caveats.

Two dataset layers

BaseDataset exposes a lazy, table-backed event registry. get_patient(id) and iter_patients() return Patient objects; set_task(task) builds a processed, indexable sample dataset. Use those samples with models, splitters and data loaders. create_sample_dataset(records, input_schema=..., output_schema=...) is the public helper for in-memory dictionaries; SampleDataset(...) itself takes a cache path, not samples=.

from pyhealth.datasets import MIMIC3Dataset
base = MIMIC3Dataset(
    root="https://storage.googleapis.com/pyhealth/Synthetic_MIMIC-III/",
    tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
    cache_dir="./cache/mimic3", num_workers=1, dev=True,
)

The MIMIC-III constructor automatically adds patients, admissions, icustays. All selectors above are lowercase; the bundled config translates them to uppercase CSV filenames. labevents additionally needs D_LABITEMS; note events have their own recording-time and availability caveats.

Raw lines 7 to 29
30## MIMIC-IV: two supported constructors
32```python
33from pyhealth.datasets import MIMIC4Dataset, MIMIC4EHRDataset
35# Combined EHR/note/CXR wrapper: modality-specific argument names
36combined = MIMIC4Dataset(
37 ehr_root="./data/mimic-iv",
38 ehr_tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
39 cache_dir="./cache/mimic4",
41# EHR-only reader: ordinary root/tables arguments
42base = MIMIC4EHRDataset(
43 root="./data/mimic-iv",
44 tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
45 cache_dir="./cache/mimic4-ehr",
47```
49Both roots contain `hosp/` and `icu/`. `tables=` is not an argument to the combined
50wrapper. Its other modalities use `note_root`/`note_tables`, `cxr_root`/`cxr_tables`.
51These restricted-data examples are illustrative; constructor/config contracts were
52verified, but no private MIMIC-IV records were loaded.

MIMIC-IV: two supported constructors

from pyhealth.datasets import MIMIC4Dataset, MIMIC4EHRDataset

# Combined EHR/note/CXR wrapper: modality-specific argument names
combined = MIMIC4Dataset(
    ehr_root="./data/mimic-iv",
    ehr_tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
    cache_dir="./cache/mimic4",
)
# EHR-only reader: ordinary root/tables arguments
base = MIMIC4EHRDataset(
    root="./data/mimic-iv",
    tables=["diagnoses_icd", "procedures_icd", "prescriptions"],
    cache_dir="./cache/mimic4-ehr",
)

Both roots contain hosp/ and icu/. tables= is not an argument to the combined wrapper. Its other modalities use note_root/note_tables, cxr_root/cxr_tables. These restricted-data examples are illustrative; constructor/config contracts were verified, but no private MIMIC-IV records were loaded.

Raw lines 30 to 53
54## Available dataset families
56These names are exported by 2.0.2; this inventory does not certify every task/model
57combination or dataset release. Read the selected class and bundled config first.
59| Family | Classes |
60|---|---|
61| EHR | `MIMIC3Dataset`, `MIMIC4Dataset`, `MIMIC4EHRDataset`, `eICUDataset`, `OMOPDataset`, `MIMICExtractDataset`, `EHRShotDataset`, `Support2Dataset` |
62| Sleep/signals | `SleepEDFDataset`, `SHHSDataset`, `ISRUCDataset`, `TUABDataset`, `TUEVDataset`, `CardiologyDataset`, `DREAMTDataset`, `BMDHSDataset` |
63| Imaging | `COVID19CXRDataset`, `ChestXray14Dataset` |
64| Text | `PhysioNetDeIDDataset`, `MedicalTranscriptionsDataset` |
65| Genomics | `ClinVarDataset`, `COSMICDataset`, `TCGAPRADDataset` |
67In 2.0.2, `SleepEDFDataset(root=..., subset="cassette")` accepts `root`,
68`dataset_name`, `config_path`, `subset`; it does **not** accept `cache_dir` or `dev`.
69The root contains `SC-subjects.xls` and the `sleep-cassette/` subdirectory
70(or the corresponding telemetry files), unless metadata is already prepared.
71Reading raw `.xls` metadata can require the optional pandas engine `xlrd`. Genomics and clinical text
72are not imaging datasets even when they share the pipeline abstraction.

Available dataset families

These names are exported by 2.0.2; this inventory does not certify every task/model combination or dataset release. Read the selected class and bundled config first.

FamilyClasses
EHRMIMIC3Dataset, MIMIC4Dataset, MIMIC4EHRDataset, eICUDataset, OMOPDataset, MIMICExtractDataset, EHRShotDataset, Support2Dataset
Sleep/signalsSleepEDFDataset, SHHSDataset, ISRUCDataset, TUABDataset, TUEVDataset, CardiologyDataset, DREAMTDataset, BMDHSDataset
ImagingCOVID19CXRDataset, ChestXray14Dataset
TextPhysioNetDeIDDataset, MedicalTranscriptionsDataset
GenomicsClinVarDataset, COSMICDataset, TCGAPRADDataset

In 2.0.2, SleepEDFDataset(root=..., subset="cassette") accepts root, dataset_name, config_path, subset; it does not accept cache_dir or dev. The root contains SC-subjects.xls and the sleep-cassette/ subdirectory (or the corresponding telemetry files), unless metadata is already prepared. Reading raw .xls metadata can require the optional pandas engine xlrd. Genomics and clinical text are not imaging datasets even when they share the pipeline abstraction.

Raw lines 54 to 73
74## Inspect actual events and samples
76```python
77patient = next(base.iter_patients())
78admissions = patient.get_events(event_type="admissions")
79if admissions:
80 diagnoses = patient.get_events(
81 event_type="diagnoses_icd",
82 filters=[("hadm_id", "==", admissions[0].hadm_id)],
83 )
84 print([event.icd9_code for event in diagnoses]) # MIMIC-III only
85```
87MIMIC-IV diagnosis events use `icd_code` and `icd_version`. Keep the version when
88harmonizing vocabularies; identically shaped code strings need not mean the same
89thing. `get_events(start=..., end=...)` includes both time boundaries; `return_df=True`
90returns prefixed Polars columns such as `diagnoses_icd/icd9_code`. Missing event
91types can yield an empty frame without the expected columns: check before selecting.
92Do not use the legacy `patient.visits`, `next_visit`, or `visit.get_code_list` APIs.

Inspect actual events and samples

patient = next(base.iter_patients())
admissions = patient.get_events(event_type="admissions")
if admissions:
    diagnoses = patient.get_events(
        event_type="diagnoses_icd",
        filters=[("hadm_id", "==", admissions[0].hadm_id)],
    )
    print([event.icd9_code for event in diagnoses])  # MIMIC-III only

MIMIC-IV diagnosis events use icd_code and icd_version. Keep the version when harmonizing vocabularies; identically shaped code strings need not mean the same thing. get_events(start=..., end=...) includes both time boundaries; return_df=True returns prefixed Polars columns such as diagnoses_icd/icd9_code. Missing event types can yield an empty frame without the expected columns: check before selecting. Do not use the legacy patient.visits, next_visit, or visit.get_code_list APIs.

Raw lines 74 to 93
94## Splitting and preprocessing
96```python
97from pyhealth.datasets import split_by_patient, get_dataloader
98train, val, test = split_by_patient(samples, [0.6, 0.2, 0.2], seed=42)
99train_loader = get_dataloader(train, batch_size=32, shuffle=True)
100val_loader = get_dataloader(val, batch_size=32, shuffle=False)
101test_loader = get_dataloader(test, batch_size=32, shuffle=False)
102```
104Check nonempty partitions and pairwise-disjoint patient IDs. Group all recordings
105from the same person together for sleep/EEG as well. `split_by_visit` relies on record
106identifiers and permits patient overlap; it is unsuitable for a new-patient claim.
107`split_by_patient` does not implement time cutoffs or stratification. For a temporal
108study build the date-based partition explicitly and state whether returning patients
109are allowed. Fit feature transforms on training data only; the convenience
110`set_task -> split` route fits processors before splitting. See
111[train-only processing](examples.md).
113For custom datasets, inspect `BaseDataset` and its config-driven `load_data`/
114`load_table` interfaces. Do not start from obsolete patient/visit parsers.

Splitting and preprocessing

from pyhealth.datasets import split_by_patient, get_dataloader
train, val, test = split_by_patient(samples, [0.6, 0.2, 0.2], seed=42)
train_loader = get_dataloader(train, batch_size=32, shuffle=True)
val_loader = get_dataloader(val, batch_size=32, shuffle=False)
test_loader = get_dataloader(test, batch_size=32, shuffle=False)

Check nonempty partitions and pairwise-disjoint patient IDs. Group all recordings from the same person together for sleep/EEG as well. split_by_visit relies on record identifiers and permits patient overlap; it is unsuitable for a new-patient claim. split_by_patient does not implement time cutoffs or stratification. For a temporal study build the date-based partition explicitly and state whether returning patients are allowed. Fit feature transforms on training data only; the convenience set_task -> split route fits processors before splitting. See train-only processing.

For custom datasets, inspect BaseDataset and its config-driven load_data/ load_table interfaces. Do not start from obsolete patient/visit parsers.

Raw lines 94 to 114