Counterfactual explanation algorithms for time-series models (Wachter, Native-Guide, etc.)
Project description
Counterfactual Explanation Algorithms for Time Series Models
A comprehensive collection of counterfactual explanation algorithms for time series classification with PyTorch implementations. This library provides state-of-the-art methods for generating and evaluating counterfactual explanations, helping to understand and interpret deep learning models for time series data.
Table of Contents
- Quick Start
- Implemented Algorithms
- Comprehensive Evaluation Metrics
- Examples and Datasets
- Visualization Examples
- Installation
- Usage
- Key Features
- Project Structure
- License
- References and Citations
- Disclaimer
- Acknowledgments
Quick Start
# Install dependencies
pip install -r requirements.txt
# Run all examples and evaluations
cd examples
python run_all.py
# Run individual examples
python example_univariate.py # FordA dataset
python example_multivariate.py # Multi-channel Arabic digits
python metrics_evaluation_example.py # Comprehensive metrics
Implemented Algorithms
This library implements 28 state-of-the-art counterfactual explanation methods for time series classification, organized into:
- Optimization-Based Methods: Wachter, COMTE, TSCF, TS-Tweaking, FFT-CF
- Evolutionary Methods: MOC/DANDL, TSEvo, Multi-SpaCE, Sub-SpaCE
- Instance-Based Methods: Native Guide, CELS/M-CELS, AB-CF
- Latent Space Methods: CGM, CounTS, Latent-CF, LASTS, GLACIER
- Segment-Based Methods: SETS, SG-CF, DisCOX, CFWoT, TS-CEM
- Hybrid Methods: SPARCE, Time-CF, TeRCE, MG-CF, TimeX, TimeX++
๐ For detailed descriptions, key features, academic references, and code examples for each method, see REFERENCES.md
Comprehensive Evaluation Metrics
The library includes a complete suite of metrics for evaluating counterfactual quality across six key dimensions:
Validity Metrics (cfts/metrics/validity.py)
prediction_change: Verifies target class prediction is achievedclass_probability_confidence: Measures prediction confidencedecision_boundary_distance: Distance from decision boundary
Proximity Metrics (cfts/metrics/proximity.py)
l2_distance: Euclidean distance between time seriesmanhattan_distance: L1 distance measuredtw_distance: Dynamic Time Warping distancefrechet_distance: Temporal ordering-aware distancenormalized_distance: Scale-invariant distance
Sparsity Metrics (cfts/metrics/sparsity.py)
l0_norm: Number of modified time pointspercentage_changed_points: Fraction of changessegment_based_sparsity: Continuous segment modificationsgini_sparsity_coefficient: Distribution of change magnitudes
Realism Metrics (cfts/metrics/realism.py)
domain_constraint_violations: Domain-specific rule violationsstatistical_similarity: Distribution similarity to original datatemporal_consistency: Temporal pattern preservationautocorrelation_preservation: Time dependency maintenancespectral_similarity: Frequency domain characteristics
Diversity Metrics (cfts/metrics/diversity.py)
pairwise_distance: Diversity between multiple counterfactualscoverage_metric: Feature space coveragenovelty_metric: Uniqueness compared to training datadiversity_index: Shannon diversity index
Stability Metrics (cfts/metrics/stability.py)
algorithmic_stability: Consistency across runsinput_stability: Robustness to input perturbationshyperparameter_sensitivity: Parameter stability analysis
Examples and Datasets
Available Examples
example_univariate.py: FordA automotive dataset (UCR Archive)example_multivariate.py: Multi-channel spoken Arabic digitsmetrics_evaluation_example.py: Comprehensive metrics demonstration
Supported Datasets
- UCR Time Series Archive: Automatic download and preprocessing
- Synthetic Data: Built-in generators for controlled experiments
- Custom Datasets: Easy integration with custom time series data
Pre-trained Models
simple_cnn_2.pth: Binary classification (FordA)cnn_multi_arabicdigits_10ch.pth: Multi-class, multi-channel
Visualization Examples
The library generates publication-ready visualizations:
Individual counterfactuals and overlay comparisons for FordA dataset
Multi-channel counterfactual analysis for Arabic digits
Evaluation using Keane et al. (2021) metrics: Validity, Proximity, and Compactness across all algorithms
Installation
Requirements
- Python 3.9+
- PyTorch 2.0+
- NumPy, SciPy, Matplotlib
- Scikit-learn
- Captum (for attribution methods)
- Optional: dtaidistance (for DTW distance metric)
Setup
# Clone the repository
git clone https://github.com/visual-xai-for-time-series/counterfactual-explanations-for-time-series.git
cd counterfactual-explanations-for-time-series
# Install dependencies
pip install -r requirements.txt
Usage
Basic Usage
import numpy as np
from cfts.cf_wachter import wachter_genetic_cf
from cfts.cf_native_guide import native_guide_uni_cf
from cfts.metrics import l2_distance, prediction_change
# Generate counterfactual
cf, prediction = wachter_genetic_cf(sample, model, step_size=0.1)
# Evaluate quality
proximity = l2_distance(sample, cf)
validity = prediction_change(model, sample, cf, target_class=1)
Advanced Example
from cfts.metrics import CounterfactualEvaluator, benchmark_algorithms
# Comprehensive evaluation
evaluator = CounterfactualEvaluator()
results = benchmark_algorithms(
algorithms=['wachter', 'native_guide', 'comte', 'sets'],
samples=test_samples,
model=trained_model,
dataset=dataset
)
Running All Examples
# Execute complete pipeline
python examples/run_all.py
Key Features
- Research-Ready: Implementations of state-of-the-art algorithms
- Comprehensive Metrics: Six categories of evaluation measures
- Rich Visualizations: Publication-quality plots and comparisons
- Easy Integration: Simple API for custom models and datasets
- Efficient: Optimized implementations with GPU support
- Well-Documented: Extensive examples and documentation
- Reproducible: Seed control and deterministic results
- Robust: Error handling and input validation
Project Structure
counterfactual-explanations-for-time-series/
โโโ cfts/ # Main library
โ โโโ cf_ab_cf/ # AB-CF implementation
โ โโโ cf_cels/ # CELS implementation
โ โโโ cf_cem/ # TS-CEM implementation
โ โโโ cf_cfwot/ # CFWoT implementation
โ โโโ cf_cgm/ # CGM implementation
โ โโโ cf_comte/ # COMTE implementation
โ โโโ cf_counts/ # CoUNTS implementation
โ โโโ cf_dandl/ # MOC implementation
โ โโโ cf_discox/ # DisCOX implementation
โ โโโ cf_fastpace/ # FastPACE implementation
โ โโโ cf_fft_cf/ # FFT-CF implementation
โ โโโ cf_glacier/ # GLACIER implementation
โ โโโ cf_lasts/ # LASTS implementation
โ โโโ cf_latent_cf/ # Latent CF implementation
โ โโโ cf_mg_cf/ # MG-CF implementation
โ โโโ cf_multispace/ # Multi-SpaCE implementation
โ โโโ cf_native_guide/ # Native Guide implementation
โ โโโ cf_sets/ # SETS implementation
โ โโโ cf_sg_cf/ # SG-CF implementation
โ โโโ cf_sparce/ # SpArCE implementation
โ โโโ cf_subspace/ # Sub-SpaCE implementation
โ โโโ cf_terce/ # TERCE implementation
โ โโโ cf_time_cf/ # Time-CF implementation
โ โโโ cf_timex/ # TimeX implementation
โ โโโ cf_timex_plus_plus/ # TimeX++ implementation
โ โโโ cf_ts_tweaking/ # TS-Tweaking implementation
โ โโโ cf_tscf/ # TSCF implementation
โ โโโ cf_tsevo/ # TSEvo implementation
โ โโโ cf_wachter/ # Wachter et al. implementation
โ โโโ metrics/ # Evaluation metrics
โ โโโ validity.py # Validity metrics
โ โโโ proximity.py # Proximity metrics
โ โโโ sparsity.py # Sparsity metrics
โ โโโ realism.py # Realism metrics
โ โโโ diversity.py # Diversity metrics
โ โโโ stability.py # Stability metrics
โโโ examples/ # Usage examples
โ โโโ example_univariate.py # FordA dataset example
โ โโโ example_multivariate.py # Arabic digits example
โ โโโ metrics_evaluation_example.py # Metrics demo
โ โโโ run_all.py # Execute all examples
โโโ models/ # Pre-trained models
โโโ requirements.txt # Dependencies
License
Released under MIT License. See the LICENSE file for details.
References and Citations
If you use the library, please cite one of the following sources (the second one is preferred).
Core Library Citation
@software{cfts-us-2025,
author = {Schlegel, Udo},
title = {Counterfactual Explanation Algorithms for Time Series Models},
url = {https://github.com/visual-xai-for-time-series/counterfactual-explanations-for-time-series},
year = {2025}
}
Reference Paper Citation
@inproceedings{schlegel_what-if_2026,
title={What-If Explanations Over Time: Counterfactuals for Time Series Classification},
author={Schlegel, Udo and Seidl, Thomas},
booktitle={World Conference on Explainable Artificial Intelligence (XAI)},
year={2026}
}
Related Work and Surveys
-
Guidotti, R. (2022). "Counterfactual explanations and how to find them: literature review and benchmarking." Data Mining and Knowledge Discovery, 1-55.
-
Verma, S., et al. (2020). "Counterfactual explanations for machine learning: A review." arXiv preprint arXiv:2010.10596.
-
Molnar, C. (2020). "Interpretable machine learning: A guide for making black box models explainable." christophm.github.io/interpretable-ml-book/
Disclaimer
AI-Assisted Development: Please note that portions of this codebase have been generated or enhanced with the assistance of AI coding tools. While we have thoroughly tested and validated all implementations, users are encouraged to review the code and verify its correctness for their specific use cases.
Acknowledgments
This library builds upon numerous research contributions in explainable AI and counterfactual explanations. We thank all researchers and developers who have contributed to this field, particularly the authors of the implemented algorithms.
Special thanks to:
- The UCR Time Series Classification Archive for providing standard datasets
- The PyTorch and scikit-learn communities for excellent tools
- All contributors and users who help improve this library
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file counterfactuals_for_time_series-0.1.5.tar.gz.
File metadata
- Download URL: counterfactuals_for_time_series-0.1.5.tar.gz
- Upload date:
- Size: 203.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f7b8a96d0cf954321b8e195891cb78c8fe8a6becdb6053235e67ec45d76f39b6
|
|
| MD5 |
314d2c7c3b22b098872c36b0eabd7c20
|
|
| BLAKE2b-256 |
a8e3fe3feb73595140f30df153ece527d16999ea687b3c1e5afa289fcce1f655
|
Provenance
The following attestation bundles were made for counterfactuals_for_time_series-0.1.5.tar.gz:
Publisher:
publish.yml on visual-xai-for-time-series/counterfactual-explanations-for-time-series
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
counterfactuals_for_time_series-0.1.5.tar.gz -
Subject digest:
f7b8a96d0cf954321b8e195891cb78c8fe8a6becdb6053235e67ec45d76f39b6 - Sigstore transparency entry: 1135006314
- Sigstore integration time:
-
Permalink:
visual-xai-for-time-series/counterfactual-explanations-for-time-series@2db7c0f6ef19eb9de9799f5d20eddab6bec50e30 -
Branch / Tag:
refs/tags/0.1.5 - Owner: https://github.com/visual-xai-for-time-series
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@2db7c0f6ef19eb9de9799f5d20eddab6bec50e30 -
Trigger Event:
release
-
Statement type:
File details
Details for the file counterfactuals_for_time_series-0.1.5-py3-none-any.whl.
File metadata
- Download URL: counterfactuals_for_time_series-0.1.5-py3-none-any.whl
- Upload date:
- Size: 254.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
789b2c41a5d4d17e454a57eca3484602fef835b890b923d89fa3ffdde098150c
|
|
| MD5 |
4b9d610553b07bce4094a26cd8ed2336
|
|
| BLAKE2b-256 |
cc05a80d4587dcb460de38637cf1841095aa05c1263db1c540e9f6ee21f8494b
|
Provenance
The following attestation bundles were made for counterfactuals_for_time_series-0.1.5-py3-none-any.whl:
Publisher:
publish.yml on visual-xai-for-time-series/counterfactual-explanations-for-time-series
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
counterfactuals_for_time_series-0.1.5-py3-none-any.whl -
Subject digest:
789b2c41a5d4d17e454a57eca3484602fef835b890b923d89fa3ffdde098150c - Sigstore transparency entry: 1135006365
- Sigstore integration time:
-
Permalink:
visual-xai-for-time-series/counterfactual-explanations-for-time-series@2db7c0f6ef19eb9de9799f5d20eddab6bec50e30 -
Branch / Tag:
refs/tags/0.1.5 - Owner: https://github.com/visual-xai-for-time-series
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@2db7c0f6ef19eb9de9799f5d20eddab6bec50e30 -
Trigger Event:
release
-
Statement type: