Package

The xai4tsc package is the importable use case. Install it with pip and use the public API in your own code, notebooks, or scripts to load datasets, train classifiers, generate explanations, and evaluate them quantitatively. All three registries (MODELS, EXPLAINERS, METRICS) support runtime extension via the register_* functions.

Installation

# editable install from a local clone (not yet published to PyPI)
pip install -e PATH/TO/XAI4TSC

Getting Started

The typical workflow follows four steps: load data, train a model, generate explanations, and evaluate them. The example below shows the full sequence using a UCR dataset and a built-in model.

Example

import xai4tsc
from xai4tsc.data import load_dataset
from xai4tsc.evaluation.evaluate import evaluate
from xai4tsc.models.models import load_model
from xai4tsc.xai.explain import generate_explanation


def main(out_dir: str) -> None:
    """
    Run an example to showcase package capabilities.

    Parameters
    ----------
    out_dir : str
        Directory to safe the output to.
    """
    # Enable package logging to the console and to <out_dir>/xai4tsc.log
    xai4tsc.enable_logging(out_dir)

    # Load data (UCR download or local numpy files)
    ds = load_dataset("GunPoint", use_predefined_splits=True)
    splits, encoder = ds.split(train_split=0.8, val_split=0.1, random_state=42)
    ds.save_splits(out_dir)
    train_data, train_labels, _ = splits[0]
    test_data, test_labels, _ = splits[1]

    # Load a model
    model = load_model(
        {"model": "FCN", "init_params": {"in_channels": 1, "num_classes": 2}},
        device="cpu",
    )

    # Set up hyperparameters
    hyperparams = {
        "epochs": 10,
        "batchsize": 32,
        "loss_func": "CrossEntropy",
        "optimizer": "adam",
        "learn_rate": 0.001,
        "patience": 3,
    }

    # Train the model
    model.train_model(
        train_data,
        train_labels,
        hyperparams,
        save_path=out_dir,  # best checkpoint + training plots land here
    )

    # Evaluate on test data
    model.evaluate_model(
        test_data,
        test_labels,
        hyperparams,
        save_path=out_dir,  # save model performance data
    )

    # Generate explanations
    exp = generate_explanation(
        method="integrated_gradients",
        model=model,
        data=test_data,
        labels=test_labels,
        encoder=encoder,
        indices=[0, 1, 2],
        device="cpu",
    )

    # Evaluate the explanations
    _ = evaluate(
        model=model,
        metric="Complexity",
        explanation=exp,
        data=test_data[exp.indices],
        labels=test_labels[exp.indices],
        metric_class_params={"normalise": True, "abs": True, "disable_warnings": True},
        device="cpu",
    )


if __name__ == "__main__":
    main("experiments/results/getting_started")

API Reference

The package is organised into the following submodules:

Key functions

The four functions a package user reaches for, in pipeline order. Each is also re-exported at the top level (e.g. from xai4tsc import generate_explanation) and from its submodule (e.g. from xai4tsc.models import load_model).

Function

Purpose

load_dataset()

Load a UCR/UEA, local, or synthetic dataset.

load_model()

Instantiate a model by name or from a checkpoint.

generate_explanation()

Produce an Explanation for chosen samples.

evaluate()

Score an explanation with a metric from the registry.

Built-in components

These are the concrete classes you select at runtime — by registry key in a YAML config or in the package API (load_model, generate_explanation(method=...), evaluate(metric=...)). The key is what you pass; the class is where its parameters and behaviour are documented. Extend any registry at runtime with the matching register_* function.

Models (xai4tsc.MODELS)

Registry key

Class

fcn

FCN

lenet

LeNet

resnet

ResNet

lstm

LSTM

patchtst

PatchTST

xlstm

XLSTM

Explainers (xai4tsc.EXPLAINERS)

Registry key

Class

integrated_gradients

IntegratedGradientsExplainer

guided_backpropagation

GuidedBackpropagationExplainer

deconvolution

DeconvolutionExplainer

deeplift

DeepLiftExplainer

occlusion

OcclusionExplainer

tshap

TSHAPExplainer

sign

SignExplainer

freqrise

FreqRISEExplainer

frequency

FrequencyExplainer

timefrequency

TimeFrequencyExplainer

random_frequency

RandomFrequencyExplainer

random_timefrequency

RandomTimeFreqExplainer

Metrics (xai4tsc.METRICS)

Every METRICS value is a callable that produces an EvaluatorBase. Most registry keys map to Quantus metric classes (listed in xai4tsc.QUANTUS_METRICS, e.g. "Complexity", "Faithfulness Correlation", "ROAD"), adapted by the single QuantusEvaluator (bound to the metric name); see the Quantus documentation for those. The xai4tsc-native metrics are:

Registry key

Class

Frequency Perturbation

FrequencyEvaluator

Time-Frequency Perturbation

TimeFrequencyEvaluator

Time-Frequency Perturbation Gaussian

TimeFrequencyEvaluatorGaussian

Time-Frequency AUC

TimeFrequencyAUCEvaluator

Extending the package

If you want to add a custom dataset, model, explainer or evaluator, subclass the relevant base class:

See the full xai4tsc for complete details.