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_univariate_ecg.py # ECG200 dataset
python example_univariate_faultdetectiona.py # FaultDetectionA dataset
python example_multivariate.py # Multi-channel Arabic digits
python example_metrics_evaluation.py # Comprehensive metrics
Implemented Algorithms
This library implements 30 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, CONFETTI
- Latent Space Methods: CGM, CounTS, Latent-CF, LASTS, GLACIER
- Segment-Based Methods: SETS, SG-CF, DisCOX, CFWoT, TS-CEM, FastPACE
- 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 fault detection dataset (UCR Archive)example_univariate_ecg.py: ECG200 electrocardiogram dataset (UCR Archive)example_univariate_faultdetectiona.py: FaultDetectionA electromechanical drive dataset (3-class)example_multivariate.py: Multi-channel spoken Arabic digits (13 channels)example_metrics_evaluation.py: Comprehensive metrics evaluation across all 30+ algorithms
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_forda_2.pth: Binary classification (FordA)simple_cnn_ecg200_2.pth: Binary classification (ECG200)simple_cnn_faultdetectiona_3.pth: 3-class classification (FaultDetectionA)cnn_multi_arabicdigits_10ch.pth: 10-class multi-channel (Arabic Digits)
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_univariate_ecg.py # ECG200 dataset example
│ ├── example_univariate_faultdetectiona.py # FaultDetectionA example
│ ├── example_multivariate.py # Arabic digits example
│ ├── example_metrics_evaluation.py # Comprehensive 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
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.6.tar.gz.
File metadata
- Download URL: counterfactuals_for_time_series-0.1.6.tar.gz
- Upload date:
- Size: 357.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dcf1d6efba1e89e31cbf530d7c3f2dd932b3200b2bdefb6dc0ee34d1ecd8a65a
|
|
| MD5 |
b51b3a49d3154372ddedccc5a223cfda
|
|
| BLAKE2b-256 |
cd622f9ab41e40c9a12294a147e802ca9a6b9c9c48072ca60b123f30cc8e3883
|
Provenance
The following attestation bundles were made for counterfactuals_for_time_series-0.1.6.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.6.tar.gz -
Subject digest:
dcf1d6efba1e89e31cbf530d7c3f2dd932b3200b2bdefb6dc0ee34d1ecd8a65a - Sigstore transparency entry: 2506805868
- Sigstore integration time:
-
Permalink:
visual-xai-for-time-series/counterfactual-explanations-for-time-series@c5dcd9285ca1c43afa4d269d54e1903bf2c162a0 -
Branch / Tag:
refs/tags/0.1.6 - 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@c5dcd9285ca1c43afa4d269d54e1903bf2c162a0 -
Trigger Event:
release
-
Statement type:
File details
Details for the file counterfactuals_for_time_series-0.1.6-py3-none-any.whl.
File metadata
- Download URL: counterfactuals_for_time_series-0.1.6-py3-none-any.whl
- Upload date:
- Size: 417.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a6afeead5c4b346f04c16a1c247489c16205e233b0ec4c34142158a79e136eb7
|
|
| MD5 |
34cd2e69036e949350392a5687d7188f
|
|
| BLAKE2b-256 |
cefb184277799b8459bb71806f85e755de1a3adcc4da876adb37aaed736354a1
|
Provenance
The following attestation bundles were made for counterfactuals_for_time_series-0.1.6-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.6-py3-none-any.whl -
Subject digest:
a6afeead5c4b346f04c16a1c247489c16205e233b0ec4c34142158a79e136eb7 - Sigstore transparency entry: 2506805945
- Sigstore integration time:
-
Permalink:
visual-xai-for-time-series/counterfactual-explanations-for-time-series@c5dcd9285ca1c43afa4d269d54e1903bf2c162a0 -
Branch / Tag:
refs/tags/0.1.6 - 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@c5dcd9285ca1c43afa4d269d54e1903bf2c162a0 -
Trigger Event:
release
-
Statement type: