Framework
The experiment runner is the standalone use case for xai4tsc. Clone the repository, write a YAML config, and run a full evaluation pipeline from the command line — no Python scripting required. Results are saved automatically to CSV files grouped by dataset and model.
Installation
git clone https://github.com/TimeXAI-group/XAI4TSC.git
cd XAI4TSC
uv sync --group runner # creates .venv from uv.lock
source .venv/bin/activate
Getting Started
Copy
experiment_runner/configs/example.yamland edit it for your datasets, models, explainers, and metrics.Run the experiment as a module from the repository root:
python -m experiment_runner --conf path/to/your/config.yaml python -m experiment_runner --conf path/to/your/config.yaml --debug
Results are written under
results_rel_path/<experiment_name>/(theexperiment_namefrom your config), organised as:results_rel_path/ └── <experiment_name>/ ├── metrics.csv # all XAI metric scores ├── models.csv # test-set performance of every model ├── experiment.log # run log └── <dataset>/ ├── metrics.csv # per-dataset metric scores ├── <dataset>_models.csv # per-dataset model performance └── <model>/ ├── metrics.csv # per-model metric scores ├── <model>_epoch_<n>.pt # best checkpoint ├── <model>_epoch_<n>_config.json # how to rebuild it └── explanations/ # per-sample relevance plotsEvery checkpoint is written with a config file named after it, so the two are unambiguously paired. It records the model name, the resolved
init_params- including the auto-detectedin_channelsandnum_classes- theepochthe weights represent, andresumed_fromwhen the run continued from an earlier checkpoint:{"model": "FCN", "init_params": {"in_channels": 1, "num_classes": 2}, "epoch": 10}
To score a trained model again without retraining it, omit the
trainkey from the model entry and pointmodel_ckpt_pathat one of those<model>_epoch_<n>.ptfiles; the architecture comes from the config file beside it and does not have to be restated. Settingtrainon that entry fine-tunes instead, and a fine-tuning run continues the epoch count, so resumingFCN_epoch_10.ptwithepochs: 5writesFCN_epoch_11.ptthroughFCN_epoch_15.ptrather than restarting at 1.Every
metrics.csvhas the same columns:Column
Meaning
datasetDataset result identity
modelModel result identity
explainerExplainer result identity (
WRAPPER-BASEfor wrapper methods)metricMetric result identity
targetThe class this row’s attributions explain, when the explanation holds one per class (
target: "all", or a per-output label encoding). Empty for a single-target explanation, where the explained class varies per samplesamplesHow many samples were handed to the metric. An upper bound rather than an exact count, since a ground-truth metric drops samples with no region of its own accord
seedThe derived seed this result was computed with, so a row can be reproduced from the row alone. Empty under
reproducible: falsestatusok(a score was produced),nan(the metric ran but could not produce a number),error(the metric raised),skipped-domain(the metric needs an explanation domain this explainer does not produce),skipped-no-ground-truth(the metric localizes against ground truth the dataset does not provide) orskipped-no-targets(no explained sample carries this target)scoreThe aggregated score; empty unless
statusisokdetailWhy, for a non-
okstatusEvery combination the run attempts gets a row, so the file accounts for the whole configuration rather than only its successes. A finished run always writes the global
metrics.csv, header-only if nothing succeeded.``models.csv`` is a different measurement and so a separate file: the test-set performance of each model, one row per (dataset, model), rather than the XAI metric scores. It starts with
dataset,model,epoch(the weights the numbers describe),statusanddetail, and the metric columns that follow depend on the formulation -pos/negand the positive class’s rates for a binary problem, macro rates for a multiclass one, andsubset_accuracy/bit_accuracy/hamming_lossfor a multi-label one. Mixing formulations in one experiment therefore gives a union of columns, with an empty cell where a formulation does not define the metric. Which columns a row has follows from the formulation and not from the split: a split with only one class present reports ananAUC and keeps every other column.The same numbers are also written per model as
<model>_e<epoch>_test_results.csv, with the one-vs-rest counts of every class, and every rate derived from them, beside it in<model>_e<epoch>_test_per_class.csv- one row per class, or per output for a multi-label model, with the same columns either way. That table is where a class’s ownaccuracy,sensitivity,specificity,ppv,npv,f1,mccandauclive; the summary carries only the aggregate. Both tables report fractions rather than percentages.Every model gets a row, including one this run did not train: an entry with no
trainkey is scored on the test split exactly like a freshly trained one, which is what pointing an entry at a checkpoint is for. A model whose iteration raises is skipped, and gets astatus: failedrow carrying the exception rather than no row at all. So the file accounts for the configuration the same waymetrics.csvdoes.epochis empty for weights whose epoch is not known - a freshly initialised model, or a checkpoint that recorded none. The files beside it are named_e0_in that case, since a file still needs a name.Confusion figures. A single-label run writes one
<model>_e<epoch>_confusion_matrix.png. A multi-label run writes one per output instead, named after the class (<model>_e<epoch>_confusion_matrix_<i>_<class>.png), because a K-by-K matrix cannot describe a problem where one sample belongs to several classes at once - its rows would not sum to the sample count. The index is in the name as well as the class, since class names come from the encoder and two of them can reduce to the same filesystem-safe spelling.Result identities. A row and its output directory are named after the config entry that produced them. Repeating an entry is supported: when two or more entries at the same level share a name, each gets a
_1,_2, … suffix in config order, so their results and artifacts stay separate. Names that occur once are used unchanged.Labels.
encodenames the label encoder:"label"forLabelEncoder(the default, oneint64class index per sample),"multihot"for multi-hot rows, which collapse to one index per distinct combination, or a dotted path to any encoder class taking no constructor arguments, e.g."sklearn.preprocessing.LabelBinarizer". An unknown name is an error rather than a silent fall-back to"label".The runner builds the object and the package takes it:
split(encoder=...)andload_saved_splits(encoder=...)accept any scikit-learn-style target encoder, so an importing user can supply their own. The output rank is the formulation - 1-D is one class index per sample, 2-D is one column per model output - and the fitted encoder is kept so indices map back to class names. Feature encoders (OneHotEncoder,OrdinalEncoder) are refused.Required settings.
experiment_name,results_rel_pathand the four component lists –data_config.datasets,train_config.models,explanation_config.explainersandevaluation_config.metrics– must be supplied. The settings blocks describe how an experiment runs; the lists describe what it runs, which has no sensible default. Omitting one fails with a message naming it, before anything is written to disk. Set a list to[]to skip that level deliberately: the run then warns and completes.Config checks. Problems are split by consequence and reported together, so one run surfaces all of them. Naming a component that is not registered is an error: the entry cannot run, and the message suggests the closest registered name. Supplying a key the runner will never read is a warning: the entry runs, but not as written. That second case is where most typos land, because a parameter name that does not match is dropped and the component silently uses its own default. Note where parameters belong, which differs by entry kind: explainers take theirs at the entry’s top level, models under
init_params, and metrics undermetric_class_paramsormetric_call_params. A parameter in the wrong place is reported with the place it belongs.Where defaults live. Every default belongs to the package parameter that consumes it – a model’s or explainer’s constructor, the arguments of
train_model()for training hyperparameters, or those ofsplit()andgenerate_explanation()for the pipeline’s own settings, so a value you omit behaves identically whether you drive the pipeline from a YAML config or import the package.A component’s parameters reach it through
dict_to_args(), which simply does not pass what you did not set. The settings in adefault_settingsblock are read by the runner before it calls anything, so for those it keeps a table_PACKAGE_BACKEDinexperiment_runner/defaults.py, naming the parameter that owns each key, and reads the value off that signature at startup. A renamed parameter therefore fails immediately instead of leaving a stale copy behind. Keys the package never sees, such as theskip_*switches and the Quantus parameter blocks, are listed alongside as runner-owned, and for thosemaster.yamlis the source. The two lists must together cover every key, which a test enforces.master.yamldocuments all of them in comments but supplies only the runner-owned ones, so the two entry points cannot diverge; a test compares every documented value against the signature it came from.
experiment_runner/configs/master.yaml is the annotated reference for every
available config key. It is not runnable: it lists each component as a
catalogue of what is available, so running it directly is refused with a pointer
to configs/example.yaml. Copy the entries you need into your own config.
Example
The shipped experiment_runner/configs/example.yaml is the go-to demo and the
config the runner uses by default (python -m experiment_runner). It
needs no download: the synthetic Synth_Multilabel_Freq dataset is generated
on first use and cached. It trains two model architectures (LeNet and FCN), explains them
with three time-domain methods (Integrated Gradients, Guided Backpropagation,
and TSHAP), and scores those explanations with the Complexity and Pixel-Flipping
metrics:
# =============================================================================
# example.yaml — the go-to demo for xai4tsc (time domain).
#
# This is the config the runner uses by default:
# python -m experiment_runner.main
#
# It needs no download: the synthetic `Synth_Multilabel_Freq` dataset is generated
# locally (and cached). It trains two model architectures, explains them with three
# time-domain XAI methods, and scores those explanations with time-domain
# metrics.
#
# For the frequency / time-frequency counterpart, see `example_frequency.yaml`.
# For an annotated reference of every available option, see `master.yaml`.
# =============================================================================
experiment_name: "example_time"
xai4tsc_version: ">=2.0.0.dev0,<3"
# Generated datasets, splits, and checkpoints are cached here and reused.
cache_path: "./cache/"
general:
reproducible: true
seed: 2025
device: "use_available"
# The example uses a generated synthetic dataset, a reference can be found in
# the class documentation.
data_config:
default_settings:
train_split: 0.7
val_split: 0.15
datasets:
- dataset: "Synth_Multilabel_Freq" # SyntheticDataset registry key
encode: "multihot" # one output per frequency, not one per combo
encode_params:
classes: ["7Hz", "19Hz", "37Hz"] # names the outputs in the per-output results
use_predefined_splits: true # the dataset's own published splits
# --- Models: two different architectures, both trained ---
train_config:
default_settings:
hyperparams:
epochs: 10
batchsize: 32
loss_func: "bcewithlogits" # per-output targets: one independent
# decision per frequency, not one of K
optimizer: "adam"
learn_rate: 0.001
patience: 3
save_best: true
train: true
models:
- model: "LeNet" # smallest built-in CNN
- model: "FCN" # fully-convolutional baseline
# in_channels / num_classes are auto-detected per dataset.
# --- Explainers: three time-domain methods ---
explanation_config:
default_settings:
target: "predicted"
samples:
type: "random"
count: 5
explainers:
- method: Integrated_Gradients
- method: Guided_Backpropagation
- method: TSHAP # exact 2-player Shapley over time windows
window_length: 0.1 # fraction of T per window
stride: 10 # compute every 10th window start (bounds cost)
perturb_baseline: "centroid"
background_data: train_set
# --- Metrics: time-domain ---
evaluation_config:
default_settings:
metric_class_params:
normalise: true
abs: true
disable_warnings: true
return_aggregate: true
metric_call_params:
softmax: false # the outputs are independent per-label probabilities
# already; renormalising them would move every score
metrics:
- metric: "Complexity" # cheap: counts non-zero attributions
- metric: "Pixel-Flipping" # faithfulness via progressive perturbation
results_rel_path: "./experiments/results/"
For the frequency / time-frequency counterpart — FreqRISE and the frequency
metrics on the same dataset — see
experiment_runner/configs/example_frequency.yaml. Full archive sweeps are in
ucr_benchmark.yaml and uea_benchmark.yaml.
API Reference
The experiment runner is built around a small set of modules:
experiment_runner.main— entry point, orchestrates the pipelineexperiment_runner.config— config resolution and validationexperiment_runner.cache— caching layer for resultsexperiment_runner.evaluate— evaluation routinesexperiment_runner.explain— explanation generationexperiment_runner.log_setup— logging configuration
See the full experiment_runner for complete details.