Package: quantus
A toolkit to evaluate neural network explanationsPyTorch and TensorFlowQuantus is currently under active development so carefully note the Quantus release version to ensure reproducibility of your work.📑 Shortcut to paper!News and Highlights! :rocket:New metrics added:EfficientMPRTandSmoothMPRTbyHedström et al., (2023)Released a new versionhereAccepted to Journal of Machine Learning Research (MLOSS), read thepaperOffers more than30+ metrics in 6 categoriesfor XAI evaluationSupports different data types (image, time-series, tabular, NLP next up!) and models (PyTorch, TensorFlow)Extended built-in support for explanation methods (captum,tf-explainandzennit)CitationIf you find this toolkit or its companion paperQuantus: An Explainable AI Toolkit for Responsible Evaluation of Neural Network Explanations and Beyondinteresting or useful in your research, use the following Bibtex annotation to cite us:@article{hedstrom2023quantus,author={Anna Hedstr{\"{o}}m and Leander Weber and Daniel Krakowczyk and Dilyara Bareeva and Franz Motzkus and Wojciech Samek and Sebastian Lapuschkin and Marina Marina M.{-}C. H{\"{o}}hne},title={Quantus: An Explainable AI Toolkit for Responsible Evaluation of Neural Network Explanations and Beyond},journal={Journal of Machine Learning Research},year={2023},volume={24},number={34},pages={1--11},url={http://jmlr.org/papers/v24/22-0142.html}}When applying the individual metrics of Quantus, please make sure to also properly cite the work of the original authors (as linked below).Table of contentsLibrary overviewInstallationGetting startedTutorialsContributingLibrary overviewA simple visual comparison of eXplainable Artificial Intelligence (XAI) methods is often not sufficient to decide which explanation method works best as shown exemplarily in Figure a) for four gradient-based methods — Saliency (Mørch et al., 1995;Baehrens et al., 2010), Integrated Gradients (Sundararajan et al., 2017), GradientShap (Lundberg and Lee, 2017) or FusionGrad (Bykov et al., 2021), yet it is a common practice for evaluation XAI methods in absence of ground truth data. Therefore, we developed Quantus, an easy-to-use yet comprehensive toolbox for quantitative evaluation of explanations — including 30+ different metrics.With Quantus, we can obtain richer insights on how the methods compare e.g., b) by holistic quantification on several evaluation criteria and c) by providing sensitivity analysis of how a single parameter e.g. the pixel replacement strategy of a faithfulness test influences the ranking of the XAI methods.MetricsThis project started with the goal of collecting existing evaluation metrics that have been introduced in the context of XAI research — to help automate the task ofXAI quantification. Along the way of implementation, it became clear that XAI metrics most often belong to one out of six categories i.e., 1) faithfulness, 2) robustness, 3) localisation 4) complexity 5) randomisation or 6) axiomatic metrics. The library contains implementations of the following evaluation metrics:Faithfulnessquantifies to what extent explanations follow the predictive behaviour of the model (asserting that more important features play a larger role in model outcomes)Faithfulness Correlation(Bhatt et al., 2020): iteratively replaces a random subset of given attributions with a baseline value and then measuring the correlation between the sum of this attribution subset and the difference in function outputFaithfulness Estimate(Alvarez-Melis et al., 2018): computes the correlation between probability drops and attribution scores on various pointsMonotonicity Metric(Arya et al. 2019): starts from a reference baseline to then incrementally replace each feature in a sorted attribution vector, measuring the effect on model performanceMonotonicity Metric(Nguyen et al, 2020): measures the spearman rank correlation between the absolute values of the attribution and the uncertainty in the probability estimationPixel Flipping(Bach et al., 2015): captures the impact of perturbing pixels in descending order according to the attributed value on the classification scoreRegion Perturbation(Samek et al., 2015): is an extension of Pixel-Flipping to flip an area rather than a single pixelSelectivity(Montavon et al., 2018): measures how quickly an evaluated prediction function starts to drop when removing features with the highest attributed valuesSensitivityN(Ancona et al., 2019): computes the correlation between the sum of the attributions and the variation in the target output while varying the fraction of the total number of features, averaged over several test samplesIROF(Rieger at el., 2020): computes the area over the curve per class for sorted mean importances of feature segments (superpixels) as they are iteratively removed (and prediction scores are collected), averaged over several test samplesInfidelity(Chih-Kuan, Yeh, et al., 2019): represents the expected mean square error between 1) a dot product of an attribution and input perturbation and 2) difference in model output after significant perturbationROAD(Rong, Leemann, et al., 2022): measures the accuracy of the model on the test set in an iterative process of removing k most important pixels, at each step k most relevant pixels (MoRF order) are replaced with noisy linear imputationsSufficiency(Dasgupta et al., 2022): measures the extent to which similar explanations have the same prediction labelRobustnessmeasures to what extent explanations are stable when subject to slight perturbations of the input, assuming that model output approximately stayed the sameLocal Lipschitz Estimate(Alvarez-Melis et al., 2018): tests the consistency in the explanation between adjacent examplesMax-Sensitivity(Yeh et al., 2019): measures the maximum sensitivity of an explanation using a Monte Carlo sampling-based approximationAvg-Sensitivity(Yeh et al., 2019): measures the average sensitivity of an explanation using a Monte Carlo sampling-based approximationContinuity(Montavon et al., 2018): captures the strongest variation in explanation of an input and its perturbed versionConsistency(Dasgupta et al., 2022): measures the probability that the inputs with the same explanation have the same prediction labelRelative Input Stability (RIS)(Agarwal, et. al., 2022): measures the relative distance between explanations e_x and e_x' with respect to the distance between the two inputs x and x'Relative Representation Stability (RRS)(Agarwal, et. al., 2022): measures the relative distance between explanations e_x and e_x' with respect to the distance between internal models representations L_x and L_x' for x and x' respectivelyRelative Output Stability (ROS)(Agarwal, et. al., 2022): measures the relative distance between explanations e_x and e_x' with respect to the distance between output logits h(x) and h(x') for x and x' respectivelyLocalisationtests if the explainable evidence is centred around a region of interest (RoI) which may be defined around an object by a bounding box, a segmentation mask or, a cell within a gridPointing Game(Zhang et al., 2018): checks whether attribution with the highest score is located within the targeted objectAttribution Localization(Kohlbrenner et al., 2020): measures the ratio of positive attributions within the targeted object towards the total positive attributionsTop-K Intersection(Theiner et al., 2021): computes the intersection between a ground truth mask and the binarized explanation at the top k feature locationsRelevance Rank Accuracy(Arras et al., 2021): measures the ratio of highly attributed pixels within a ground-truth mask towards the size of the ground truth maskRelevance Mass Accuracy(Arras et al., 2021): measures the ratio of positively attributed attributions inside the ground-truth mask towards the overall positive attributionsAUC(Fawcett et al., 2006): compares the ranking between attributions and a given ground-truth maskFocus(Arias et al., 2022): quantifies the precision of the explanation by creating mosaics of data instances from different classesComplexitycaptures to what extent explanations are concise i.e., that few features are used to explain a model predictionSparseness(Chalasani et al., 2020): uses the Gini Index for measuring, if only highly attributed features are truly predictive of the model outputComplexity(Bhatt et al., 2020): computes the entropy of the fractional contribution of all features to the total magnitude of the attribution individuallyEffective Complexity(Nguyen at el., 2020): measures how many attributions in absolute values are exceeding a certain thresholdRandomisationtests to what extent explanations deteriorate as inputs to the evaluation problem e.g., model parameters are increasingly randomisedMPRT (Model Parameter Randomisation Test)(Adebayo et. al., 2018): randomises the parameters of single model layers in a cascading or independent way and measures the distance of the respective explanation to the original explanationSmooth MPRT(Hedström et. al., 2023): adds a "denoising" preprocessing step to the original MPRT, where the explanations are averaged over N noisy samples before the similarity between the original- and fully random model's explanations is measuredEfficient MPRT(Hedström et. al., 2023): reinterprets MPRT by evaluating the rise in explanation complexity (discrete entropy) before and after full model randomisation, asking for increased explanation complexity post-randomisationRandom Logit Test(Sixt et al., 2020): computes for the distance between the original explanation and the explanation for a random other classAxiomaticassesses if explanations fulfil certain axiomatic propertiesCompleteness(Sundararajan et al., 2017): evaluates whether the sum of attributions is equal to the difference between the function values at the input x and baseline x' (and referred to as Summation to Delta (Shrikumar et al., 2017), Sensitivity-n (slight variation, Ancona et al., 2018) and Conservation (Montavon et al., 2018))Non-Sensitivity(Nguyen at el., 2020): measures whether the total attribution is proportional to the explainable evidence at the model outputInput Invariance(Kindermans et al., 2017): adds a shift to input, asking that attributions should not change in response (assuming the model does not)Additional metrics will be included in future releases. Pleaseopen an issueif you have a metric you believe should be apart of Quantus.Disclaimers.It is worth noting that the implementations of the metrics in this library have not been verified by the original authors. Thus any metric implementation in this library may differ from the original authors. Further, bear in mind that evaluation metrics for XAI methods are often empirical interpretations (or translations) of qualities that some researcher(s) claimed were important for explanations to fulfil, so it may be a discrepancy between what the author claims to measure by the proposed metric and what is actually measured e.g., using entropy as an operationalisation of explanation complexity. Please read theuser guidelinesfor further guidance on how to best use the library.InstallationIf you already havePyTorchorTensorFlowinstalled on your machine,
the most light-weight version of Quantus can be obtained fromPyPIas follows (no additional explainability functionality or deep learning framework will be included):pip install quantusAlternatively, you can simply add the desired deep learning framework (in brackets) to have the package installed together with Quantus.
To install Quantus with PyTorch, please run:pip install "quantus[torch]"For TensorFlow, please run:pip install "quantus[tensorflow]"Package requirementsThe package requirements are as follows:python>=3.7.0
torch>=1.11.0
tensorflow>=2.5.0Please note that the exactPyTorchand/ orTensorFlowversions
to be installed depends on your Python version (3.7-3.11) and platform (darwin,linux, …).
See[project.optional-dependencies]section in thepyproject.tomlfile.Getting startedThe following will give a short introduction to how to get started with Quantus. Note that this example is based on thePyTorchframework, but we also supportTensorFlow, which would differ only in the loading of the model, data and explanations. To get started with Quantus, you need:A model (model), inputs (x_batch) and labels (y_batch)Some explanations you want to evaluate (a_batch)Step 1. Load data and modelLet's first load the data and model. In this example, a pre-trained LeNet available from Quantus
for the purpose of this tutorial is loaded, but generally, you might use any Pytorch (or TensorFlow) model instead. To follow this example, one needs to have quantus and torch installed, by e.g.,pip install 'quantus[torch]'.importquantusfromquantus.helpers.model.modelsimportLeNetimporttorchimporttorchvisionfromtorchvisionimporttransforms# Enable GPU.device=torch.device("cuda:0"iftorch.cuda.is_available()else"cpu")# Load a pre-trained LeNet classification model (architecture at quantus/helpers/models).model=LeNet()ifdevice.type=="cpu":model.load_state_dict(torch.load("tests/assets/mnist",map_location=torch.device('cpu')))else:model.load_state_dict(torch.load("tests/assets/mnist"))# Load datasets and make loaders.test_set=torchvision.datasets.MNIST(root='./sample_data',download=True,transform=transforms.Compose([transforms.ToTensor()]))test_loader=torch.utils.data.DataLoader(test_set,batch_size=24)# Load a batch of inputs and outputs to use for XAI evaluation.x_batch,y_batch=iter(test_loader).next()x_batch,y_batch=x_batch.cpu().numpy(),y_batch.cpu().numpy()Step 2. Load explanationsWe still need some explanations to evaluate.
For this, there are two possibilities in Quantus. You can provide either:a set of re-computed attributions (np.ndarray)any arbitrary explanation function (callable), e.g., the built-in methodquantus.explainor your own customised functionWe show the different options below.Using pre-computed explanationsQuantus allows you to evaluate explanations that you have pre-computed,
assuming that they match the data you provide inx_batch. Let's say you have explanations
forSaliencyandIntegrated Gradientsalready pre-computed.In that case, you can simply load these into corresponding variablesa_batch_saliencyanda_batch_intgrad:a_batch_saliency=load("path/to/precomputed/saliency/explanations")a_batch_intgrad=load("path/to/precomputed/intgrad/explanations")Another option is to simply obtain the attributions using one of many XAI frameworks out there,
such asCaptum,Zennit,tf.explain,
oriNNvestigate. The following code example shows how to obtain explanations (SaliencyandIntegrated Gradients, to be specific)
usingCaptum:importcaptumfromcaptum.attrimportSaliency,IntegratedGradients# Generate Integrated Gradients attributions of the first batch of the test set.a_batch_saliency=Saliency(model).attribute(inputs=x_batch,target=y_batch,abs=True).sum(axis=1).cpu().numpy()a_batch_intgrad=IntegratedGradients(model).attribute(inputs=x_batch,target=y_batch,baselines=torch.zeros_like(x_batch)).sum(axis=1).cpu().numpy()# Save x_batch and y_batch as numpy arrays that will be used to call metric instances.x_batch,y_batch=x_batch.cpu().numpy(),y_batch.cpu().numpy()# Quick assert.assert[isinstance(obj,np.ndarray)forobjin[x_batch,y_batch,a_batch_saliency,a_batch_intgrad]]Passing an explanation functionIf you don't have a pre-computed set of explanations but rather want to pass an arbitrary explanation function
that you wish to evaluate with Quantus, this option exists.For this, you can for example rely on the built-inquantus.explainfunction to get started, which includes some popular explanation methods
(please runquantus.available_methods()to see which ones).  Examples of how to usequantus.explainor your own customised explanation function are included in the next section.As seen in the above image, the qualitative aspects of explanations
may look fairly uninterpretable --- since we lack ground truth of what the explanations
should be looking like, it is hard to draw conclusions about the explainable evidence. To gather quantitative evidence for the quality of the different explanation methods, we can apply Quantus.Step 3. Evaluate with QuantusQuantus implements XAI evaluation metrics from different categories,
e.g., Faithfulness, Localisation and Robustness etc which all inherit from the basequantus.Metricclass.
To apply a metric to your setting (e.g.,Max-Sensitivity)
it first needs to be instantiated:metric=quantus.MaxSensitivity(nr_samples=10,lower_bound=0.2,norm_numerator=quantus.fro_norm,norm_denominator=quantus.fro_norm,perturb_func=quantus.uniform_noise,similarity_func=quantus.difference,abs=True,normalise=True)and then applied to your model, data, and (pre-computed) explanations:scores=metric(model=model,x_batch=x_batch,y_batch=y_batch,a_batch=a_batch_saliency,device=device,explain_func=quantus.explain,explain_func_kwargs={"method":"Saliency"},)Use quantus.explainSince a re-computation of the explanations is necessary for robustness evaluation, in this example, we also pass an explanation function (explain_func) to the metric call. Here, we rely on the built-inquantus.explainfunction to recompute the explanations. The hyperparameters are set with theexplain_func_kwargsdictionary. Please find more details on how to usequantus.explainatAPI documentation.Employ customised functionsYou can alternatively use your own customised explanation function
(assuming it returns annp.ndarrayin a shape that matches the inputx_batch). This is done as follows:defyour_own_callable(model,models,targets,**kwargs)->np.ndarray"""Logic goes here to compute the attributions and return anexplanation  in the same shape as x_batch (np.array),(flatten channels if necessary)."""returnexplanation(model,x_batch,y_batch)scores=metric(model=model,x_batch=x_batch,y_batch=y_batch,device=device,explain_func=your_own_callable)Run large-scale evaluationQuantus also provides high-level functionality to support large-scale evaluations,
e.g., multiple XAI methods, multifaceted evaluation through several metrics, or a combination thereof. To utilisequantus.evaluate(), you simply need to define two things:TheMetricsyou would like to use for evaluation (each__init__parameter configuration counts as its own metric):metrics={"max-sensitivity-10":quantus.MaxSensitivity(nr_samples=10),"max-sensitivity-20":quantus.MaxSensitivity(nr_samples=20),"region-perturbation":quantus.RegionPerturbation(),}TheXAI methodsyou would like to evaluate, e.g., adictwith pre-computed attributions:xai_methods={"Saliency":a_batch_saliency,"IntegratedGradients":a_batch_intgrad}You can then simply run a large-scale evaluation as follows (this aggregates the result bynp.meanaveraging):importnumpyasnpresults=quantus.evaluate(metrics=metrics,xai_methods=xai_methods,agg_func=np.mean,model=model,x_batch=x_batch,y_batch=y_batch,**{"softmax":False,})Please seeGetting started tutorialto run code similar to this example. For more information on how to customise metrics and extend Quantus' functionality, please seeGetting started guide.TutorialsFurther tutorials are available that showcase the many types of analysis that can be done using Quantus.
For this purpose, please see notebooks in thetutorialsfolder which includes examples such as:All Metrics ImageNet Example: shows how to instantiate the different metrics for ImageNet datasetMetric Parameterisation Analysis: explores how sensitive a metric could be to its hyperparametersRobustness Analysis Model Training: measures robustness of explanations as model accuracy increasesFull Quantification with Quantus: example of benchmarking explanation methodsTabular Data Example: example of how to use Quantus with tabular dataQuantus and TensorFlow Data Example: showcases how to use Quantus with TensorFlow... and more.ContributingWe welcome any sort of contribution to Quantus! For a detailed contribution guide, please refer toContributingdocumentation first.If you have any developer-related questions, pleaseopen an issueor write us athedstroem.anna@gmail.com.