pyhealth.datasets.SampleDataset#
This class is the basic sample dataset. All sample datasets are inherited from this class.
- class pyhealth.datasets.SampleDataset(path, dataset_name=None, task_name=None, delete_on_close=False, **kwargs)[source]#
Bases:
StreamingDatasetA streaming dataset that loads sample metadata and processors from disk.
SampleDataset expects the path directory to contain a schema.pkl file created by a SampleBuilder.save(…) call. The schema.pkl must include the fitted input_schema, output_schema, input_processors, output_processors, patient_to_index and record_to_index mappings.
- input_schema#
The configuration used to instantiate processors for input features (string aliases or processor specs).
- output_schema#
The configuration used to instantiate processors for output features.
- input_processors#
A mapping of input feature names to fitted FeatureProcessor instances.
- output_processors#
A mapping of output feature names to fitted FeatureProcessor instances.
- patient_to_index#
Dictionary mapping patient IDs to the list of sample indices associated with that patient.
- record_to_index#
Dictionary mapping record/visit IDs to the list of sample indices associated with that record.
- dataset_name#
Optional human friendly dataset name.
- task_name#
Optional human friendly task name.
Examples
>>> from pyhealth.datasets import create_sample_dataset >>> dataset = create_sample_dataset( ... samples=[ ... {"patient_id": "p1", "feature": 1, "label": 0}, ... {"patient_id": "p2", "feature": 2, "label": 1}, ... ], ... input_schema={"feature": "raw"}, ... output_schema={"label": "raw"}, ... in_memory=False, ... ) >>> dataset.subset([1]).patient_to_index {'p2': [0]} >>> dataset.close()
Initialize a SampleDataset pointing at a directory created by SampleBuilder.
- Parameters:
path (
str) – Path to a directory containing a schema.pkl produced by SampleBuilder.save and associated pickled sample files.dataset_name (
Optional[str]) – Optional human-friendly dataset name.task_name (
Optional[str]) – Optional human-friendly task name.delete_on_close (
bool) – Whetherclose()should deletepath. This is reserved for temporary datasets owned by PyHealth.**kwargs – Extra keyword arguments forwarded to litdata.StreamingDataset (such as streaming options).
- __init__(path, dataset_name=None, task_name=None, delete_on_close=False, **kwargs)[source]#
Initialize a SampleDataset pointing at a directory created by SampleBuilder.
- Parameters:
path (
str) – Path to a directory containing a schema.pkl produced by SampleBuilder.save and associated pickled sample files.dataset_name (
Optional[str]) – Optional human-friendly dataset name.task_name (
Optional[str]) – Optional human-friendly task name.delete_on_close (
bool) – Whetherclose()should deletepath. This is reserved for temporary datasets owned by PyHealth.**kwargs – Extra keyword arguments forwarded to litdata.StreamingDataset (such as streaming options).
- set_shuffle(shuffle, seed=None)[source]#
Sets whether iterating the dataset shuffles, and the shuffle seed.
The order of each pass is determined by
seedand the epoch (seeset_epoch); litdata shuffles with its own generator, so the global random state is not used. Loaders fromget_dataloader()call this for you at the start of every pass.- Parameters:
Examples
>>> dataset.set_shuffle(True, seed=0)
- Return type:
- subset(indices)[source]#
Create a StreamingDataset restricted to the provided indices.
The subset reads with litdata’s POSIX-fast mmap reads turned off (litdata >= 0.2.68). They cache per index run, not per chunk file, which makes a patient-level split ~20x slower to iterate. The full dataset keeps them.
- Return type:
- async aread_window(index, start, frames, fields=None, *, max_concurrent_reads=8)#
Async
read_window(), with bounded parallel field reads per call.The first call initializes dataset metadata synchronously. Reuse one dataset per worker/event loop; callers bound simultaneous window requests. Cancellation drains child tasks, but an SDK/thread fallback may finish its underlying I/O afterward.
- property frame_counts: list[int]#
Frame counts in record-index order for data written with
TemporalArrayLoader.Reads index metadata only, including the dataset’s subsample/split selection. Use these counts to keep application-specific window sampling outside storage code.
- get_by_key(key)#
Load a sample by entity key from the
keys/store (str or int keys).The key store is read from the dataset root (local cache if present, else the remote URL). Remote lookups use Polars
scan_parquetwith predicate pushdown so shards stay in object storage.- Return type:
- read_window(index, start, frames, fields=None, *, max_concurrent_reads=8)#
Read selected axis-0 frames directly from a record written by
optimize.Records must be flat dictionaries; selected fields must be fixed-width NumPy arrays or CPU tensors with matching frame-axis lengths.
fields=Noneselects all fields; an empty sequence returns an empty dictionary without payload I/O. Windows use[start, start + frames)and must fit entirely within the selected arrays.Requires uncompressed, unencrypted PyTree chunks and built-in array serializers. S3/R2 fetch array ranges plus small, bounded-cache metadata reads. Other cloud backends may download a whole chunk. Returned arrays/tensors are writable and independent of the source. Dataset transforms are not applied to partial records.
POSIX TemporalArrayLoader windows use bounded in-place chunk mappings when POSIX-fast is enabled. Only selected group views are decoded; source chunks must remain immutable while in use. The synchronous path executes in the caller’s thread; the async path offloads page faults and decoding to a thread.
This explicit random-access operation does not advance the iteration/checkpoint position or assign requests to ranks/workers. Use
aread_windowfor async callers. Dataset objects should be initialized independently in each process, as usual.For example,
read_window(0, start=3, frames=4, fields=["features", "valid"])returns frames 3, 4, 5 and 6 from record 0. A field shaped(T, 2)becomes(4, 2). Windows never cross records, pad or wrap; the application’s sampler chooses valid starts usingframe_countsfor TemporalArrayLoader datasets. That loader stores whole tracks in field groups: selecting any field fetches its group’s window, but returns only requested fields. See temporal.py and window.py for the binary layout and the corresponding byte-range calculation.
- set_drop_last(drop_last)#
Set the drop_last parameter.
Invalidates the shuffler cache when the parameter changes to ensure subsequent length calculations reflect the new drop_last setting.
- set_epoch(current_epoch)#
Set the current epoch to the dataset on epoch starts.
When using the StreamingDataLoader, this is done automatically
- Return type: