xai4tsc.data.base

DatasetBase ABC: splitting, label encoding, saving, loading pre-split data.

Attributes

logger

Classes

PowersetLabelEncoder

Collapse multi-hot label rows to single class indices, preserving the combos.

MultiHotLabelEncoder

Keep multi-hot label rows as one target column per model output.

DatasetBase

Base class for all datasets in xai4tsc.

Functions

class_names(→ list[str])

Return the display name of each class, ordered by class index.

decode_labels(→ numpy.ndarray)

Map class indices back to their original label values.

Module Contents

xai4tsc.data.base.logger
class xai4tsc.data.base.PowersetLabelEncoder

Collapse multi-hot label rows to single class indices, preserving the combos.

Multi-label datasets emit a multi-hot label row per sample (e.g. [0, 1, 1] = attributes 1 and 2 present). Training with CrossEntropyLoss needs 1-D integer class indices, so each distinct combination is mapped to one class index - the label-powerset reduction. The combination itself is kept as the class name (classes_) so predictions can be decoded back to multi-hot later; _split_dataset() / DatasetBase.load_saved_splits() log the index→name mapping.

The cost is that the number of outputs grows as 2**L while the supervision per output shrinks, and that an attribution explains a combination - whose meaning includes the absence of the labels it omits - rather than one label. MultiHotLabelEncoder is the alternative that keeps one output per label.

Implements the small subset of the sklearn encoder interface the framework uses (fit / transform / fit_transform / inverse_transform and the classes_ attribute), so it slots into the same code paths as LabelEncoder.

fit(y: numpy.ndarray) → PowersetLabelEncoder

Record the sorted unique multi-hot rows as classes_.

transform(y: numpy.ndarray) → numpy.ndarray

Map each multi-hot row to its class index (1-D int64).

fit_transform(y: numpy.ndarray) → numpy.ndarray

Fit then transform in one call.

inverse_transform(indices: numpy.ndarray) → numpy.ndarray

Map class indices back to their multi-hot rows.

class xai4tsc.data.base.MultiHotLabelEncoder(classes: object | None = None)

Keep multi-hot label rows as one target column per model output.

A multi-label dataset emits a multi-hot row per sample (e.g. [0, 1, 1] = labels 1 and 2 present), which already is the indicator matrix a per-output head is trained against with BCEWithLogitsLoss. So there is nothing to compute here: the targets are the stored labels. The class exists to supply the encoder contract the rest of the framework reads off it - fit / transform, and the classes_ that names each output.

scikit-learn has no target encoder for this input. LabelBinarizer takes 1-D labels, and MultiLabelBinarizer takes label sets: fitting it on multi-hot rows does not raise, it reads [0, 1, 1] as the set {0, 1} and yields classes_ = [0 1], a two-column target that would size a model at two outputs. Pass MultiLabelBinarizer itself when the labels really are sets.

Parameters:

classes (array-like, optional) – The label identities in column order, with scikit-learn’s meaning: classes_ becomes a copy of this. The columns of a multi-hot row are positional, so unlike MultiLabelBinarizer this cannot determine how many there are - it has to agree with the row width, and a mismatch raises rather than attaching the wrong name to an output. Omitted, classes_ is arange(n_outputs).

See also

PowersetLabelEncoder

collapses the same rows to one index per combination.

classes = None
fit(y: numpy.ndarray) → MultiHotLabelEncoder

Record the label identity of each column as classes_.

transform(y: numpy.ndarray) → numpy.ndarray

Return the multi-hot rows as an int64 target, one column per output.

fit_transform(y: numpy.ndarray) → numpy.ndarray

Fit then transform in one call.

inverse_transform(rows: numpy.ndarray) → numpy.ndarray

Return the multi-hot rows unchanged; they are their own decoding.

xai4tsc.data.base.class_names(encoder: object) → list[str]

Return the display name of each class, ordered by class index.

Parameters:

encoder (object) – A fitted label encoder.

Returns:

One name per class index; empty when the encoder exposes no classes.

Return type:

list of str

xai4tsc.data.base.decode_labels(encoder: object, indices: numpy.ndarray) → numpy.ndarray

Map class indices back to their original label values.

The pipeline carries int64 class indices, so this is the inverse every consumer needs. It indexes classes_ directly rather than calling inverse_transform, which for a binarizer expects its own indicator matrix rather than indices.

Parameters:
  • encoder (object) – The fitted encoder the indices came from.

  • indices (np.ndarray) – 1-D array of class indices.

Returns:

Original label values, one per index. A powerset encoder returns 2-D rows.

Return type:

np.ndarray

class xai4tsc.data.base.DatasetBase(max_samples: int | None = None, sample_strategy: str = 'random', max_series_length: int | None = None, series_position: str = 'first')

Bases: abc.ABC

Base class for all datasets in xai4tsc.

Provides concrete implementations of splitting, saving, and loading pre-split data. Subclasses only need to implement load().

Data domain

data_domain is the signal domain the loaded arrays are expressed in, and it travels downstream on xai4tsc.Explanation.data_domain, where it defines the model-native domain that explainers and metrics are checked against. It is the time domain for raw series, which is every dataset shipped here; a dataset of spectra declares otherwise. Subclasses that know their own domain set it as a class attribute; LocalDataset takes it as a constructor argument, since only the user knows what is in the file.

name: str = None

Human-readable dataset identifier.

data_domain: xai4tsc._domains.Domain

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

abstractmethod load() → tuple

Load raw (unsplit) data from the source.

Returns:

(data, labels, metadata) where data has shape (n_samples, n_channels, n_timesteps).

Return type:

tuple[np.ndarray, array-like, pd.DataFrame | None]

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 into train / test / (optional) val.

Parameters:
  • train_split (float) – Fraction of samples for training.

  • val_split (float) – Fraction of samples for validation (0 disables validation set).

  • random_state (int or None) – Seed for reproducible splits, DEFAULT_SEED by default. None draws from OS entropy and is not reproducible. Ignored when rng is provided.

  • encoder (object, optional) – An sklearn-style target encoder (fit / transform / classes_), used to turn the stored labels into model targets and retained so class indices can be mapped back to names. None (default) uses LabelEncoder. The encoded rank is the formulation: 1-D gives one class index per sample, 2-D gives one column per model output. scikit-learn feature encoders (OneHotEncoder, OrdinalEncoder) are rejected - see _reject_feature_encoder().

  • impute_missing (bool) – If True, NaN values are replaced with the per-channel mean before splitting. If False (default), a ValueError is raised when NaN values are detected.

  • rng (np.random.Generator | None) – A shared numpy Generator instance. When supplied, random_state is ignored and this generator is used for all random operations (sample restriction, sklearn split seed) so that the entire pipeline draws from a single reproducible random stream.

  • stratify (bool) – If True (default), splits are stratified by class label so that every class is proportionally represented in each split. Falls back to random splitting with a warning when a class has too few samples to stratify.

  • use_predefined_splits (bool) – Use the partition the dataset itself defines, where it has one, and ignore train_split / val_split / stratify. Only subclasses that own a partition honour it - the archive’s _TRAIN/_TEST files for UcrUeaDataset, the source project’s partition for SynthMultilabelFreqDataset. A dataset with no such partition reports the request and splits normally, since there is no other partition it could have served.

Returns:

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

Return type:

tuple[list, encoder]

get_splits() → tuple

Return the cached splits produced by split().

Raises:

RuntimeError – If split() has not been called yet.

save_splits(save_path: pathlib.Path | str) → None

Save the current splits to save_path/splits/ as .npy + .json files.

Parameters:

save_path (Path or str) – Parent directory. A splits/ sub-directory is created inside it.

Raises:

RuntimeError – If no splits are available yet.

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

Load pre-split files from directory.

Looks for train*.npy, test*.npy, val*.npy (optional) and matching *.json label files.

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

  • encoder (object, optional) – An sklearn-style target encoder, as in split(). None uses LabelEncoder. It is fitted on the union of the splits so every class is represented even when one split lacks it.

Returns:

(splits, fitted_encoder).

Return type:

tuple[list, encoder]