xai4tsc.data.base

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

Attributes

logger

Classes

MultiHotLabelEncoder

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

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 1-D class indices back to their original label values.

Module Contents

xai4tsc.data.base.logger
class xai4tsc.data.base.MultiHotLabelEncoder

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 uses CrossEntropyLoss on 1-D integer class indices, so each distinct combination is mapped to one class index. 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.

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) → MultiHotLabelEncoder

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.

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 1-D class indices back to their original label values.

The pipeline carries int64 class indices, so this is the inverse every consumer needs. It is not simply encoder.inverse_transform: that expects the encoder’s own output, which for OneHotEncoder is an (n, K) 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. Multi-hot encoders return 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.0, random_state: int | None = DEFAULT_SEED, encode: str = 'label', impute_missing: bool = False, rng: numpy.random.Generator | None = None, stratify: bool = True, class_order: list | None = None) → 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.

  • encode (str) – Label encoding scheme: "label" (default), "onehot", or "ordinal".

  • 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.

  • class_order (list, optional) – Explicit class order for encode="ordinal", forwarded to _make_encoder(). Needed only for ordered string labels, whose order is otherwise lexicographic.

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, encode: str = 'label') → 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.

  • encode (str) – Label encoding scheme.

Returns:

(splits, fitted_encoder).

Return type:

tuple[list, encoder]