import math
from abc import ABC, abstractmethod
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from itertools import chain
from numbers import Real
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from .sample_dataset import SampleDataset
# TODO: train_dataset.dataset still access the whole dataset which may leak information
# TODO: add more splitting methods
[docs]class Split(ABC):
"""Interface for ``BaseDataset.set_task(task, split=...)``.
``set_task`` fits every processor on the samples of part 0 and returns one
``SampleDataset`` per part, in order, as views over one processed cache.
It uses the parts exactly as returned: they may overlap or leave samples
out. :class:`PatientSplit` is the reference implementation.
Examples:
>>> import numpy as np
>>> from pyhealth.datasets import Split
>>> class HoldoutSplit(Split):
... def __init__(self, test_patients):
... self.test_patients = sorted(test_patients)
... def split_indices(self, patient_to_index):
... test = set(self.test_patients)
... parts = ([], [])
... for pid, indices in patient_to_index.items():
... parts[pid in test].extend(indices)
... return [np.array(sorted(p), dtype=np.int64) for p in parts]
... def to_dict(self):
... return {"kind": "holdout", "test_patients": self.test_patients}
>>> HoldoutSplit(["p2"]).split_indices({"p1": [0, 1], "p2": [2]})
[array([0, 1]), array([2])]
"""
[docs] @abstractmethod
def split_indices(
self, patient_to_index: Mapping[str, Sequence[int]]
) -> list[np.ndarray]:
"""Returns the sample indices of each part.
Args:
patient_to_index: Patient ID to the indices of its samples.
Returns:
One ``int64`` array of sample indices per part, training part
first. Sorted indices keep reads from the cache sequential.
"""
[docs] @abstractmethod
def to_dict(self) -> dict:
"""Returns a JSON-serialisable description of the split.
It goes into the processed-cache key, so it must change whenever the
parts would, and is saved as ``SampleDataset.fit_split``.
"""
[docs]@dataclass(frozen=True)
class PatientSplit(Split):
"""A patient-level split for ``BaseDataset.set_task(task, split=...)``.
With a split, ``set_task`` fits every processor on the training patients
only and returns one dataset per part, so validation and test patients
never shape preprocessing (vocabularies, learned statistics).
Patients are sorted by ID before shuffling with ``seed``, so the same
``PatientSplit`` gives the same patients on every run and machine,
whatever order the samples are stored in.
Unlike :func:`split_by_patient`, which splits an already-processed
``SampleDataset`` whose processors were fitted on all samples, the parts
are chosen before fitting. ``split_by_patient`` shuffles patients in the
order they appear in the dataset, so for the same ratios and seed it
generally picks different patients.
Args:
ratios: Two or more non-negative fractions summing to 1. The first
part is the training part, e.g. (train, test), (train, val, test)
or (train, val, cal, test).
seed: Seed for the shuffle.
Examples:
>>> from pyhealth.datasets import PatientSplit
>>> split = PatientSplit(ratios=(0.7, 0.1, 0.2), seed=42)
>>> parts = split.split_indices({"p1": [0, 1], "p2": [2], "p3": [3, 4]})
>>> sorted(int(i) for part in parts for i in part)
[0, 1, 2, 3, 4]
"""
ratios: Sequence[float]
seed: int = 0
def __post_init__(self):
ratios = tuple(float(r) for r in self.ratios)
if len(ratios) < 2:
raise ValueError(f"PatientSplit needs at least 2 ratios, training part first; got {ratios}.")
if any(r < 0 for r in ratios):
raise ValueError(f"PatientSplit ratios must be non-negative, got {ratios}.")
if not math.isclose(sum(ratios), 1.0, abs_tol=1e-6):
raise ValueError(f"PatientSplit ratios must sum to 1, got {ratios} (sum {sum(ratios)}).")
object.__setattr__(self, "ratios", ratios)
[docs] def to_dict(self) -> dict:
"""JSON-serialisable description, used in cache keys and metadata."""
return {"kind": "patient", "ratios": list(self.ratios), "seed": int(self.seed)}
[docs] def split_indices(
self, patient_to_index: Mapping[str, Sequence[int]]
) -> list[np.ndarray]:
"""Splits sample indices by patient.
Patients are sorted, shuffled with ``seed`` and cut by ``ratios``.
Args:
patient_to_index: Patient ID to the indices of its samples.
Returns:
One sorted ``int64`` array of sample indices per ratio, in order
(train first). Each patient's samples land in exactly one part.
"""
patients = sorted(patient_to_index, key=str)
order = np.random.default_rng(self.seed).permutation(len(patients))
cuts = [
int(len(patients) * sum(self.ratios[: k + 1]))
for k in range(len(self.ratios) - 1)
]
parts = []
for part in np.split(order, cuts):
indices = np.fromiter(
chain.from_iterable(patient_to_index[patients[p]] for p in part),
dtype=np.int64,
)
indices.sort()
parts.append(indices)
return parts
def _validate_ratios(ratios: object, expected_length: int) -> None:
"""Validate split proportions without changing the caller's values."""
if not isinstance(ratios, (list, tuple, np.ndarray)):
raise TypeError("ratios must be a list, tuple, or 1-D NumPy array")
if isinstance(ratios, np.ndarray) and ratios.ndim != 1:
raise ValueError("ratios must be one-dimensional")
if len(ratios) != expected_length:
raise ValueError(f"ratios must contain exactly {expected_length} values")
values = []
for index, value in enumerate(ratios):
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
raise TypeError(f"ratios[{index}] must be a real number, not a boolean")
try:
numeric_value = float(value)
except (OverflowError, ValueError) as exc:
raise ValueError(
f"ratios[{index}] must be finite and between 0 and 1"
) from exc
if not math.isfinite(numeric_value):
raise ValueError(f"ratios[{index}] must be finite")
if not 0 <= value <= 1:
raise ValueError(f"ratios[{index}] must be between 0 and 1")
values.append(numeric_value)
total = math.fsum(values)
if not math.isclose(total, 1.0, rel_tol=0.0, abs_tol=1e-6):
raise ValueError(f"ratios must sum to 1.0 within 1e-6; got {total!r}")
def _label_to_int(label) -> int:
"""Convert a stored label (int/np scalar/torch scalar) to Python int."""
if torch.is_tensor(label):
return int(label.item())
return int(label)
[docs]def sample_balanced(
dataset: SampleDataset,
ratio: float = 1.0,
subsample: float = 1.0,
seed: Optional[int] = None,
) -> SampleDataset:
"""Keep positives and negatives at a target ratio, then cap total size.
Args:
dataset: Dataset with ``patient_to_index`` populated.
ratio: Negatives per positive (e.g., 1.0 -> ~1 neg per pos). Values <=0 keep only positives.
subsample: Max fraction of the original dataset size to retain. If the ratio-selected set
exceeds ``len(dataset) * subsample``, both positives and negatives are downsampled
proportionally while preserving the ratio as closely as possible.
seed: Optional RNG seed for reproducible negative sampling.
Returns:
A new ``SampleDataset`` containing all positives plus sampled negatives,
with refreshed ``patient_to_index`` and ``record_to_index`` mappings.
"""
if ratio < 0:
raise ValueError("ratio must be non-negative")
if subsample <= 0 or subsample > 1:
raise ValueError("subsample must be in (0, 1]")
rng = np.random.default_rng(seed)
pos_indices: List[int] = []
neg_indices: List[int] = []
for idx in range(len(dataset)):
label = _label_to_int(dataset[idx]["label"])
if label == 1:
pos_indices.append(idx)
else:
neg_indices.append(idx)
if not pos_indices:
return dataset
desired_pos = len(pos_indices)
desired_neg = min(len(neg_indices), int(round(desired_pos * ratio)))
cap = max(1, int(len(dataset) * subsample))
desired_total = desired_pos + desired_neg
if desired_total <= cap:
keep_pos = desired_pos
keep_neg = desired_neg
else:
ratio_effective = desired_neg / desired_pos if desired_pos > 0 else 0.0
keep_pos = max(1, min(desired_pos, int(cap / (1 + ratio_effective))))
keep_neg = int(round(keep_pos * ratio_effective)) if ratio_effective > 0 else 0
keep_neg = min(keep_neg, len(neg_indices))
if keep_pos + keep_neg > cap:
keep_neg = max(0, cap - keep_pos)
if keep_pos < desired_pos:
pos_keep = list(rng.choice(pos_indices, size=keep_pos, replace=False))
else:
pos_keep = pos_indices
if keep_neg > 0:
neg_keep = list(rng.choice(neg_indices, size=keep_neg, replace=False))
else:
neg_keep = []
keep_indices = pos_keep + neg_keep
balanced = dataset.subset(keep_indices) # type: ignore
# Rebuild patient_to_index and record_to_index for the reduced set.
balanced.patient_to_index = {}
balanced.record_to_index = {}
for i in range(len(balanced)):
sample = balanced[i]
pid = sample.get("patient_id")
rid = sample.get("record_id", sample.get("visit_id"))
if pid is not None:
balanced.patient_to_index.setdefault(pid, []).append(i)
if rid is not None:
balanced.record_to_index.setdefault(rid, []).append(i)
return balanced
[docs]def split_by_visit(
dataset: SampleDataset,
ratios: Union[Tuple[float, float, float], List[float]],
seed: Optional[int] = None,
):
"""Splits the dataset by visit (i.e., samples).
Args:
dataset: a `SampleDataset` object
ratios: a list/tuple of ratios for train / val / test
seed: random seed for shuffling the dataset
Returns:
train_dataset, val_dataset, test_dataset: ``SampleDataset`` views
(``dataset.subset``) over the same processed samples.
Raises:
TypeError: If ``ratios`` has an unsupported container or element type.
ValueError: If its length, components, or total is invalid.
Example:
>>> from pyhealth.datasets import create_sample_dataset
>>> samples = [{"patient_id": f"p{i}", "record_id": f"r{i}", "feature": i,
... "label": i % 2} for i in range(8)]
>>> dataset = create_sample_dataset(samples, {"feature": "raw"}, {"label": "raw"})
>>> train, val, test = split_by_visit(dataset, [0.5, 0.25, 0.25], seed=42)
>>> [len(part) for part in (train, val, test)]
[4, 2, 2]
Note:
The processors of ``dataset`` (vocabularies, learned statistics) were
fitted on all of its samples, so every part shaped them. To fit them on
the training part only, split inside ``set_task`` instead:
``base_dataset.set_task(task, split=...)`` with :class:`PatientSplit`
or a custom :class:`Split`.
"""
_validate_ratios(ratios, expected_length=3)
rng = np.random.default_rng(seed)
index = np.arange(len(dataset))
rng.shuffle(index)
train_index = index[: int(len(dataset) * ratios[0])]
val_index = index[
int(len(dataset) * ratios[0]) : int(len(dataset) * (ratios[0] + ratios[1]))
]
test_index = index[int(len(dataset) * (ratios[0] + ratios[1])) :]
train_dataset = dataset.subset(train_index) # type: ignore
val_dataset = dataset.subset(val_index) # type: ignore
test_dataset = dataset.subset(test_index) # type: ignore
return train_dataset, val_dataset, test_dataset
[docs]def split_by_patient(
dataset: SampleDataset,
ratios: Union[Tuple[float, float, float], List[float]],
seed: Optional[int] = None,
):
"""Splits the dataset by patient.
Args:
dataset: a `SampleDataset` object
ratios: a list/tuple of ratios for train / val / test
seed: random seed for shuffling the dataset. Patients are sorted by ID
before shuffling, so the split depends only on the seed and the
set of patients, not on the order of the samples.
Returns:
train_dataset, val_dataset, test_dataset: ``SampleDataset`` views
(``dataset.subset``) over the same processed samples.
Raises:
TypeError: If ``ratios`` has an unsupported container or element type.
ValueError: If its length, components, or total is invalid.
Example:
>>> from pyhealth.datasets import create_sample_dataset
>>> samples = [{"patient_id": f"p{i}", "record_id": f"r{i}", "feature": i,
... "label": i % 2} for i in range(8)]
>>> dataset = create_sample_dataset(samples, {"feature": "raw"}, {"label": "raw"})
>>> train, val, test = split_by_patient(dataset, [0.5, 0.25, 0.25], seed=42)
>>> [len(part) for part in (train, val, test)]
[4, 2, 2]
Note:
The processors of ``dataset`` (vocabularies, learned statistics) were
fitted on all of its samples, so every part shaped them. To fit them on
the training part only, split inside ``set_task`` instead:
``base_dataset.set_task(task, split=...)`` with :class:`PatientSplit`
or a custom :class:`Split`.
"""
_validate_ratios(ratios, expected_length=3)
rng = np.random.default_rng(seed)
# Sort first: dict order follows sample order, which callers may change.
patient_indx = sorted(dataset.patient_to_index, key=str)
num_patients = len(patient_indx)
rng.shuffle(patient_indx)
train_patient_indx = patient_indx[: int(num_patients * ratios[0])]
val_patient_indx = patient_indx[
int(num_patients * ratios[0]) : int(num_patients * (ratios[0] + ratios[1]))
]
test_patient_indx = patient_indx[int(num_patients * (ratios[0] + ratios[1])) :]
train_index = list(
chain(*[dataset.patient_to_index[i] for i in train_patient_indx])
)
val_index = list(chain(*[dataset.patient_to_index[i] for i in val_patient_indx]))
test_index = list(chain(*[dataset.patient_to_index[i] for i in test_patient_indx]))
train_dataset = dataset.subset(train_index) # type: ignore
val_dataset = dataset.subset(val_index) # type: ignore
test_dataset = dataset.subset(test_index) # type: ignore
return train_dataset, val_dataset, test_dataset
[docs]def split_by_strat_fold(
dataset: SampleDataset,
train_folds: tuple[int, ...] | list[int] = tuple(range(1, 9)),
val_folds: tuple[int, ...] | list[int] = (9,),
test_folds: tuple[int, ...] | list[int] = (10,),
fold_field: str = "strat_fold",
folds: tuple[int, ...] | list[int] | None = None,
check_patient_disjoint: bool = False,
):
"""Split a sample dataset using integer fold assignments.
The recommended PTB-XL protocol uses folds 1–8 for training, fold 9 for
validation, and fold 10 for testing. Official PTB-XL folds are
patient-disjoint; this helper does not assume that of arbitrary data.
Pass ``check_patient_disjoint=True`` to verify no ``patient_id`` appears
in more than one of train/val/test (uses ``dataset.patient_to_index``).
Pass ``folds`` (one integer per sample, aligned with dataset indices) to
avoid decoding every sample via ``dataset[i]``. When omitted, fold values
are read from ``sample[fold_field]``.
Args:
dataset (SampleDataset): A :class:`~pyhealth.datasets.SampleDataset`
(or compatible object exposing ``subset`` and ``__getitem__``).
train_folds (Tuple[int, ...] | List[int]): Folds assigned to train
(default ``1..8``).
val_folds (Tuple[int, ...] | List[int]): Folds assigned to validation
(default ``9``).
test_folds (Tuple[int, ...] | List[int]): Folds assigned to test
(default ``10``).
fold_field (str): Sample key holding the fold integer when ``folds``
is not provided. Defaults to ``\"strat_fold\"``.
folds (Tuple[int, ...] | List[int] | None): Optional precomputed fold
for each index. Length must equal ``len(dataset)``.
check_patient_disjoint (bool): If True, raise ``ValueError`` when a
``patient_id`` has samples in more than one split. Requires
``dataset.patient_to_index``. Defaults to False.
Returns:
tuple: ``(train_dataset, val_dataset, test_dataset)`` subsets.
Raises:
KeyError: If ``folds`` is omitted and a sample is missing ``fold_field``.
TypeError: If ``check_patient_disjoint`` is True but the dataset has
no ``patient_to_index``.
ValueError: If fold sets overlap, ``folds`` has the wrong length, a
sample fold is unassigned, or a patient leaks across splits.
Examples:
>>> # doctest: +SKIP
>>> from pyhealth.datasets import split_by_strat_fold
>>> train, val, test = split_by_strat_fold(sample_dataset)
"""
train_set = {int(f) for f in train_folds}
val_set = {int(f) for f in val_folds}
test_set = {int(f) for f in test_folds}
if train_set & val_set or train_set & test_set or val_set & test_set:
raise ValueError("train_folds, val_folds, and test_folds must be disjoint")
n_samples = len(dataset)
if folds is not None:
if len(folds) != n_samples:
raise ValueError(
f"folds has length {len(folds)} but dataset has {n_samples} samples"
)
fold_values = [int(f) for f in folds]
else:
fold_values = []
for i in range(n_samples):
sample = dataset[i]
if fold_field not in sample:
raise KeyError(
f"sample is missing {fold_field!r}; pass folds= to avoid "
"decoding samples, or emit this field from the task"
)
fold_values.append(int(sample[fold_field]))
train_index: list[int] = []
val_index: list[int] = []
test_index: list[int] = []
for i, fold in enumerate(fold_values):
if fold in train_set:
train_index.append(i)
elif fold in val_set:
val_index.append(i)
elif fold in test_set:
test_index.append(i)
else:
raise ValueError(
f"{fold_field}={fold} is not in train/val/test fold sets"
)
if check_patient_disjoint:
patient_to_index = getattr(dataset, "patient_to_index", None)
if patient_to_index is None:
raise TypeError(
"check_patient_disjoint=True requires dataset.patient_to_index"
)
split_of_index = {}
for i in train_index:
split_of_index[i] = "train"
for i in val_index:
split_of_index[i] = "val"
for i in test_index:
split_of_index[i] = "test"
leaks = []
for pid, indices in patient_to_index.items():
splits = {split_of_index[i] for i in indices if i in split_of_index}
if len(splits) > 1:
leaks.append((str(pid), splits))
if leaks:
details = "; ".join(
f"{pid} in {sorted(splits)}" for pid, splits in leaks
)
raise ValueError(
"check_patient_disjoint: "
f"{len(leaks)} patient(s) appear in multiple splits: {details}"
)
return (
dataset.subset(train_index), # type: ignore
dataset.subset(val_index), # type: ignore
dataset.subset(test_index), # type: ignore
)
[docs]def split_by_sample(
dataset: SampleDataset,
ratios: Union[Tuple[float, float, float], List[float]],
seed: Optional[int] = None,
get_index: Optional[bool] = False,
):
"""Splits the dataset by sample
Args:
dataset: a `SampleDataset` object
ratios: a list/tuple of ratios for train / val / test
seed: random seed for shuffling the dataset
get_index: if True, return three ``torch.Tensor`` index vectors
instead of datasets
Returns:
train_dataset, val_dataset, test_dataset: ``SampleDataset`` views
(``dataset.subset``) over the same processed samples, or index
tensors if ``get_index`` is True.
Raises:
TypeError: If ``ratios`` has an unsupported container or element type.
ValueError: If its length, components, or total is invalid.
Example:
>>> from pyhealth.datasets import create_sample_dataset
>>> samples = [{"patient_id": f"p{i}", "record_id": f"r{i}", "feature": i,
... "label": i % 2} for i in range(8)]
>>> dataset = create_sample_dataset(samples, {"feature": "raw"}, {"label": "raw"})
>>> train, val, test = split_by_sample(dataset, [0.5, 0.25, 0.25], seed=42)
>>> [len(part) for part in (train, val, test)]
[4, 2, 2]
Note:
The processors of ``dataset`` (vocabularies, learned statistics) were
fitted on all of its samples, so every part shaped them. To fit them on
the training part only, split inside ``set_task`` instead:
``base_dataset.set_task(task, split=...)`` with :class:`PatientSplit`
or a custom :class:`Split`.
"""
_validate_ratios(ratios, expected_length=3)
rng = np.random.default_rng(seed)
index = np.arange(len(dataset))
rng.shuffle(index)
train_index = index[: int(len(dataset) * ratios[0])]
val_index = index[
int(len(dataset) * ratios[0]) : int(len(dataset) * (ratios[0] + ratios[1]))
]
test_index = index[int(len(dataset) * (ratios[0] + ratios[1])) :]
train_dataset = dataset.subset(train_index) # type: ignore
val_dataset = dataset.subset(val_index) # type: ignore
test_dataset = dataset.subset(test_index) # type: ignore
if get_index:
return (
torch.tensor(train_index),
torch.tensor(val_index),
torch.tensor(test_index),
)
else:
return train_dataset, val_dataset, test_dataset
[docs]def split_by_patient_tuh(
dataset: SampleDataset,
ratios: Union[Tuple[float, float], List[float]],
seed: Optional[int] = None,
get_index: Optional[bool] = False,
):
"""Splits a TUH EEG dataset by PATIENT within the TUH train partition.
Like :func:`split_by_patient_conformal_tuh` but returns a 3-way split
(train / val / test) instead of 4-way (train / val / cal / test). The
test set is always the TUH eval partition; no calibration set is produced.
Ensures that **all windows from a given patient stay in the same split**
(train or val), preventing within-patient data leakage.
Args:
dataset: a ``SampleDataset`` produced by ``EEGEventsTUEV`` or
``EEGAbnormalTUAB``. Each sample must carry a ``"split"`` field
(``"train"`` or ``"eval"``) and the dataset must have a
``patient_to_index`` mapping.
ratios: fraction of *patients* in the TUH train partition to assign to
train / val respectively. Must be a length-2 sequence summing
to 1.0.
seed: random seed used to shuffle the patient list.
get_index: if ``True``, return three :class:`torch.Tensor` index
vectors instead of datasets.
Returns:
``(train_dataset, val_dataset, test_dataset)``
Raises:
TypeError: If ``ratios`` has an unsupported container or element type.
ValueError: If its length, components, or total is invalid.
Example:
>>> from pyhealth.datasets import create_sample_dataset
>>> samples = [{"patient_id": f"p{i}", "record_id": f"r{i}", "feature": i,
... "label": i % 2, "split": "train" if i < 6 else "eval"}
... for i in range(8)]
>>> dataset = create_sample_dataset(samples, {"feature": "raw"}, {"label": "raw"})
>>> train, val, test = split_by_patient_tuh(dataset, [0.5, 0.5], seed=42)
>>> [len(part) for part in (train, val, test)]
[3, 3, 2]
Note:
The processors of ``dataset`` (vocabularies, learned statistics) were
fitted on all of its samples, so every part shaped them. To fit them on
the training part only, split inside ``set_task`` instead:
``base_dataset.set_task(task, split=...)`` with :class:`PatientSplit`
or a custom :class:`Split`.
"""
_validate_ratios(ratios, expected_length=2)
train_patient_to_indices: dict = {}
test_list: List[int] = []
for pid, indices in dataset.patient_to_index.items():
first_sample = dataset[indices[0]]
assert "split" in first_sample, (
f"Patient {pid}: sample missing 'split' field. "
"Use EEGEventsTUEV or EEGAbnormalTUAB to build the dataset."
)
if first_sample["split"] == "train":
train_patient_to_indices[pid] = list(indices)
else:
test_list.extend(list(indices))
patient_ids = sorted(train_patient_to_indices, key=str)
rng = np.random.default_rng(seed)
rng.shuffle(patient_ids)
n = len(patient_ids)
train_end = int(n * ratios[0])
train_pids = patient_ids[:train_end]
val_pids = patient_ids[train_end:]
train_index = np.array(
list(chain(*[train_patient_to_indices[p] for p in train_pids]))
)
val_index = np.array(
list(chain(*[train_patient_to_indices[p] for p in val_pids]))
)
test_index = np.array(test_list)
if get_index:
return (
torch.tensor(train_index),
torch.tensor(val_index),
torch.tensor(test_index),
)
else:
return (
dataset.subset(train_index), # type: ignore
dataset.subset(val_index), # type: ignore
dataset.subset(test_index), # type: ignore
)
[docs]def split_by_sample_tuh(
dataset: SampleDataset,
ratios: Union[Tuple[float, float], List[float]],
seed: Optional[int] = None,
get_index: Optional[bool] = False,
):
"""Splits a TUH EEG dataset (TUEV/TUAB) using its pre-defined split.
Like :func:`split_by_sample_conformal_tuh` but returns a 3-way split
(train / val / test) instead of 4-way (train / val / cal / test). The
test set is always the TUH eval partition; no calibration set is produced.
Args:
dataset: a ``SampleDataset`` object produced by ``EEGEventsTUEV`` or
``EEGAbnormalTUAB``
ratios: the fraction of the train pool assigned to train / val
respectively. Must be a length-2 sequence summing to 1.0.
seed: random seed for shuffling the train pool
get_index: if True, return three ``torch.Tensor`` index vectors instead
of datasets
Returns:
train_dataset, val_dataset, test_dataset
Raises:
TypeError: If ``ratios`` has an unsupported container or element type.
ValueError: If its length, components, or total is invalid.
Example:
>>> from pyhealth.datasets import create_sample_dataset
>>> samples = [{"patient_id": f"p{i}", "record_id": f"r{i}", "feature": i,
... "label": i % 2, "split": "train" if i < 6 else "eval"}
... for i in range(8)]
>>> dataset = create_sample_dataset(samples, {"feature": "raw"}, {"label": "raw"})
>>> train, val, test = split_by_sample_tuh(dataset, [0.5, 0.5], seed=42)
>>> [len(part) for part in (train, val, test)]
[3, 3, 2]
Note:
The processors of ``dataset`` (vocabularies, learned statistics) were
fitted on all of its samples, so every part shaped them. To fit them on
the training part only, split inside ``set_task`` instead:
``base_dataset.set_task(task, split=...)`` with :class:`PatientSplit`
or a custom :class:`Split`.
"""
_validate_ratios(ratios, expected_length=2)
for i in range(len(dataset)):
assert "split" in dataset[i], (
f"Sample {i} is missing the 'split' field. "
"Use EEGEventsTUEV or EEGAbnormalTUAB to build the dataset."
)
train_pool: List[int] = []
test_list: List[int] = []
for i in range(len(dataset)):
if dataset[i]["split"] == "train":
train_pool.append(i)
else:
test_list.append(i)
rng = np.random.default_rng(seed)
train_arr = np.array(train_pool)
rng.shuffle(train_arr)
n = len(train_arr)
train_end = int(n * ratios[0])
train_index = train_arr[:train_end]
val_index = train_arr[train_end:]
test_index = np.array(test_list)
if get_index:
return (
torch.tensor(train_index),
torch.tensor(val_index),
torch.tensor(test_index),
)
else:
return (
dataset.subset(train_index), # type: ignore
dataset.subset(val_index), # type: ignore
dataset.subset(test_index), # type: ignore
)