Counterfactual Explanations for Time Series

June 21, 2026 ยท View on GitHub

PyPI Version Python Versions Wheel CI Status Documentation Status License

CONFETTI Logo


Counterfactual Explanations for Time Series

CONFETTI is a multi-objective method for generating counterfactual explanations for multivariate time series classifiers. It identifies the most influential features or temporal regions, constructs a minimal perturbation, and optimizes it under multiple objectives to produce sparse, realistic, and confidence-increasing counterfactuals.

CONFETTI is model-agnostic and works with any classifier โ€” Keras, PyTorch, or scikit-learn.


โœจ Highlights

  • Multi-objective optimization using NSGA-III
  • Time series: works with any Torch/Keras/scikit-learn multivariate time series classifier
  • Rust-accelerated backend for distances and NSGA-III
  • Optional use of class activation maps for feature-weighted perturbations
  • Built-in distance metrics: Euclidean, Manhattan, DTW, Soft-DTW, GAK, CTW
  • Generates multiple diverse counterfactuals per instance
  • Parallelized counterfactual generation

๐Ÿš€ Installation

PyPI Installation

pip install confetti-ts

Pre-built wheels are available for common platforms. If no wheel is available for your system, the install requires a Rust toolchain.

Development Installation

git clone https://github.com/serval-uni-lu/confetti.git
cd confetti

uv venv
source .venv/bin/activate
uv pip install -e .

Core dependencies:

  • Python 3.12+
  • NumPy, pandas, scikit-learn, joblib, matplotlib

Optional (model backends):

  • Keras 3.x + TensorFlow (pip install confetti-ts[keras])
  • PyTorch (pip install confetti-ts[torch])
  • All backends (pip install confetti-ts[all])

โšก Quick Example โ€” Time Series

Below is a minimal end-to-end example for multivariate time series counterfactuals. It loads a trained model, prepares a dataset, and generates counterfactuals for a single instance.

The example files are included in the repository under examples/. Clone it first with git clone https://github.com/serval-uni-lu/confetti.git.

from confetti import CONFETTI
from confetti.attribution import cam
from confetti.utils import load_multivariate_ts_from_csv
from confetti.visualizations import plot_counterfactual
import keras

# Load model
model_path = "examples/models/toy_fcn.keras"
model = keras.models.load_model(model_path)

# Load dataset in (n_samples, time_steps, n_features) format
X_train, y_train = load_multivariate_ts_from_csv("examples/data/toy_train.csv")
X_test, y_test   = load_multivariate_ts_from_csv("examples/data/toy_test.csv")

# Select instance to explain
instance = X_test[0:1]

# Generate CAM weights for training data (optional)
training_weights = cam(model, X_train)

# Initialize explainer
explainer = CONFETTI(model_path=model_path)

# Generate counterfactuals
results = explainer.generate_counterfactuals(
    instances_to_explain=instance,
    reference_data=X_train,
    reference_weights=training_weights,      # or None if not available
)

# results is a CounterfactualResults list โ€” one CounterfactualSet per instance.
# Each set contains the original instance, the best counterfactual, all
# candidates, and the NUN's CAM feature-importance weights (when provided).
cf_set = results[0]

# Visualize the best counterfactual
plot_counterfactual(
    original=cf_set.original_instance,
    counterfactual=cf_set.best,
    cam_weights=cf_set.feature_importance,
    cam_mode="heatmap",
    title="Counterfactual Explanation"
)

Counterfactual Example

In the visualization:

  • green curves represent the original instance
  • red curves represent the counterfactual subsequence
  • the heatmap corresponds to CAM scores of the nearest unlike neighbor

๐Ÿ†• What's New in v1.0.1

  • Stable release โ€” production-ready API with no breaking changes expected
  • Rust-accelerated backend โ€” distances (DTW, Soft-DTW, GAK, Manhattan) and NSGA-III components via PyO3
  • Custom NSGA-III โ€” zero-dependency genetic algorithm (pymoo removed)
  • Built-in distance metrics โ€” pure-numpy DTW, Soft-DTW, GAK, CTW, Manhattan (tslearn removed)
  • PyTorch adapter โ€” use PyTorch models alongside Keras and scikit-learn
  • Visualization theming โ€” light/dark theme support with improved plot aesthetics

See the full CHANGELOG for details.


๐Ÿ“š Documentation

The full documentation, including usage guides, API reference, and examples, is available at:

๐Ÿ‘‰ https://confetti-ts.readthedocs.io/en/latest/


๐Ÿ“„ License

CONFETTI is released under the MIT License.


๐Ÿ“ Citing CONFETTI

If you use CONFETTI in your research, please consider citing the following paper:

@inproceedings{cetina2026counterfactual,
  title={Counterfactual Explainable AI (XAI) Method for Deep Learning-Based Multivariate Time Series Classification},
  author={Cetina, Alan Gabriel Paredes and Benguessoum, Kaouther and Lourenco, Raoni and Kubler, Sylvain},
  booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},
  volume={40},
  number={21},
  pages={17393--17400},
  year={2026}
}

The original code used when the method was published is at the paper branch of this repository. It contains the experiment scripts, model configurations, and dataset handling used in the publication.