TSInterpret

repository·main·Indexed 40 days ago

https://github.com/fzi-forschungszentrum-informatik/tsinterpret

A Python library for the interpretability of time series classification models. It provides a unified interface for various interpretability algorithms, including COMTE, LEFTIST, NUN-CF, SETS, TSEvo, and TSR, with support for TensorFlow, PyTorch, and scikit-learn backends.

Tokens
11.6K
Snippets
31
Records
47
Agent score
49%

What's inside TSInterpret

  1. Overview of TSInterpret

    main

    TSInterpret is a Python library designed for interpreting time series classification models. It provides a unified interface for various interpretability algorithms specifically adapted for time series data, rather than relying on general-purpose tabular or image explainability methods that ignore the temporal component.

    Key features include:

    • Support for multiple frameworks: PyTorch (pytorch), TensorFlow (tf), and scikit-learn (sklearn).
    • Implementation of specialized algorithms like Counterfactual (Ates et al.), NUN-CF, LEFTIST, TSR, SETS, and TSEvo.
    • Unified visualizations for interpretability results.
    • Integration with existing libraries such as shap, captum, and tf-explain where applicable.
  2. Overview of implemented algorithms in TSInterpret

    main

    TSInterpret provides several algorithms for time series interpretability, categorized by their method type (InstanceBased or FeatureAttribution), data compatibility (univariate or multivariate), and backend requirements.

    Algorithm Comparison Table

    MethodBackendTypeDataTraining Set Required
    COMTETF, PYT, SK, BBInstanceBasedmultiy
    LEFTISTTF, PYT, SK, BBFeatureAttributionuniy
    NUN-CFTF, PYT, SKInstanceBaseduniy
    SETSTFInstanceBaseduni & multiy
    TSEvoTF, PYTInstanceBaseduni & multiy
    TSRTF, PYTFeatureAttributionmultin

    Legend:

    • BB: black-box
    • TF: TensorFlow
    • PYT: PyTorch
    • SK: scikit-learn
    • uni: univariate time series
    • multi: multivariate time series
    • y: yes (requires training set)
    • n: no (does not require training set)
  3. Identify the goals of Explainability in TSInterpret

    main

    In TSInterpret, Interpretability is the end goal: supporting user understanding of the model's decision-making process. Explainability refers to the specific algorithms used to reach that goal.

    Use explainability algorithms to answer questions such as:

    • How does a prediction change depending on feature inputs?
    • Which features are important (or unimportant) for a specific prediction?
    • What minimal changes to features are required to obtain a different prediction of your choosing?
    • How does each individual feature contribute to the model's prediction?
  4. Understand the taxonomy of explanation methods in TSInterpret

    main

    TSInterpret categorizes explanation methods based on three main criteria to help you choose the right tool for your time series model:

    1. Post-Hoc vs. Instinct

    • Instinct Interpretability: Models that are interpretable by design (e.g., through constrained complexity or built-in explanation components).
    • Post-Hoc Interpretability: Methods applied to a model after it has been trained. These are typically decoupled from the model itself.

    2. Model-Specific vs. Model-Agnostic

    • Model-Specific: Methods limited to specific model classes. These often require access to model internals, such as Gradients.
    • Model-Agnostic: Methods that can be applied to any model by analyzing the relationship between inputs and outputs without accessing internal functions.

    3. Results of Explanation Methods

    Depending on the insight you need, you can use different types of methods:

    • Feature Attribution (FA): Returns a score for each feature indicating its contribution to the model's output.
    • Instance-based (IB): Identifies a subset of relevant features that must be present to maintain or change a prediction.
    • Surrogate Models: Trains a simpler, inherently interpretable model to approximate the complex model's behavior.
  5. Details of specific interpretability algorithms

    main

    TSInterpret implements the following specific algorithms with these characteristics:

    • NUN-CF: Generates counterfactuals using a native guide selected via K-nearest neighbor. It offers three options: the native guide, the native guide with bary centering, and counterfactuals based on the native guide and class activation mapping.
    • COMTE: A heuristic perturbation approach for multivariate time series counterfactuals. It aims to change a small number of features to obtain a counterfactual.
    • LEFTIST: An agnostic local explanation method adapted from LIME. It uses prefixed shapelets (defined by length and position) as interpretable components to provide feature importance.
    • SETS: Generates counterfactuals by perturbing previously extracted shapelets back into the original time series being explained.
    • TSEvo: An evolution-based counterfactual generation method for both univariate and multivariate time series. It uses a multi-objective problem and multiple perturbation methods (Gaussian, frequency, and dataset-based) to account for different time series properties.
    • TSR (Temporal Saliency Rescaling): Calculates importance for each timestep, followed by feature importance using various Saliency Methods (both Back-propagation and perturbation based). The implementation leverages tf-explain, shap, and captum.
  6. Quickstart: Explain and visualize a time series model

    main

    This example demonstrates how to use the TSR (Temporal Saliency Rescaling) interpretability model to explain a TensorFlow-based time series classifier using Integrated Gradients (IG) in time mode.

    Note: The example assumes you have a trained model and a dataset (like BasicMotions from tslearn).

    from TSInterpret.InterpretabilityModels.Saliency.TSR import TSR
    import numpy as np
    import tensorflow as tf
    
    # 1. Setup model and data (Conceptual steps)
    # model_to_explain = tf.keras.models.load_model(PATH_TO_YOUR_CLASSIFICATION_MODEL)
    # train_x, train_y, test_x, test_y = ... (loaded via tslearn)
    
    # 2. Initialize the interpretability model
    # Arguments: model, input_dim_1 (time steps), input_dim_2 (features), method, mode
    int_mod = TSR(model_to_explain, train_x.shape[-2], train_x.shape[-1], method='IG', mode='time')
    
    # 3. Prepare a single sample and its label for explanation
    item = np.array([test_x[0,:,:]])
    label = int(np.argmax(test_y[0]))
    
    # 4. Generate explanation
    # TSR=True enables Temporal Saliency Rescaling
    exp = int_mod.explain(item, labels=label, TSR=True)
    
    # 5. Visualize the results
    %matplotlib inline  
    int_mod.plot(np.array([test_x[0,:,:]]), exp)
  7. Install TSInterpret via pip

    main

    You can install TSInterpret from PyPI or directly from the GitHub repository. TSInterpret requires Python 3.6 or higher.

    From PyPI:

    pip install tsinterpret

    From GitHub (latest development version):

    pip install https://github.com/fzi-forschungszentrum-informatik/TSInterpret.git --upgrade

    From GitHub via SSH:

    pip install git@github.com:fzi-forschungszentrum-informatik/TSInterpret.git --upgrade
  8. Basic usage workflow in TSInterpret

    main

    TSInterpret follows a pattern inspired by scikit-learn, consisting of three distinct steps: Initialize, Explain, and Plot.

    Note that input and output details vary depending on the specific algorithm used. The following example demonstrates the workflow using the NativeGuideCF method.

    1. Import the desired explainer class.
    2. Initialize the explainer by passing the model (or a prediction function), data shapes, training data, and method-specific arguments.
    3. Explain a specific test instance to retrieve the explanation and labels.
    4. Plot the results to visualize the explanation.
    from TSInterpret.InterpretabilityModels.counterfactual.NativeGuideCF import NativeGuideCF
    
    # 1. Initialize
    exp_model = NativeGuideCF(model, shape, (train_x, train_y), backend='PYT', mode='feat', method='dtw_bary_center')
    
    # 2. Explain
    exp, label = exp_model.explain(item, np.argmax(y_target, axis=1))
    
    # 3. Plot
    exp_model.plot(item, np.argmax(y_target, axis=1)[0], exp, label)
  9. How TSEvo counterfactual explanations work

    main

    TSEvo provides counterfactual explanations for uni- and multivariate time series classification. It answers the "what if" question by finding a counterfactual instance $x^{cf}$ that is close to the original instance $x$ but results in a different classification $y eq y^{cf}$.

    Technically, TSEvo optimizes a problem involving:

    • Proximity ($R_{1}$)
    • Sparsity ($R_{2}$)
    • Mutation operators ($R_{3}$)
    • Output distance ($R_{4}$)

    The optimization is performed using an evolutionary algorithm based on NSGA-II with mutation operators specifically adapted for the time series domain.

  10. How Temporal Saliency Rescaling (TSR) works

    main
    Temporal Saliency Rescaling (TSR) is a two-step interpretability approach designed to improve the quality of saliency maps for time series predictors. Traditional saliency methods (like GradCAM or SHAP) often fail in time series due to the dual nature of the time and feature domains. TSR addresses this by first calculating the importance of each time step, followed by the importance of each feature. It is built upon existing saliency methods and is specifically designed for gradient-based models.
  11. Explain and Visualize with NativeGuideCF

    main

    Once NativeGuideCF is instantiated, follow these steps to generate and view explanations:

    1. Prepare the instance: Ensure your input item is in the correct shape and obtain the current predicted label.
    2. Call .explain(): Pass the item and the target class index. It returns the counterfactual instance (exp) and the resulting label (label).
    3. Visualize: Use .plot() or .plot_in_one() to render the comparison between the original instance and the counterfactual.
    # 1. Prepare item and target
    item = test_x[20].reshape(1, 1, -1)
    # Assuming y_target is the softmax output of the model
    target_class = np.argmax(y_target, axis=1)[0]
    
    # 2. Explain
    exp, label = exp_model.explain(item, target_class)
    
    # 3. Visualize
    exp_model.plot_in_one(item, target_class, exp, label)