pytorch_dataset
DummyConfig
dataclass
Dummy configuration for testing MEDS dataset
Source code in meds_torch/data/components/pytorch_dataset.py
PytorchDataset
Bases: SeedableMixin, Dataset, TimeableMixin
A PyTorch Dataset class for handling complex, multi-modal medical data.
This dataset is designed to work with data from the MEDS (Medical Event Data Set) format, supporting various types of medical events, static patient information, and task-specific labels. It provides functionality for loading, processing, and collating data for use in PyTorch models.
Key Features: - Supports task-specific data handling for binary classification - Implements custom sampling strategies and sequence length constraints
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
Configuration options for the dataset. |
required |
split |
str
|
The data split to use (e.g., ‘train’, ‘validation’, ‘test’). |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
config |
DictConfig
|
The dataset configuration. |
split |
str
|
The current data split. |
static_dfs |
dict
|
Dictionary of static DataFrames for each data shard. |
subj_indices |
dict
|
Mapping of subject IDs to their indices in the dataset. |
subj_seq_bounds |
dict
|
Sequence bounds (start, end) for each subject. |
index |
list
|
List of (subject_id, start, end) tuples for data access. |
labels |
dict
|
Task-specific labels for each data point. |
tasks |
list
|
List of task names. |
Methods: len(): Returns the number of items in the dataset. getitem(idx): Retrieves a single data point. collate(batch): Collates a batch of data points based on the specified collation strategy.
Examples:
>>> import tempfile
>>> from pathlib import Path
>>>
>>> # Test initialization without task
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(tmp_dir)
... # Remove task path to test taskless initialization
... config.task_label_path = None
... config.task_name = None
... config.do_include_prediction_time = False
... dataset = PytorchDataset(config, split='train')
... print(f"Dataset size: {len(dataset)}")
... print(f"Has task: {dataset.has_task}")
... # Test data loading
... sample = dataset[0]
... print("Sample keys:")
... for key in sorted(list(sample.keys())): print(f" {key}")
Dataset size: 3
Has task: False
Sample keys:
dynamic
end_idx
end_time
start_idx
start_time
static_indices
static_values
subject_id
>>> # Test initialization with task
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(tmp_dir)
... dataset = PytorchDataset(config, split='train')
... print(f"Dataset size: {len(dataset)}")
... print(f"Has task: {dataset.has_task}")
... print(f"First subject label: {dataset.labels[0]}") # Subject IDs start at 1
Dataset size: 3
Has task: True
First subject label: 0
Source code in meds_torch/data/components/pytorch_dataset.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 | |
__getitem__(idx)
Retrieve a single data point from the dataset.
This method returns a dictionary corresponding to a single subject’s data at the specified index. The data is not tensorized in this method, as that work is typically done in the collate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx |
int
|
The index of the data point to retrieve. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Tensor]
|
A dictionary containing the data for the specified index. The structure typically includes: - code: List of categorical metadata elements. - mask: Mask of valid elements in the sequence, False means it is a padded element. - numeric_value: List of dynamic numeric values. - numeric_value_mask: Mask of numeric values (False means no numeric value was recorded) - time_delta_days: List of dynamic time deltas between observations. - static_indices(Optional): List of static MEDS codes. - static_values(Optional): List of static MEDS numeric values. - static_mask(Optional): List of static masks (True means the value is static). |
Notes
This method uses the SeedableMixin to ensure reproducibility in data loading.
Source code in meds_torch/data/components/pytorch_dataset.py
collate(batch)
Combines a batch of data points into a single, tensorized batch.
The collated output is a fully tensorized and padded dictionary, ready for input into an
input_encoder. This method uses the JointNestedRaggedTensorDict API to collate and pad the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch |
list[dict]
|
A list of dictionaries, each representing a single sample as returned by the getitem method. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing the collated batch data. |
Source code in meds_torch/data/components/pytorch_dataset.py
load_subject(subject_dynamic_data, subject_id, global_st, global_end)
Load and process data for a single subject.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject_dynamic_data |
The dynamic data for the subject. |
required | |
subject_id |
int
|
The ID of the subject to load. |
required |
global_st |
int
|
The start index of the sequence to load. |
required |
global_end |
int
|
The end index of the sequence to load. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, list[float]]
|
A dictionary containing the processed data for the subject. |
Examples:
import tempfile from pathlib import Path import polars as pl import numpy as np from nested_ragged_tensors.ragged_numpy import JointNestedRaggedTensorDict
Test basic subject loading
with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … dataset = PytorchDataset(config, split=’train’) … … # First get the dynamic data using load_subject_dynamic_data … dynamic_data, subject_id, st, end = dataset.load_subject_dynamic_data(0) … … # Then load the complete subject data … subject_data = dataset.load_subject(dynamic_data, subject_id, st, end) … … # Verify the returned data structure … print(“Keys in subject data:”) … for key in sorted(subject_data.keys()): print(f”{key}”) … print() … print(f”Has static indices: {len(subject_data[‘static_indices’]) > 0}”) … print(f”Has dynamic data: {isinstance(subject_data[‘dynamic’], JointNestedRaggedTensorDict)}”) … print(f”Has end time: {‘end_time’ in subject_data}”) Keys in subject data: dynamic end_idx end_time start_idx start_time static_indices static_values
Has static indices: True Has dynamic data: True Has end time: True Test with different configuration settings
with tempfile.TemporaryDirectory() as tmp_dir: … # Create config with modified settings … config = create_dummy_dataset(tmp_dir) … config.do_prepend_static_data = False … config.postpend_token = ‘none’ … config.do_include_start_time_min = False … … dataset = PytorchDataset(config, split=’train’) … dynamic_data, subject_id, st, end = dataset.load_subject_dynamic_data(0) … subject_data = dataset.load_subject(dynamic_data, subject_id, st, end) … … # Verify the modified behavior … print(f”Contains start time: {‘start_time’ in subject_data}”) … dynamic_tensors = subject_data[‘dynamic’].tensors … has_eos = np.any(dynamic_tensors[‘dim0/code’] == config.EOS_TOKEN_ID) … print(f”Contains EOS token: {has_eos}”) Contains start time: False Contains EOS token: False
Test with maximum sequence length constraint
with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … config.max_seq_len = 5 # Set small max sequence length … … dataset = PytorchDataset(config, split=’train’) … dynamic_data, subject_id, st, end = dataset.load_subject_dynamic_data(0) … subject_data = dataset.load_subject(dynamic_data, subject_id, st, end) … … # Verify sequence length constraints … dynamic_len = len(subject_data[‘dynamic’].tensors[‘dim0/code’]) … print(f”Dynamic sequence length: {dynamic_len}”) … print(f”Respects max length: {dynamic_len <= config.max_seq_len}”) Dynamic sequence length: 5 Respects max length: True
Source code in meds_torch/data/components/pytorch_dataset.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 | |
load_subject_dynamic_data(idx)
Loads and returns the dynamic data slice for a given subject index, with subject ID and time range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx |
int
|
Index of the subject in the dataset index |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(subject_dynamic_data, subject_id, st, end) where: - subject_dynamic_data is a JointNestedRaggedTensorDict containing the dynamic data - subject_id is the ID of the subject - st is the start time index - end is the end time index |
Examples:
import tempfile from pathlib import Path import polars as pl from nested_ragged_tensors.ragged_numpy import JointNestedRaggedTensorDict
Create a test dataset and initialize the PytorchDataset
with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … dataset = PytorchDataset(config, split=’train’) … … # Test loading dynamic data for first subject … dynamic_data, subject_id, st, end = dataset.load_subject_dynamic_data(0) … print(f”Subject ID: {subject_id}”) … print(f”Time range: {st} to {end}”) … print(f”Dynamic data keys: {sorted(dynamic_data.tensors.keys())}”) Subject ID: 0 Time range: 0 to 4 Dynamic data keys: [‘dim0/time_delta_days’, ‘dim1/bounds’, ‘dim1/code’, ‘dim1/numeric_value’]
Test loading dynamic data for second subject
with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … dataset = PytorchDataset(config, split=’train’) … … # Load second subject … dynamic_data, subject_id, st, end = dataset.load_subject_dynamic_data(1) … print(f”Subject ID: {subject_id}”) … print(f”Time range: {st} to {end}”) … # Verify data structure … print(f”Has numeric values: {‘dim1/numeric_value’ in dynamic_data.tensors}”) … print(f”Has time deltas: {‘dim0/time_delta_days’ in dynamic_data.tensors}”) Subject ID: 1 Time range: 0 to 4 Has numeric values: True Has time deltas: True
Test error case with invalid index
with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … dataset = PytorchDataset(config, split=’train’) … try: … dynamic_data = dataset.load_subject_dynamic_data(999) # Invalid index … except IndexError as e: … print(“Caught expected IndexError”) Caught expected IndexError
Source code in meds_torch/data/components/pytorch_dataset.py
read_subject_descriptors()
Read subject schemas and static data from the dataset.
This method processes the Parquet files for each shard in the dataset, extracting static data and creating various mappings and indices for efficient data access.
The method populates the following instance attributes: - self.static_dfs: Dictionary of static DataFrames for each shard. - self.subj_indices: Mapping of subject IDs to their indices. - self.subj_seq_bounds: Dictionary of sequence bounds for each subject. - self.index: List of (subject_id, start, end) tuples for data access. - self.labels: Dictionary of task labels (if tasks are specified).
If a task is specified in the configuration, this method also processes the task labels and integrates them with the static data.
Raises:
| Type | Description |
|---|---|
ValueError
|
If duplicate subjects are found across shards. |
FileNotFoundError
|
If specified task files are not found. |
Source code in meds_torch/data/components/pytorch_dataset.py
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 | |
SeqPaddingSide
Bases: StrEnum
An enumeration of the possible sequence padding sides for the dataset.
Source code in meds_torch/data/components/pytorch_dataset.py
SubsequenceSamplingStrategy
Bases: StrEnum
An enumeration of the possible subsequence sampling strategies for the dataset.
Attributes:
| Name | Type | Description |
|---|---|---|
RANDOM |
Randomly sample a subsequence from the full sequence. |
|
TO_END |
Sample a subsequence from the end of the full sequence. Note this starts at the last element and moves back. |
|
FROM_START |
Sample a subsequence from the start of the full sequence. |
Source code in meds_torch/data/components/pytorch_dataset.py
create_dummy_dataset(base_dir, n_subjects=3, split='train', seed=42)
Creates a dummy MEDS dataset for testing purposes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir |
str | Path
|
Directory where the dummy dataset will be created |
required |
n_subjects |
int
|
Number of test subjects to generate |
3
|
split |
str
|
Dataset split to create (‘train’, ‘validation’, or ‘test’) |
'train'
|
seed |
int | None
|
Random seed for reproducible data generation |
42
|
Returns:
| Type | Description |
|---|---|
DummyConfig
|
DummyConfig object with paths to the created dataset files |
Examples:
>>> from pprint import pprint
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(tmp_dir)
... # Verify directory structure
... data_dir = Path(tmp_dir)
... print(sorted(str(p.relative_to(tmp_dir))
... for p in data_dir.glob("**/*")
... if p.is_file()))
['data/train/shard_0.nrt', 'schema/train/shard_0.parquet', 'task_labels.parquet']
>>> # Test creating dataset with different parameters
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(
... tmp_dir, n_subjects=2, split='validation', seed=123
... )
... # Verify static data
... static_df = pl.read_parquet(
... Path(config.schema_files_root) / "validation/shard_0.parquet"
... )
... print(f"Number of subjects: {len(static_df)}")
... print(f"Columns: {static_df.columns}")
Number of subjects: 2
Columns: ['subject_id', 'start_time', 'time', 'code', 'numeric_value']
>>> # Test loading dynamic data
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(tmp_dir)
... dynamic_data = JointNestedRaggedTensorDict(
... tensors_fp=Path(tmp_dir) / "data/train/shard_0.nrt")
... print(f"Dynamic data length: {len(dynamic_data)}")
... print("Available features:")
... for feature in sorted(dynamic_data.tensors.keys()): print(f" {feature}")
Dynamic data length: 3
Available features:
dim1/bounds
dim1/time_delta_days
dim2/bounds
dim2/code
dim2/numeric_value
>>> # Test loading static data and task labels
>>> # Notice that the first index in the dynamic data corresponds to the first row in the static data,
>>> # and that the second index in the dynamic data corresponds to the second row in the static data
>>> # and so on.
>>> with tempfile.TemporaryDirectory() as tmp_dir:
... config = create_dummy_dataset(tmp_dir)
... print(pl.read_parquet(Path(tmp_dir) / "schema/train/shard_0.parquet"))
... print(pl.read_parquet(Path(tmp_dir) / "task_labels.parquet"))
... pprint(config)
shape: (3, 5)
┌────────────┬─────────────────────┬─────────────────────────────────┬───────────┬─────────────────┐
│ subject_id ┆ start_time ┆ time ┆ code ┆ numeric_value │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ datetime[μs] ┆ list[datetime[μs]] ┆ list[i64] ┆ list[f64] │
╞════════════╪═════════════════════╪═════════════════════════════════╪═══════════╪═════════════════╡
│ 0 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │
│ 1 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │
│ 2 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │
└────────────┴─────────────────────┴─────────────────────────────────┴───────────┴─────────────────┘
shape: (3, 3)
┌────────────┬─────────────────────┬───────────────┐
│ subject_id ┆ prediction_time ┆ boolean_value │
│ --- ┆ --- ┆ --- │
│ i64 ┆ datetime[μs] ┆ i64 │
╞════════════╪═════════════════════╪═══════════════╡
│ 0 ┆ 1998-01-01 00:00:00 ┆ 0 │
│ 1 ┆ 1998-01-01 00:00:00 ┆ 1 │
│ 2 ┆ 1998-01-01 00:00:00 ┆ 0 │
└────────────┴─────────────────────┴───────────────┘
DummyConfig(schema_files_root='.../schema',
task_label_path='.../task_labels.parquet',
data_dir='...',
task_name='dummy_task',
max_seq_len=10,
do_prepend_static_data=True,
postpend_token='eos',
do_flatten_tensors=True,
EOS_TOKEN_ID=5,
do_include_subject_id=True,
do_include_subsequence_indices=True,
do_include_start_time_min=True,
do_include_end_time=True,
do_include_prediction_time=True,
subsequence_sampling_strategy='from_start')
Source code in meds_torch/data/components/pytorch_dataset.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
get_task_indices_and_labels(task_df, static_dfs)
Processes the joint DataFrame to determine the index range for each subject’s task.
For each row in task_df_joint, it is assumed that time is a sorted column and the function
computes the index of the last event at prediction_time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
- |
task_df_joint (DataFrame
|
A DataFrame resulting from the merge_task_with_static function. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int, int]]
|
|
dict[str, list]
|
|
Examples:
import tempfile with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_dataset(tmp_dir) … shard = “train/shard_0” … task_df = pl.read_parquet(Path(config.data_dir) / “task_labels.parquet”) … static_dfs = {“shard_0”: pl.read_parquet(Path(config.data_dir) / “schema/train/shard_0.parquet”)} task_df shape: (3, 3) ┌────────────┬─────────────────────┬───────────────┐ │ subject_id ┆ prediction_time ┆ boolean_value │ │ — ┆ — ┆ — │ │ i64 ┆ datetime[μs] ┆ i64 │ ╞════════════╪═════════════════════╪═══════════════╡ │ 0 ┆ 1998-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 1998-01-01 00:00:00 ┆ 1 │ │ 2 ┆ 1998-01-01 00:00:00 ┆ 0 │ └────────────┴─────────────────────┴───────────────┘ static_dfs[“shard_0”] shape: (3, 5) ┌────────────┬─────────────────────┬─────────────────────────────────┬───────────┬─────────────────┐ │ subject_id ┆ start_time ┆ time ┆ code ┆ numeric_value │ │ — ┆ — ┆ — ┆ — ┆ — │ │ i64 ┆ datetime[μs] ┆ list[datetime[μs]] ┆ list[i64] ┆ list[f64] │ ╞════════════╪═════════════════════╪═════════════════════════════════╪═══════════╪═════════════════╡ │ 0 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │ │ 1 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │ │ 2 ┆ 1995-01-01 00:00:00 ┆ [1995-01-01 00:00:00, 1996-01-… ┆ [1, 2, 3] ┆ [0.1, 0.2, 0.3] │ └────────────┴─────────────────────┴─────────────────────────────────┴───────────┴─────────────────┘
Run the function
BINARY_LABEL_COL = “boolean_value” # Define the constant used in the function indices, labels, pred_times = get_task_indices_and_labels(task_df, static_dfs)
Check the results
print(indices) # Only subjects 1 and 2 should be present (inner join) [(0, 4), (1, 4), (2, 4)] print(labels) # Labels for subjects 1 and 2 [0, 1, 0]
Source code in meds_torch/data/components/pytorch_dataset.py
subsample_subject_data(subject_data, max_seq_len, sampling_strategy, do_flatten_tensors=True, global_st=0, postpend_token=PostpendToken.none)
Subsample subject data based on maximum sequence length and sampling strategy.
This function handles subsampling for both flattened and nested tensor structures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject_data |
JointNestedRaggedTensorDict
|
Input tensor dictionary containing the sequence data |
required |
max_seq_len |
int
|
Maximum allowed sequence length |
required |
sampling_strategy |
SubsequenceSamplingStrategy
|
Strategy for selecting subsequence (RANDOM, TO_END, FROM_START) |
required |
do_flatten_tensors |
bool
|
Whether to flatten tensors before subsampling |
True
|
global_st |
int
|
Starting index offset for maintaining global indexing |
0
|
Returns:
| Type | Description |
|---|---|
JointNestedRaggedTensorDict
|
tuple containing: |
int
|
|
int
|
|
bool
|
|
Examples:
>>> import numpy as np
>>> np.random.seed(42)
>>> # Create sample nested data
>>> tensors = {
... "code": [[1,2],[3,4],[5,6],[7,8,9,10],[11,12]],
... "time": [0,1,2,3,4],
... }
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> # Test FROM_START strategy without flattening
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=2,
... sampling_strategy=SubsequenceSamplingStrategy.FROM_START,
... do_flatten_tensors=False
... )
>>> subsampled.tensors["dim1/code"].tolist()
[1, 2, 3, 4]
>>> subsampled.tensors["dim0/time"].tolist()
[0, 1]
>>> st, end
(0, 2)
>>> has_censor_token
False
>>> # Test TO_END strategy with flattening
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=4,
... sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... do_flatten_tensors=True
... )
>>> subsampled.tensors["dim0/code"].tolist()
[9, 10, 11, 12]
>>> subsampled.tensors["dim0/time"].tolist()
[0, 0, 4, 0]
>>> st, end
(3, 5)
>>> has_censor_token
False
>>> # Test censorship when it should be there
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=4,
... sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... do_flatten_tensors=True,
... postpend_token=PostpendToken.censor,
... )
>>> subsampled.tensors["dim0/code"].tolist()
[10, 11, 12]
>>> subsampled.tensors["dim0/time"].tolist()
[0, 4, 0]
>>> st, end
(3, 5)
>>> has_censor_token
True
>>> # Test censorship when it should not be there
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=4,
... sampling_strategy=SubsequenceSamplingStrategy.FROM_START,
... do_flatten_tensors=True,
... postpend_token=PostpendToken.censor,
... )
>>> subsampled.tensors["dim0/code"].tolist()
[1, 2, 3, 4]
>>> subsampled.tensors["dim0/time"].tolist()
[0, 0, 1, 0]
>>> st, end
(0, 2)
>>> has_censor_token
False
>>> # Test TO_END strategy
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=2,
... sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... do_flatten_tensors=False,
... )
>>> st, end
(3, 5)
>>> has_censor_token
False
>>> # Test RANDOM strategy
>>> data = JointNestedRaggedTensorDict(raw_tensors=tensors)
>>> subsampled, st, end, has_censor_token = subsample_subject_data(
... data, max_seq_len=2,
... sampling_strategy=SubsequenceSamplingStrategy.RANDOM,
... do_flatten_tensors=True,
... )
>>> len(subsampled.tensors["dim0/code"]) == 2
True
>>> has_censor_token
False
Source code in meds_torch/data/components/pytorch_dataset.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |