### Development Installation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/CONTRIBUTING.md Clone the repository and install the project in development mode with extra dependencies. Ensure development occurs on a separate branch. ```bash git clone https://github.com/fzi-forschungszentrum-informatik/TSInterpret.git pip install -e .[dev] ``` -------------------------------- ### Install Latest Development Version from GitHub (HTTPS) Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Install the most recent development version directly from the GitHub repository using HTTPS. ```shell pip install https://github.com/fzi-forschungszentrum-informatik/TSInterpret.git --upgrade ``` -------------------------------- ### Install TSInterpret via PyPI Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Use this command to install the TSInterpret library from the Python Package Index. ```shell pip install tsinterpret ``` -------------------------------- ### Install Latest Development Version from GitHub (SSH) Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Install the most recent development version directly from the GitHub repository using SSH. ```shell pip install git@github.com:fzi-forschungszentrum-informatik/TSInterpret.git --upgrade ``` -------------------------------- ### Install TSInterpret Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/README.md Install the TSInterpret library using pip. For the latest development version, install directly from GitHub. ```shell pip install TSInterpret ``` ```shell pip install https://github.com/fzi-forschungszentrum-informatik/TSInterpret/archive/refs/heads/main.zip ``` -------------------------------- ### Prepare Data for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch.ipynb Selects a specific instance from the test set, reshapes it to the model's expected input format, and converts it to a PyTorch tensor. It then gets the model's prediction probabilities for this instance. ```python model.eval() item=test_x[20].reshape(1,1,-1) shape=item.shape _item= torch.from_numpy(item).float() model.eval() y_target = torch.nn.functional.softmax(model(_item)).detach().numpy() ``` -------------------------------- ### Call the explain method Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch.ipynb Prepare the instance and the predicted label of the instance as parameters for the explain method. Use this to get explanations for a model's prediction. ```python explanations = leftist.explain(np.array(explained_instance),label) ``` -------------------------------- ### Plot explanations Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Plots the original instance and its corresponding explanation. Requires matplotlib to be installed. ```python %matplotlib inline leftist.plot(np.array([explained_instance]).reshape(1,-1,1), np.array([explanations[0]])) ``` -------------------------------- ### Call Explain Method with Torch Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_torch_feat.ipynb Prepare the instance and the predicted label of the instance as parameters for the explain methods. Use this to get a counterfactual explanation. ```python ts = 2 test_y[ts] print(model(torch.from_numpy(test_x[ts][np.newaxis,:]).float())) cf_explanation, label = exp_model.explain(test_x[ts], target = None) ``` -------------------------------- ### ResNet Training Progress Output Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Example output showing the training and validation loss per epoch during the ResNet model training process. ```text Epoch: 1, Train loss: 1.186, Val loss: 1.212 Epoch: 2, Train loss: 1.126, Val loss: 0.892 Epoch: 3, Train loss: 0.814, Val loss: 0.763 Epoch: 4, Train loss: 0.674, Val loss: 0.608 Epoch: 5, Train loss: 0.552, Val loss: 0.423 Epoch: 6, Train loss: 0.348, Val loss: 0.259 Epoch: 7, Train loss: 0.192, Val loss: 0.132 Epoch: 8, Train loss: 0.099, Val loss: 0.072 Epoch: 9, Train loss: 0.021, Val loss: 0.007 Epoch: 10, Train loss: 0.001, Val loss: 0.008 Epoch: 11, Train loss: 0.004, Val loss: 0.009 Epoch: 12, Train loss: 0.001, Val loss: 0.002 Epoch: 13, Train loss: 0.0, Val loss: 0.0 Epoch: 14, Train loss: 0.0, Val loss: 0.0 Epoch: 15, Train loss: 0.0, Val loss: 0.0 Epoch: 16, Train loss: 0.0, Val loss: 0.0 Epoch: 17, Train loss: 0.0, Val loss: 0.001 Epoch: 18, Train loss: 0.0, Val loss: 0.001 Epoch: 19, Train loss: 0.0, Val loss: 0.002 Epoch: 20, Train loss: 0.0, Val loss: 0.003 Epoch: 21, Train loss: 0.0, Val loss: 0.003 Epoch: 22, Train loss: 0.0, Val loss: 0.004 Epoch: 23, Train loss: 0.0, Val loss: 0.004 Epoch: 24, Train loss: 0.0, Val loss: 0.004 Epoch: 25, Train loss: 0.0, Val loss: 0.005 Epoch: 26, Train loss: 0.0, Val loss: 0.005 Epoch: 27, Train loss: 0.0, Val loss: 0.005 Epoch: 28, Train loss: 0.0, Val loss: 0.005 Epoch: 29, Train loss: 0.0, Val loss: 0.005 Epoch: 30, Train loss: 0.0, Val loss: 0.005 Epoch: 31, Train loss: 0.0, Val loss: 0.005 Epoch: 32, Train loss: 0.0, Val loss: 0.004 Epoch: 33, Train loss: 0.0, Val loss: 0.004 Epoch: 34, Train loss: 0.0, Val loss: 0.004 Epoch: 35, Train loss: 0.0, Val loss: 0.004 Epoch: 36, Train loss: 0.0, Val loss: 0.004 Epoch: 37, Train loss: 0.0, Val loss: 0.004 Epoch: 38, Train loss: 0.0, Val loss: 0.004 Epoch: 39, Train loss: 0.0, Val loss: 0.004 Epoch: 40, Train loss: 0.0, Val loss: 0.004 Epoch: 41, Train loss: 0.0, Val loss: 0.003 Epoch: 42, Train loss: 0.0, Val loss: 0.003 Epoch: 43, Train loss: 0.0, Val loss: 0.003 Epoch: 44, Train loss: 0.0, Val loss: 0.003 Epoch: 45, Train loss: 0.0, Val loss: 0.003 Epoch: 46, Train loss: 0.0, Val loss: 0.003 Epoch: 47, Train loss: 0.0, Val loss: 0.003 Epoch: 48, Train loss: 0.0, Val loss: 0.003 Epoch: 49, Train loss: 0.0, Val loss: 0.003 Epoch: 50, Train loss: 0.0, Val loss: 0.003 Epoch: 51, Train loss: 0.0, Val loss: 0.003 Epoch: 52, Train loss: 0.0, Val loss: 0.003 Epoch: 53, Train loss: 0.0, Val loss: 0.002 Epoch: 54, Train loss: 0.0, Val loss: 0.002 Epoch: 55, Train loss: 0.0, Val loss: 0.002 Epoch: 56, Train loss: 0.0, Val loss: 0.002 Epoch: 57, Train loss: 0.0, Val loss: 0.002 Epoch: 58, Train loss: 0.0, Val loss: 0.002 Epoch: 59, Train loss: 0.0, Val loss: 0.002 Epoch: 60, Train loss: 0.0, Val loss: 0.002 Epoch: 61, Train loss: 0.0, Val loss: 0.002 Epoch: 62, Train loss: 0.0, Val loss: 0.002 Epoch: 63, Train loss: 0.0, Val loss: 0.002 Epoch: 64, Train loss: 0.0, Val loss: 0.002 Epoch: 65, Train loss: 0.0, Val loss: 0.002 Epoch: 66, Train loss: 0.0, Val loss: 0.002 Epoch: 67, Train loss: 0.0, Val loss: 0.002 Epoch: 68, Train loss: 0.0, Val loss: 0.002 Epoch: 69, Train loss: 0.0, Val loss: 0.002 Epoch: 70, Train loss: 0.0, Val loss: 0.002 Epoch: 71, Train loss: 0.0, Val loss: 0.002 Epoch: 72, Train loss: 0.0, Val loss: 0.002 Epoch: 73, Train loss: 0.0, Val loss: 0.002 Epoch: 74, Train loss: 0.0, Val loss: 0.002 Epoch: 75, Train loss: 0.0, Val loss: 0.001 Epoch: 76, Train loss: 0.0, Val loss: 0.001 Epoch: 77, Train loss: 0.0, Val loss: 0.001 Epoch: 78, Train loss: 0.0, Val loss: 0.001 Epoch: 79, Train loss: 0.0, Val loss: 0.001 Epoch: 80, Train loss: 0.0, Val loss: 0.001 Epoch: 81, Train loss: 0.0, Val loss: 0.001 Epoch: 82, Train loss: 0.0, Val loss: 0.001 Epoch: 83, Train loss: 0.0, Val loss: 0.001 Epoch: 84, Train loss: 0.0, Val loss: 0.001 Epoch: 85, Train loss: 0.0, Val loss: 0.001 Epoch: 86, Train loss: 0.0, Val loss: 0.001 Epoch: 87, Train loss: 0.0, Val loss: 0.001 Epoch: 88, Train loss: 0.0, Val loss: 0.001 Epoch: 89, Train loss: 0.0, Val loss: 0.001 Epoch: 90, Train loss: 0.0, Val loss: 0.001 Epoch: 91, Train loss: 0.0, Val loss: 0.001 Epoch: 92, Train loss: 0.0, Val loss: 0.001 Epoch: 93, Train loss: 0.0, Val loss: 0.001 Epoch: 94, Train loss: 0.0, Val loss: 0.001 Epoch: 95, Train loss: 0.0, Val loss: 0.001 Epoch: 96, Train loss: 0.0, Val loss: 0.001 Epoch: 97, Train loss: 0.0, Val loss: 0.001 Epoch: 98, Train loss: 0.0, Val loss: 0.001 ``` -------------------------------- ### Import Libraries for LEFTIST Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch _ECG5000.ipynb Imports necessary libraries for data loading, model definition, and preprocessing. Ensure these are installed before running. ```python import pickle import numpy as np import torch from ClassificationModels.CNN_T import ResNetBaseline, UCRDataset from tslearn.datasets import UCR_UEA_datasets import sklearn ``` -------------------------------- ### Initialize NativeGuideCF Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Initialize the NativeGuideCF explainer by providing the model, shape, training data, and specifying backend, mode, and method. Ensure 'model', 'shape', 'train_x', and 'train_y' are defined beforehand. ```python exp_model=NativeGuideCF(model,shape,(train_x,train_y), backend='PYT', mode='feat',method='dtw_bary_center') ``` -------------------------------- ### Instantiate NativeGuideCF Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch.ipynb Initializes the NativeGuideCF explainer for PyTorch models. This method requires the trained model, training data (features and labels), backend type, data mode, and the desired counterfactual method ('NUN_CF'). ```python from TSInterpret.InterpretabilityModels.counterfactual.NativeGuideCF import NativeGuideCF exp_model=NativeGuideCF(model,(train_x,train_y), backend='PYT', mode='feat',method='NUN_CF') ``` -------------------------------- ### Instantiate NativeGuideCF for PyTorch Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch_ECG5000.ipynb Initializes the NativeGuideCF model for PyTorch backend. Specify data, backend, mode, and optimization method. ```python from TSInterpret.InterpretabilityModels.counterfactual.NativeGuideCF import NativeGuideCF exp_model=NativeGuideCF(model,(train_x,train_y), backend='PYT', mode='feat',method="NUN_CF") ``` -------------------------------- ### Explain Instance with NunCF Torch Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch.ipynb Call the explain method on an instance using the prepared instance and predicted label. Requires numpy and the exp_model instance. ```python exp,label=exp_model.explain(item, np.argmax(y_target,axis=1)[0]) ``` -------------------------------- ### Initialize NativeGuideCF Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_tensorflow.ipynb Initializes the NativeGuideCF explainer object from the TSInterpret library. This requires the trained model, training data (features and labels), and specifies the backend ('TF' for TensorFlow) and the explanation method ('NUN_CF'). ```python from TSInterpret.InterpretabilityModels.counterfactual.NativeGuideCF import NativeGuideCF exp_model=NativeGuideCF(model,(train_x,train_y), backend='TF', mode = 'time',method='NUN_CF') ``` -------------------------------- ### Get Counterfactual Label Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch_epi.ipynb Displays the predicted counterfactual label. ```python label ``` -------------------------------- ### Get Predicted Label Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch_epi.ipynb Displays the predicted label obtained from the model inference. ```python y_label ``` -------------------------------- ### Prepare Data for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch epi.ipynb Prepare the item to be explained and its predicted label. The item should be formatted as a numpy array. ```python item = np.array([train_x[1,:,:]]) label =test_preds[1] ``` -------------------------------- ### Explain Instance with NativeGuideCF Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch_ECG5000.ipynb Calls the explain method to generate a counterfactual explanation for a given item and its predicted target label. ```python exp,label=exp_model.explain(item, np.argmax(y_target,axis=1) ) ``` -------------------------------- ### Get Shape of Explanation Array Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Prints the shape of the generated counterfactual explanation array. ```python array.shape ``` -------------------------------- ### Get Shape of Input Item Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Prints the shape of the input data item being explained. ```python item.shape ``` -------------------------------- ### Get Predictions from LSTM Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_torch_LSTM.ipynb Uses the loaded LSTM model to generate predictions on the test dataset. ```python y_pred, ground_truth = get_all_preds(model, test_loader) ``` -------------------------------- ### Initialize and use COMTECF explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_sklearn.ipynb Initializes the COMTECF explainer with the trained model and data, then generates an explanation. ```python from TSInterpret.InterpretabilityModels.counterfactual.COMTECF import COMTECF exp_model= COMTECF(model,(train_x,pred_y),mode='time', backend='SK', method= 'opt') exp = exp_model.explain(item) array, label=exp %matplotlib inline org_label=np.argmax(y_target) cf_label=label[0] exp=array ``` -------------------------------- ### Initialize SETSCF Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_tensorflow.ipynb Initializes the SETSCF explainer with a loaded model and dataset. Configure shapelet length, backend, and mode as needed. ```python exp_model= SETSCF(model, (train_x,train_y), backend='TF', mode='time', min_shapelet_len=3, max_shapelet_len=20, time_contract_in_mins_per_dim=1, #initial_num_shapelets_per_case=10, fit_shapelets = False) ``` -------------------------------- ### Initialize LEFTIST with PyTorch Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch _ECG5000.ipynb Sets up the LEFTIST explainer with a PyTorch model, reference data, and specifies transformation and learning process names. Ensure all required variables like `model`, `train_x`, `test_x` are defined beforehand. ```python explained_instance = train_x[1] nb_interpretable_feature = 10 explanation_size = 2 nb_neighbors = 1000 learning_process_name = 'Lime' transform_name = 'straight_line' model_to_explain=model ``` ```python from TSInterpret.InterpretabilityModels.leftist.leftist import LEFTIST ``` ```python leftist = LEFTIST(model_to_explain,(test_x,None),mode='feat', backend='PYT', \ learning_process_name='Lime',transform_name='straight_line') ``` -------------------------------- ### Get Shape of Counterfactual Population Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_tensorflow.ipynb Prints the shape of the generated counterfactual population, which represents the modified time series instances. ```python np.array(pop).shape ``` -------------------------------- ### Import Libraries and Set Environment Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_tensorflow.ipynb Imports necessary libraries for data manipulation, machine learning, and sets up the environment by disabling GPU usage. It also suppresses warnings for cleaner output. ```python import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import numpy as np from tslearn.datasets import UCR_UEA_datasets import warnings import tensorflow.keras as keras warnings.filterwarnings("ignore") ``` -------------------------------- ### Initialize COMTECF Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Initializes the COMTECF explainer for PyTorch models. Requires the model, training data, backend, mode, and optimization method. ```python %load_ext autoreload %autoreload 2 from TSInterpret.InterpretabilityModels.counterfactual.COMTECF import COMTECF exp_model= COMTECF(model,(train_x,train_y),backend='PYT',mode='feat', method= 'opt') ``` -------------------------------- ### Interpretability Algorithm Steps Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch _ECG5000.ipynb Outlines the four main steps for using an interpretability algorithm: loading the method, instantiation, calling explain, and plotting results. ```python 1. Load the Interpretability Method 2. Instaniate the Method with the desired Parameters 3. Call the explain Method 4. Plot the results ``` -------------------------------- ### Get Unique Test Labels Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch_ECG5000.ipynb Determines and displays the unique class labels present in the test set. This is useful for understanding the distribution of classes in the test data. ```python np.unique(test_y) ``` -------------------------------- ### Prepare Data for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Prepare the input item and its corresponding predicted label for the explanation method. The item is typically a single data sample, and the label is the predicted class index. ```python item = np.array([test_x[0,:,:]]) label = int(np.argmax(test_y[0])) ``` -------------------------------- ### Predict Labels and Get Predictions Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_tensorflow.ipynb Predicts the class labels for the test set using the loaded TensorFlow model and prints the resulting array of predicted labels. ```python label_pred=np.argmax(model.predict(test_x),axis=1) label_pred ``` -------------------------------- ### Prepare Input Item for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_tensorflow.ipynb Selects the first time series from the test set and formats it as a NumPy array with the expected input shape for the explainer. It also determines the true label for this item. ```python item= np.array([test_x[0,:,:]]) label=int(np.argmax(test_y[0])) ``` -------------------------------- ### Plot Counterfactual Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_tensorflow.ipynb Plots the original time series item, its original predicted label, the counterfactual explanation, and its predicted label using the COMTECF model's plotting utility. Requires matplotlib to be installed. ```python %matplotlib inline org_label=np.argmax(y_target) cf_label=label[0] exp=array print(exp.shape) exp_model.plot_in_one(np.array(item[0]),org_label,np.array(exp[0]),cf_label) ``` -------------------------------- ### Import TSInterpret Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Import the NativeGuideCF explainer from the TSInterpret library. This is the first step in using the library for interpretability. ```python from TSInterpret.InterpretabilityModels.counterfactual.NativeGuideCF import NativeGuideCF ``` -------------------------------- ### Initialize TSEvo Counterfactual Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_torch.ipynb Initializes the TSEvo explainer with the trained model, test data, and specifies the explanation mode and backend. ```python from TSInterpret.InterpretabilityModels.counterfactual.TSEvoCF import TSEvo exp =TSEvo(model= model,data=(test_x,np.array(y_pred)), mode = 'feat',backend='PYT',epochs =500) ``` -------------------------------- ### Initialize COMTECF Explainer (PyTorch) Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch_epi.ipynb Initializes the COMTECF explainer for PyTorch models. Specify the model, training data, backend, mode, and optimization method. ```python from TSInterpret.InterpretabilityModels.counterfactual.COMTECF import COMTECF exp_model= COMTECF(model,(train_x,train_y),backend='PYT',mode='feat', method= 'brute') ``` -------------------------------- ### Define explanation parameters Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Sets up parameters required for generating explanations, including the instance to explain, number of features, explanation size, and model parameters. ```python explained_instance = train_x[0] nb_interpretable_feature = 10 explanation_size = 5 nb_neighbors = 1000 learning_process_name = 'Lime' transform_name = 'straight_line' ``` -------------------------------- ### Initialize LEFTIST Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_tensorflow.ipynb Initializes the LEFTIST explainer with the model, test data, and specified parameters for time series explanation. ```python leftist = LEFTIST(model_to_explain,(test_x, test_y),mode='time',backend='TF',transform_name='straight_line',learning_process_name='Lime') ``` -------------------------------- ### Initialize TSEvo Counterfactual Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_torch_Multivariate.ipynb Initializes the TSEvo explainer with the trained model, test data, and desired configuration. The `mode` parameter specifies whether explanations focus on features or time, and `backend` indicates the framework (PyTorch, scikit-learn, or TensorFlow). ```python from TSInterpret.InterpretabilityModels.counterfactual.TSEvoCF import TSEvo exp =TSEvo(model= model,data=(test_x,np.array(y_pred)), mode = 'feat',backend='PYT',epochs =10) ``` -------------------------------- ### Initialize and Use TSR Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate.ipynb Initializes the TSR explainer with the loaded model and dataset parameters, then generates an explanation for the input item. The 'FO' method and 'time' mode are used for interpretation. ```python #TODO SLIDING WINDOW from TSInterpret.InterpretabilityModels.Saliency.TSR import TSR int_mod=TSR(model, train_x.shape[-2],train_x.shape[-1], method='FO', mode='time') print(item.shape) exp= int_mod.explain(item,labels=label,TSR =True) ``` -------------------------------- ### Prepare Input for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate.ipynb Prepares a single time series item from the test set and specifies the true label for explanation. ```python item = np.array([test_x[0,:,:]],dtype=np.float64) label =0 ``` -------------------------------- ### Explain an instance using tsinterpret Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_tensorflow.ipynb Prepare the instance and the predicted label of the instance as parameters for the explain methods. Use `test_x[ts]` as the item to be explained. ```python ts = 5 test_y[ts] cf_explanation, label = exp_model.explain(test_x[ts], target = None) ``` -------------------------------- ### Prepare data for explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_sklearn.ipynb Prepares a single test item and predicts probabilities for it and the training data. ```python item=test_x[10].reshape(1,test_x.shape[1],test_x.shape[2]) shape=item.shape y_target= model.predict_proba(item) pred_y= model.predict_proba(train_x) ``` -------------------------------- ### Load and preprocess dataset Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_sklearn.ipynb Loads the 'BasicMotions' dataset and scales the time series data using TimeSeriesScalerMinMax. ```python dataset='BasicMotions' train_x,train_y, test_x, test_y=UCR_UEA_datasets().load_dataset(dataset) train_x = TimeSeriesScalerMinMax().fit_transform(train_x) test_x = TimeSeriesScalerMinMax().fit_transform(test_x) ``` -------------------------------- ### Initialize LEFTIST explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Initializes the LEFTIST explainer with the trained model, test data, and specifies the mode and backend. ```python model_to_explain = model random_state=0 leftist = LEFTIST(model_to_explain,(test_x,None),mode='time', backend='SK') ``` -------------------------------- ### Train ResNet Model with PyTorch Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Prepares datasets, initializes a ResNet model, and trains it using provided data loaders. Loads the trained model weights from a specified path. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) model = ResNetBaseline(in_channels=6, num_pred_classes=n_pred_classes) fit(model, train_loader, test_loader) model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) ``` -------------------------------- ### Train ResNet Model and Save Weights Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch epi.ipynb Prepares datasets, trains a ResNet model, and saves its state dictionary. Ensure the dataset directory exists before saving. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) model = ResNetBaseline(in_channels=X_train.shape[-1], num_pred_classes=n_pred_classes) #model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) fit(model,train_loader,test_loader) if dataset in os.listdir('../../ClassificationModels/models/'): print('Folder exists') else: os.mkdir(f'../../ClassificationModels/models/{dataset}') torch.save(model.state_dict(), f'../../ClassificationModels/models/{dataset}/ResNet') model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) test_preds, ground_truth = get_all_preds(model, test_loader) model.eval() ``` -------------------------------- ### Initialize LEFTIST Interpretability Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch.ipynb Instantiates the LEFTIST model with the specified parameters, including the model to explain, reference data, operational mode ('feat'), backend ('PYT'), learning process ('Lime'), transformation type ('background'), explanation size, and number of neighbors. ```python leftist = LEFTIST(model_to_explain,(test_x,test_y),mode='feat', backend='PYT', learning_process_name='Lime',transform_name=transform_name, explanation_size=explanation_size,nb_neighbors=1000) ``` -------------------------------- ### Prepare DataLoaders and Load Pretrained Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch.ipynb Creates PyTorch DataLoaders for training and testing datasets, preparing them for batch processing. It then instantiates a ResNetBaseline model and loads pre-trained weights, ready for fine-tuning or evaluation. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) model = ResNetBaseline(in_channels=1, num_pred_classes=n_pred_classes) model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) ``` -------------------------------- ### Loading and Initializing ResNet Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_torch_feat.ipynb Loads a pre-trained ResNet model for classification and prepares the test data loader. Ensure the model path and dataset name are correct. ```python from ClassificationModels.CNN_T import ResNetBaseline, UCRDataset, get_all_preds from ClassificationModels.LSTM_T import LSTM #device = torch.device( "cpu")#"cuda:0" if torch.cuda.is_available() else model = ResNetBaseline(in_channels=train_x.shape[1], num_pred_classes=n_classes) model.load_state_dict(torch.load(f'../../ClassificationModels//models/{dataset}/ResNet')) test_dataset = UCRDataset(test_x,test_y) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=True) ``` -------------------------------- ### Initialize SETSCF Counterfactual Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_torch_time.ipynb Initializes the SETSCF (Shapelet-based Temporal Association Rule Mining for Counterfactual Explanations) explainer. This involves providing the trained model, training data, and configuring parameters like the backend, mode, and shapelet length constraints. ```python %load_ext autoreload %autoreload 2 from TSInterpret.InterpretabilityModels.counterfactual.SETSCF import SETSCF exp_model= SETSCF(model, (train_x,train_y), backend='PYT', mode='time', min_shapelet_len=3, max_shapelet_len=20, time_contract_in_mins_per_dim=1, #initial_num_shapelets_per_case=10, fit_shapelets = False, le=False) ``` -------------------------------- ### Prepare Data for TSR Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate_ResNet.ipynb Prepares a single data item and its label for explanation. Ensure the item is a numpy array with the correct dimensions. ```python item = np.array([test_x[0,:,:]],dtype=np.float64) label =0 ``` -------------------------------- ### Initialize TSEvo Counterfactual Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_torch_LSTM.ipynb Initializes the TSEvo counterfactual explanation method with the trained LSTM model, test data, and specifies the explanation mode and backend. ```python from TSInterpret.InterpretabilityModels.counterfactual.TSEvoCF import TSEvo exp =TSEvo(model= model,data=(test_x,np.array(y_pred)), mode = 'time',backend='PYT',epochs =10) ``` -------------------------------- ### Initialize TSR Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate_ResNet.ipynb Initializes the TSR explainer model. Requires the trained model, input dimensions, and desired explanation method and mode. ```python from TSInterpret.InterpretabilityModels.Saliency.TSR import TSR int_mod=TSR(model, train_x.shape[-1],train_x.shape[-2], method='FO', mode='feat') exp= int_mod.explain(item,labels=label,TSR =True) ``` -------------------------------- ### Generate explanations Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Generates explanations for a given instance using the initialized LEFTIST explainer. ```python explanations = leftist.explain(np.array(explained_instance),1000,explanation_size=explanation_size) ``` -------------------------------- ### Generate Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_tensorflow.ipynb Generates an explanation for a given instance using the initialized LEFTIST explainer. ```python explanations = leftist.explain(np.array(explained_instance)) ``` -------------------------------- ### Explain Test Instance Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/GettingStarted.md Call the explain method on a test instance to obtain an explanation and label. The 'item' and 'y_target' should be pre-defined. ```python exp,label=exp_model.explain(item, np.argmax(y_target,axis=1)) ``` -------------------------------- ### Initialize and Load LSTM Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_torch_LSTM.ipynb Creates an LSTM model, sets up data loaders, and loads pre-trained weights. It checks if the model directory exists and creates it if not. ```python #n_pred_classes =train_y.shape[0] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) device='cpu' hidden_size=10 rnn=0.1 model = LSTM(6, hidden_size ,n_classes,rnndropout=rnn).to(device) #fit(model,train_loader,test_loader) if dataset in os.listdir('../../ClassificationModels/models/'): print('Folder exists') else: os.mkdir(f'../../ClassificationModels/models/{dataset}') #torch.save(model.state_dict(), f'../../ClassificationModels/models/{dataset}/LSTM') model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/LSTM')) model.eval() ``` -------------------------------- ### Initialize TSEvo Explainer Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_tensorflow.ipynb Initializes the TSEvo explainer object from the TSInterpret library. It requires the pre-trained model, test data (features and one-hot encoded labels), backend specification ('TF' for TensorFlow), and training epochs. ```python from TSInterpret.InterpretabilityModels.counterfactual.TSEvoCF import TSEvo exp =TSEvo(model= model,data=(test_x,test_y), backend='TF',mode='time',epochs =100) ``` -------------------------------- ### Prepare Data and Predict Label (PyTorch) Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch_epi.ipynb Prepares input data for a PyTorch model, performs inference, and extracts the predicted label. Ensure the model is in evaluation mode and the input data is correctly formatted as a PyTorch tensor. ```python item=test_x[1].reshape(1,test_x.shape[1],-1) shape=item.shape _item= torch.from_numpy(item).float() model.eval() y_pred = torch.nn.functional.softmax(model(_item)).detach().numpy() y_label= np.argmax(y_pred) ``` -------------------------------- ### Prepare Input Item and Label Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_tensorflow_univariate.ipynb Prepares a single time series instance from the test set for explanation. It reshapes the data to match the model's expected input format and extracts the true label for that instance. ```python item= np.array([test_x[0,:,:]]) label=int(np.argmax(test_y[0])) ``` -------------------------------- ### Prepare PyTorch Model and Data Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Sets the model to evaluation mode and prepares a data item for prediction. Ensure the model and test data are already defined. ```python model.eval() item=test_x[10].reshape(1,test_x.shape[1],-1) shape=item.shape _item= torch.from_numpy(item).float() model.eval() y_pred = torch.nn.functional.softmax(model(_item)).detach().numpy() y_label= np.argmax(y_pred) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_sklearn.ipynb Imports required libraries for dataset loading, model training, and preprocessing. ```python import numpy as np from tslearn.datasets import UCR_UEA_datasets from tslearn.svm import TimeSeriesSVC from tslearn.preprocessing import TimeSeriesScalerMinMax ``` -------------------------------- ### Initialize TSR Interpretability Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch epi.ipynb Instantiate the TSR model for interpretability. Requires the model, dimensions (NumTimeStep, NumFeatures), the desired saliency method, and the mode ('time' or 'feat'). ```python from TSInterpret.InterpretabilityModels.Saliency.TSR import TSR int_mod=TSR(model, train_x.shape[-1],train_x.shape[-2], method='GS', mode='feat') ``` -------------------------------- ### Print Explanation and Input Shapes Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate.ipynb Prints the shape of the generated explanation and the input item to verify consistency. This is useful for debugging. ```python print(exp.shape) print(np.array([test_x[0,:,:]]).shape) ``` -------------------------------- ### Load and fit SVM model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Loads a pre-trained SVM model from a pickle file and fits it to the training data. Ensure the model path is correct. ```python model= pickle.load(open(f'../../ClassificationModels/models/GunPoint/GunPoint_SVM.sav','rb')).fit(train_x,train_y) ``` -------------------------------- ### Load Pre-trained ResNet Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/NunCF_torch.ipynb Initializes a ResNetBaseline model, creates PyTorch DataLoaders for training and testing, and loads a pre-trained state dictionary for the model. Ensure the model path is correct. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) model = ResNetBaseline(in_channels=1, num_pred_classes=n_pred_classes) state_dict= torch.load(f'../../ClassificationModels/models/{dataset}/ResNet') model.load_state_dict(state_dict) ``` -------------------------------- ### Initialize COMTECF Explainer Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_tensorflow.ipynb Initializes the COMTECF (Counterfactual Explanations for Time Series) model from TSInterpret. This requires the trained model, training data, and specifies the mode, backend, and method for explanation. ```python from TSInterpret.InterpretabilityModels.counterfactual.COMTECF import COMTECF exp_model= COMTECF(model,(train_x,train_y),mode='time', backend='TF', method= 'brute') ``` -------------------------------- ### Set Parameters for LEFTIST Initialization Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch.ipynb Defines parameters required for initializing the LEFTIST interpretability model. This includes setting the model to evaluation mode, selecting an instance to explain, and specifying parameters like the number of interpretable features, explanation size, and the learning process/transformation names. ```python model.eval() explained_instance = train_x[0] label=train_y[0] nb_interpretable_feature = 10 explanation_size = 1 nb_neighbors = 1000 learning_process_name = 'Lime' transform_name = 'background' model_to_explain=model ``` -------------------------------- ### Plot Explanation Results (Sample) Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Visualize the explanation results for a given item. This function plots the saliency on a sample, optionally with a specified figure size. Ensure the input item and explanation are provided. ```python int_mod.plot(np.array([test_x[0,:,:]]),exp,figsize=(15,15)) ``` -------------------------------- ### Call Explain Method Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch epi.ipynb Call the explain method on the instantiated TSR model with the prepared item and label. TSR parameter controls temporal rescaling. ```python exp=int_mod.explain(item,labels=label,TSR =False) ``` -------------------------------- ### Prepare PyTorch DataLoaders for ResNet Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Creates PyTorch Datasets and DataLoaders for training and testing a ResNet model. It specifies the batch size and shuffling for the training loader, and the batch size for the testing loader. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) ``` -------------------------------- ### Visualize the explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_torch.ipynb Visualize the explanation by calling the plot method. Pass the original instance and the explanation as parameters. This is useful for understanding the model's decision process. ```python leftist.plot(np.array([explained_instance]),np.array([explanations[0]])) ``` -------------------------------- ### Load Dataset and Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_tensorflow.ipynb Loads a dataset from UCR_UEA_datasets and a pre-trained Keras model. Be aware of potential warnings during model loading. ```python data = UCR_UEA_datasets().load_dataset("BasicMotions") model = keras.models.load_model("../../ClassificationModels/models/BasicMotions/best_model_fcn_wang_ep200.hdf5") train_x,train_y,test_x,test_y = data ``` -------------------------------- ### Prepare DataLoaders and Initialize LSTM Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch_LSTM.ipynb Prepares PyTorch DataLoaders for training and testing, initializes an LSTM model with specified hidden size and dropout, and loads pre-trained weights if available. ```python n_pred_classes =train_y.shape[1] train_dataset = UCRDataset(train_x.astype(np.float64),train_y.astype(np.int64)) test_dataset = UCRDataset(test_x.astype(np.float64),test_y.astype(np.int64)) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=1,shuffle=False) device='cpu' hidden_size=10 rnn=0.1 model = LSTM(6, hidden_size ,n_pred_classes,rnndropout=rnn).to(device) #fit(model,train_loader,test_loader) if dataset in os.listdir('../../ClassificationModels/models/'): print('Folder exists') else: os.mkdir(f'../../ClassificationModels/models/{dataset}') #torch.save(model.state_dict(), f'../../ClassificationModels/models/{dataset}/LSTM') model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/LSTM')) model.eval() test_preds, ground_truth = get_all_preds(model, test_loader) ground_truth=np.argmax(ground_truth,axis=1) sns.set(rc={'figure.figsize':(5,4)}) heatmap=confusion_matrix(ground_truth, test_preds) sns.heatmap(heatmap, annot=True) plt.savefig(f'../../ClassificationModels/models/{dataset}/LSTM_confusion_matrix.png') plt.close() acc= accuracy_score(ground_truth, test_preds) a = classification_report(ground_truth, test_preds, output_dict=True) dataframe = pd.DataFrame.from_dict(a) dataframe.to_csv(f'../../ClassificationModels/models/{dataset}/LSTMclassification_report.csv', index = False) ``` -------------------------------- ### Select Observation and Label for Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSEvo_tensorflow.ipynb Selects the first observation and its corresponding label from the test set for subsequent interpretability analysis. Prints their shapes. ```python observation_01= X_test[0] label_01 =test_y[0] print(observation_01.shape) print(label_01.shape) ``` -------------------------------- ### Initialize TSR Model in PyTorch Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Instantiate the TSR model for PyTorch. Ensure the model is in evaluation mode and import the necessary class. This snippet sets up the interpretability model with specified parameters like the number of time steps, features, method, and mode. ```python model.eval() from TSInterpret.InterpretabilityModels.Saliency.TSR import TSR int_mod=TSR(model, train_x.shape[-1],train_x.shape[-2], method='GRAD', mode='feat') ``` -------------------------------- ### Generate and Plot Saliency Explanations Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch_LSTM.ipynb Generates saliency explanations for a given test item using the initialized interpretation model and plots these explanations in 'time' mode. ```python exp=int_mod.explain(np.array([test_x[0,:,:]]),labels =1 ,TSR = True) int_mod.plot(np.array([test_x[0,:,:]]),exp) ``` -------------------------------- ### Plot Explanation Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_tensorflow.ipynb Plots the explanation for the given instance. Requires the instance and the explanation data. ```python leftist.plot(np.array([explained_instance]), np.array([explanations[1]])) ``` -------------------------------- ### List Available Multivariate Datasets Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch epi.ipynb Uses the tslearn library to list all available multivariate datasets from the UCR/UEA repository. This helps in selecting a dataset for loading. ```python UCR_UEA_datasets().list_multivariate_datasets() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Leftist_sklearn.ipynb Imports the required libraries for data loading, manipulation, and model training. ```python import pickle import numpy as np from tslearn.datasets import UCR_UEA_datasets ``` -------------------------------- ### Load UCR/UEA Dataset and Preprocess Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Sets_torch_time.ipynb Loads a specified dataset from the UCR/UEA archive using tslearn and performs basic preprocessing. It reshapes the data and determines the number of classes. ```python import sklearn dataset='BasicMotions' X_train,train_y,X_test,test_y=UCR_UEA_datasets().load_dataset(dataset) #train_x=np.swapaxes(X_train,1,2) #test_x=np.swapaxes(X_test,1,2) train_x=X_train test_x=X_test #enc1=sklearn.preprocessing.OneHotEncoder(sparse=False).fit(train_y.reshape(-1, 1))#pickle.load(open(f'../../ClassificationModels/models/{dataset}/OneHotEncoder.pkl','rb')) #test_y=enc1.transform(test_y.reshape(-1,1)) #train_y=enc1.transform(train_y.reshape(-1,1)) n_classes = len(np.unique(test_y)) ``` -------------------------------- ### Call TSR Explain Method Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_torch.ipynb Call the explain method of the initialized TSR model. Pass the prepared item, its label, and specify whether to use Temporal Rescaling (TSR). The attribution parameter can also be set. ```python exp=int_mod.explain(item,labels=label,TSR = True, attribution=0.0) ``` -------------------------------- ### Load Pre-trained ResNet Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_Univariate_ResNet.ipynb Initializes a ResNetBaseline model and loads its pre-trained weights from a specified file path. The model is then set to evaluation mode. ```python model =ResNetBaseline(in_channels=1, num_pred_classes=n_pred_classes) model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) model.eval() ``` -------------------------------- ### Explain Input Item with COMTECF Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_tensorflow.ipynb Generates counterfactual explanations for the prepared input item using the initialized COMTECF model. ```python exp = exp_model.explain(item) ``` -------------------------------- ### Plot Explanation with Heatmap Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/TSR_tensorflow.ipynb Visualizes the explanation with an overlaid heatmap. This provides a more detailed view of the important time steps contributing to the model's prediction for the given time series. ```python %matplotlib inline int_mod.plot(np.array([test_x[0,:,:]]),exp, heatmap = True) ``` -------------------------------- ### Load Pre-trained ResNet Model Source: https://github.com/fzi-forschungszentrum-informatik/tsinterpret/blob/main/docs/Notebooks/Ates_torch.ipynb Initializes a ResNetBaseline model with the appropriate input channels and number of prediction classes, then loads the pre-trained weights from a saved state dictionary. ```python model = ResNetBaseline(in_channels= X_train.shape[-1], num_pred_classes=n_pred_classes) #fit(model, train_loader,test_loader) model.load_state_dict(torch.load(f'../../ClassificationModels/models/{dataset}/ResNet')) ```