xai4tsc.data.datasets

Dataset classes: UcrUeaDataset, LocalDataset, SyntheticDataset.

Attributes

logger

SYNTHETIC_DATASETS

Classes

UcrUeaDataset

Download from the UCR/UEA archive and load raw (unsplit) data.

LocalDataset

Load a single-file dataset from a local directory.

SyntheticDataset

Base class for programmatically generated datasets.

SynthMultilabelFreqDataset

Multi-label synthetic dataset with time-frequency ground-truth explanations.

Functions

register_synthetic_dataset(→ None)

Register a custom SyntheticDataset subclass under name.

load_dataset(→ xai4tsc.data.base.DatasetBase)

Resolve to the correct DatasetBase subclass.

Module Contents

xai4tsc.data.datasets.logger
class xai4tsc.data.datasets.UcrUeaDataset(name: str, cache_dir: pathlib.Path | None = None, download: bool = True, pad_series: bool = False, max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first')

Bases: xai4tsc.data.base.DatasetBase

Download from the UCR/UEA archive and load raw (unsplit) data.

name

Human-readable dataset identifier.

cache_dir
download = True
pad_series = False
load() → tuple

Load raw data from the UCR/UEA archive via sktime.

sktime downloads and caches the .ts files under cache_dir (passed as extract_path). Restrictions (max_samples, max_series_length) are applied after loading. The caller (split()) saves the processed train / val / test arrays to the split cache.

split(train_split: float = 0.8, val_split: float = 0.1, random_state: int | None = DEFAULT_SEED, encoder: object | None = None, impute_missing: bool = False, rng: numpy.random.Generator | None = None, stratify: bool = True, use_predefined_splits: bool = False) → tuple

Load and split the dataset.

When use_predefined_splits is True, loads the official _TRAIN.ts and _TEST.ts files directly and ignores train_split, val_split, and stratify. No validation set is produced, and passing a non-default value for any of the three is reported rather than silently dropped. It defaults to False because the archive partition has no validation split, so selecting it would silently void the fractions a caller asked for and leave early stopping monitoring training loss.

Otherwise delegates to DatasetBase.split() for random / stratified splitting.

class xai4tsc.data.datasets.LocalDataset(path: str | pathlib.Path, name: str, data_format: str = 'numpy', layout: str = 'auto', data_domain: str | xai4tsc._domains.Domain = 'time', pad_series: bool = False, max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first')

Bases: xai4tsc.data.base.DatasetBase

Load a single-file dataset from a local directory.

The directory must contain one data*.npy file and one label*.json file (unsplit layout). For pre-split local data, use load_saved_splits() directly.

path
name

Human-readable dataset identifier.

data_format = 'numpy'
layout = 'auto'
data_domain

Signal domain the loaded arrays are expressed in (see above).

pad_series = False
load() → tuple

Load raw data from the local directory using the configured format loader.

Returns:

(data, labels, metadata) with data in (B, C, T) layout.

Return type:

tuple

class xai4tsc.data.datasets.SyntheticDataset(name: str, cache_dir: str | pathlib.Path | None = None, seed: int = DEFAULT_SEED, max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first')

Bases: xai4tsc.data.base.DatasetBase, abc.ABC

Base class for programmatically generated datasets.

Subclasses implement generate_dataset() (pure, deterministic given the constructor’s seed + parameters). The concrete load() here owns caching: it first looks for a previously generated dataset on disk and only regenerates on a miss.

Caching layout (under cache_dir/synthetic/<cache_key>/):

  • data.npy — generated array (B, C, T)

  • labels.json — labels as records ([{"label": ...}, ...]; multi-hot labels are stored as lists)

  • metadata.json — per-sample metadata records (optional)

Metadata convention: one row per sample, index-aligned with data in the same order. For ground-truth localization datasets it carries the discriminative regions keyed per class (ground_truth) plus distractors (non_discriminative); see the package data conventions.

Example:

class GaussianDataset(SyntheticDataset):
    def _cache_params(self):
        return {"n": self.n_samples, "c": self.n_classes, "t": self.length}

    def generate_dataset(self):
        rng = np.random.default_rng(self.seed)
        data = rng.standard_normal((self.n_samples, 1, self.length))
        labels = rng.integers(0, self.n_classes, self.n_samples)
        return data.astype("float32"), labels, None
name

Human-readable dataset identifier.

cache_dir
seed = 3735928559
abstractmethod generate_dataset() → tuple

Generate and return (data, labels, metadata) — deterministic.

data is (B, C, T) float32; labels is (B,) integer or (B, n_attrs) multi-hot (collapsed to class indices by the multihot encoder); metadata is the per-sample DataFrame (or None).

cache_subdir(root: str | pathlib.Path) → pathlib.Path

Return this dataset’s cache directory under root/synthetic/.

static is_split_layout(directory: str | pathlib.Path) → bool

Return True if directory holds a pre-split train/test layout.

static is_raw_layout(directory: str | pathlib.Path) → bool

Return True if directory holds a single generated blob (not split).

load() → tuple

Return raw (data, labels, metadata), generating + caching on a miss.

With no cache_dir the dataset is generated fresh. Otherwise the cache directory is checked first (first-look); on a hit the persisted blob is loaded without regeneration, on a miss it is generated and persisted.

class xai4tsc.data.datasets.SynthMultilabelFreqDataset(name: str = 'Synth_Multilabel_Freq', cache_dir: str | pathlib.Path | None = None, seed: int = 42, sample_length: int = 500, sampling_rate: int = 100, discriminative_frequencies: tuple[int, ...] = (7, 19, 37), frequency_window_length: int = 150, num_samples_per_pattern: int = 500, overlap_min: float = 0.25, overlap_max: float = 0.5, noise_std: float = 0.1, sin_amplitude: float = 1.0, num_full_distractions: int = 3, num_window_distractions: int = 3, train_ratio: float = 0.7, test_ratio: float = 0.15, max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first')

Bases: SyntheticDataset

Multi-label synthetic dataset with time-frequency ground-truth explanations.

Each sample is a sum of sinusoidal bursts. A multi-hot label marks which discriminative frequencies are present: frequency k of discriminative_frequencies contributes a burst of frequency_window_length samples at a random time window, and the classes are the power set of those frequencies (3 frequencies give 8 classes). Non-discriminative distractor sinusoids are added at other frequencies, some spanning the whole series and some windowed, so the discriminative signal has to be localized in both time and frequency to be found.

Per-sample metadata records the discriminative regions under ground_truth and the distractors under non_discriminative, which makes this dataset a ground truth for the localization metrics (e.g. Time-Frequency AUC). Regions are stored as the plain mappings that survive the JSON round-trip of save_splits(), with the singular channel / freq / phase keys; from_mapping() parses them.

Region frequencies are recorded in Hz, as the source dataset writes them, and every metadata row carries the sampling_rate they are relative to.

The dataset owns its own train / test / val partition - the source repository’s two-stage stratified split, seeded by seed - so the train_split and val_split arguments of split() are not used. Configure the partition with train_ratio and test_ratio instead.

Notes

Adapted from the reference implementation at https://github.com/TimeXAIgroup/multilabel-ts-xai-benchmark (data/benchmark.py, generate_dataset.py, utils.py), MIT licensed, Copyright (c) 2026 TimeXAIgroup; see THIRD_PARTY_LICENSES.md.

References

J. Fischer, N. Gumpfer, T. Papenbrock, and J. Hannig, “A Synthetic Multi-Label Time Series Classification Dataset with Time-Frequency Ground-Truth Explanation for Evaluating Explainable Artificial Intelligence Methods”, SSRN preprint 7389286. Dataset: https://doi.org/10.5281/zenodo.20744119

data_domain: xai4tsc._domains.Domain

the discriminative features are frequencies localized in time, but the arrays themselves are time-domain (B, 1, T) float32.

Type:

Raw series

sample_length = 500
sampling_rate = 100
discriminative_frequencies = (7, 19, 37)
frequency_window_length = 150
num_samples_per_pattern = 500
overlap_min = 0.25
overlap_max = 0.5
noise_std = 0.1
sin_amplitude = 1.0
num_full_distractions = 3
num_window_distractions = 3
train_ratio = 0.7
test_ratio = 0.15
property nyquist_frequency: int

Highest representable frequency in Hz, bounding the distractor pool.

property distractor_pool: numpy.ndarray

Integer frequencies in Hz available to distractors, in ascending order.

generate_dataset() → tuple

Generate the whole dataset, unsplit.

Returns:

(data, labels, metadata) where data is (B, 1, T) float32, labels is (B, n_frequencies) multi-hot and metadata holds one row per sample with ground_truth, non_discriminative and sampling_rate.

Return type:

tuple[np.ndarray, np.ndarray, pd.DataFrame]

split(train_split: float = 0.8, val_split: float = 0.1, random_state: int | None = DEFAULT_SEED, encoder: object | None = None, impute_missing: bool = False, rng: numpy.random.Generator | None = None, stratify: bool = True, use_predefined_splits: bool = True) → tuple

Generate (or load from cache) and split, by this dataset’s own partition.

With use_predefined_splits (the default), the partition is the source repository’s: two chained stratified train_test_split calls seeded by this dataset’s seed, giving train_ratio / test_ratio / remainder. It is then a property of the dataset rather than of the run, so re-running returns the same rows and the published dataset is reproduced.

Set it to False for the framework’s ordinary splitting, which honours train_split / val_split / stratify like any other dataset. The ground-truth regions are scoped to their classes on both paths.

Parameters:
  • train_split (float) – Fraction of samples for training. Ignored under use_predefined_splits, where the partition comes from train_ratio; a value that disagrees with it is reported once.

  • val_split (float) – Fraction of samples for validation. Ignored under use_predefined_splits, where it is 1 - train_ratio - test_ratio; a value that disagrees with it is reported once.

  • random_state (int or None) – Seeds the sample restriction only. The partition uses the dataset’s own seed.

  • encoder (object, optional) – An sklearn-style target encoder. MultiHotLabelEncoder (one output per frequency) or PowersetLabelEncoder (one class per combination) both fit this dataset’s multi-hot labels, and either lets a region be scoped to the classes it discriminates.

  • impute_missing (bool) – Accepted for signature parity. Generated data holds no NaN, so there is nothing to impute.

  • rng (np.random.Generator or None) – Shared generator for the sample restriction; overrides random_state.

  • stratify (bool) – Stratify the splits by class. Ignored under use_predefined_splits, where the partition is stratified by class combination by construction.

  • use_predefined_splits (bool) – Use this dataset’s own partition, the default here because that partition is part of the published dataset this generator reproduces and it already yields a validation split, so nothing is lost by preferring it.

Returns:

(splits, fitted_encoder) where splits is a list of (X, y, metadata) tuples in order [train, test, val].

Return type:

tuple[list, encoder]

load_saved_splits(directory: pathlib.Path | str, encoder: object | None = None) → tuple

Load the saved splits and scope each region to the classes it marks.

Parameters:
  • directory (Path or str) – Directory containing the split files.

  • encoder (object, optional) – An sklearn-style target encoder, as in split().

Returns:

As load_saved_splits(), with classes added to every ground-truth region.

Return type:

tuple[list, encoder]

xai4tsc.data.datasets.SYNTHETIC_DATASETS: dict[str, type]
xai4tsc.data.datasets.register_synthetic_dataset(name: str, dataset_class: type) → None

Register a custom SyntheticDataset subclass under name.

The factory xai4tsc.data.load_dataset() dispatches name=<name> to the registered class (checked before the path/UCR branches), so registering a name makes it loadable by name.

Parameters:
  • name (str) – Registry key (matched against load_dataset’s name).

  • dataset_class (type) – A SyntheticDataset subclass.

xai4tsc.data.datasets.load_dataset(name: str, path: str | None = None, cache_dir: str | None = None, pad_series: bool = False, max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first', layout: str = 'auto', data_domain: str = 'time', **kwargs: object) → xai4tsc.data.base.DatasetBase

Resolve to the correct DatasetBase subclass.

Parameters:
  • name (str) – Human-readable dataset name (always required). If name is in the SYNTHETIC_DATASETS registry, the matching SyntheticDataset is returned (checked first) and generation params are forwarded as **kwargs.

  • path (str | Path | None) – If provided, a LocalDataset is returned pointing at path. If None (and name is not a synthetic dataset), a UcrUeaDataset is returned.

  • cache_dir (Path | None) – Passed through to UcrUeaDataset when path is None, stores UCR / UEA datasets to mitigate multiple downloads.

  • pad_series (bool) – If True, variable-length series are zero-padded to the maximum series length before returning data. Passed to the selected subclass.

  • max_samples (int | None) – Subsample to at most this many samples before splitting. Prevents OOM on very large datasets (e.g. InsectWingbeat).

  • sample_strategy (str) – How to select the subset when max_samples is active: "random" (default), "first", "last", or "stratified".

  • max_series_length (int | None) – Truncate each series to at most this many timesteps. Applied before padding for variable-length datasets.

  • series_position (str) – Which end of a long series to retain: "first" (default) or "last".

  • layout (str) – Axis order of a local array: "auto" (default), "bct" or "btc". Only meaningful with path; UCR/UEA and synthetic data are already (B, C, T), so it is not forwarded to them.

  • data_domain (str) – Signal domain a local array is expressed in: "time" (default), "frequency" or "time_frequency". Only meaningful with path: UCR/UEA data is always raw series and a synthetic dataset declares its own domain, so a non-default value is ignored with a warning for those.

  • **kwargs – Forwarded to the selected subclass constructor (e.g. download, data_format).