Package: calibrated-explanations
Calibrated Explanations (Documentation)calibrated-explanationsis a Python package for the local feature importance explanation method called Calibrated Explanations, supporting both classification and regression.
The proposed method is based on Venn-Abers (classification & regression) and Conformal Predictive Systems (regression) and has the following characteristics:Fast, reliable, stable and robust feature importance explanations.Calibration of the underlying model to ensure that predictions reflect reality.Uncertainty quantification of the prediction from the underlying model and the feature importance weights.Rules with straightforward interpretation in relation to the feature weights.Possibility to generate counterfactual rules with uncertainty quantification of the expected predictions.Conjunctional rules conveying joint contribution between features.Below is an example of a probabilistic counterfactual explanation for an instance of the California Housing dataset (with the threshold 180 000). The light red area in the background is representing the calibrated probability interval (for the prediction being below the threshold) of the underlying model, as indicated by a Conformal Predictive System and calibrated through Venn-Abers. The darker red bars for each rule show the probability intervals that Venn-Abers indicate for an instance changing a feature value in accordance with the rule condition.Getting startedThenotebooks foldercontains a number of notebooks illustrating different use cases forcalibrated-explanations. The following are commented and should be a good start:quickstart- similar to this Getting Started, including plots.quickstart_wrap- similar to this Getting Started, but with a wrapper class for easier use.demo_binary_classificationdemo_regressiondemo_probabilistic_regressionClassificationLet us illustrate how we may usecalibrated-explanationsto generate explanations from a classifier trained on a dataset fromwww.openml.org, which we first split into a
training and a test set usingtrain_test_splitfromsklearn, and then further split the
training set into a proper training set and a calibration set:fromsklearn.datasetsimportfetch_openmlfromsklearn.model_selectionimporttrain_test_splitdataset=fetch_openml(name="wine",version=7,as_frame=True)X=dataset.data.values.astype(float)y=(dataset.target.values=='True').astype(int)feature_names=dataset.feature_namesX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=2,stratify=y)X_prop_train,X_cal,y_prop_train,y_cal=train_test_split(X_train,y_train,test_size=0.25)We now fit a model on our data.fromsklearn.ensembleimportRandomForestClassifierrf=RandomForestClassifier(n_jobs=-1)rf.fit(X_prop_train,y_prop_train)Factual ExplanationsLets extract explanations for our test set using thecalibrated-explanationspackage by importingCalibratedExplainerfromcalibrated_explanations.fromcalibrated_explanationsimportCalibratedExplainer,__version__print(__version__)explainer=CalibratedExplainer(rf,X_cal,y_cal,feature_names=feature_names)factual_explanations=explainer.explain_factual(X_test)Once we have the explanations, we can plot all of them usingplot_all. Default, a regular plot, without uncertainty intervals included, is created. To include uncertainty intervals, change the parameteruncertainty=True. To plot only a single instance, theplot_explanationfunction can be called, submitting the index of the test instance to plot. You can also add and remove conjunctive rules.factual_explanations.plot_all()factual_explanations.plot_all(uncertainty=True)factual_explanations.plot_explanation(0,uncertainty=True)factual_explanations.add_conjunctions().plot_all()factual_explanations.remove_conjunctions().plot_all()Counterfactual ExplanationsAn alternative to factual rules is to extract counterfactual rules.explain_counterfactualcan be called to get counterfactual rules with an appropriate discretizer automatically assigned.counterfactual_explanations=explainer.explain_counterfactual(X_test)Counterfactuals are also visualized using theplot_all. Plotting an individual counterfactual explanation is done usingplot_explanation, submitting the index of the test instance to plot. Adding or removing conjunctions is done as before.counterfactual_explanations.plot_all()counterfactual_explanations.plot_explanation(0)counterfactual_explanations.add_conjunctions().plot_all()Individual explanations can also be plotted usingplot_explanation.factual_explanations.get_explanation(0).plot_explanation()counterfactual_explanations.get_explanation(0).plot_explanation()Support for multiclasscalibrated-explanationssupports multiclass which is demonstrated indemo_multiclass. That notebook also demonstrates how both feature names and target and categorical labels can be added to improve the interpretability.RegressionExtracting explanations for regression is very similar to how it is done for classification.dataset=fetch_openml(name="house_sales",version=3)X=dataset.data.values.astype(float)y=dataset.target.valuesX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1)X_prop_train,X_cal,y_prop_train,y_cal=train_test_split(X_train,y_train,test_size=0.25)Let us now fit aRandomForestRegressorfromsklearnto the proper training
set:fromsklearn.ensembleimportRandomForestRegressorrf=RandomForestRegressor()rf.fit(X_prop_train,y_prop_train)Factual ExplanationsDefine aCalibratedExplainerobject using the new model and data. Themodeparameter must be explicitly set to regression. Regular and uncertainty plots work in the same way as for classification.explainer=CalibratedExplainer(rf,X_cal,y_cal,mode='regression')factual_explanations=explainer.explain_factual(X_test)factual_explanations.plot_all()factual_explanations.plot_all(uncertainty=True)factual_explanations.add_conjunctions().plot_all()Default, the confidence interval is set to a symmetric interval of 90% (defined aslow_high_percentiles=(5,95)). The intervals can cover any user specified interval, including one-sided intervals. To define a one-sided upper-bounded 90% interval, setlow_high_percentiles=(-np.inf,90), and to define a one-sided lower-bounded 95% interval, setlow_high_percentiles=(5,np.inf). Percentiles can also be set to any other values in the range (0,100) (exclusive), and intervals do not have to be symmetric.lower_bounded_explanations=explainer.explain_factual(X_test,low_high_percentiles=(5,np.inf))asymmetric_explanations=explainer.explain_factual(X_test,low_high_percentiles=(5,75))Counterfactual ExplanationsTheexplain_counterfactualwill work exactly the same as for classification. Counterfactual plots work in the same way as for classification.counterfactual_explanations=explainer.explain_counterfactual(X_test)counterfactual_explanations.plot_all()counterfactual_explanations.add_conjunctions().plot_all()counterfactual_explanations.plot_explanation(0)The parameterlow_high_percentilesworks in the same way as for factual explanations.Probabilistic Regression ExplanationsIt is possible to create probabilistic explanations for regression, providing the probability that the target value is below the provided threshold (which is 180 000 in the examples below). All methods are the same as for normal regression and classification, except that theexplain_factualandexplain_counterfactualmethods need the additional threshold value (here 180 000).factual_explanations=explainer.explain_factual(X_test,180000)factual_explanations.plot_all()factual_explanations.plot_all(uncertainty=True)factual_explanations.add_conjunctions().plot_all()counterfactual_explanations=explainer.explain_counterfactual(X_test,180000)counterfactual_explanations.plot_all()counterfactual_explanations.add_conjunctions().plot_all()Additional Regression Use CasesRegression offers many more options and to learn more about them, see thedemo_regressionor thedemo_probabilistic_regressionnotebooks.TopKnown LimitationsThe implementation currently only support numerical input. Use theutils.transform_to_numeric(not yet in any  released version) to transform aDataFramewith text data into numerical form and at the same time extractingcategorical_features,categorical_labels,target_labels(if text labels) andmappings(used to apply the same mappings to new data) to be used as input to theCalibratedExplainer. The algorithm does not currently support image data.TopInstallcalibrated-explanationsis implemented in Python, so you need a Python environment.Installcalibrated-explanationsfrom PyPI:pip install calibrated-explanationsor from conda-forge:conda install -c conda-forge calibrated-explanationsor by following further instructions atconda-forge.The dependencies are:crepesvenn-aberslimematplotlibNumPyTopContributingContributions are welcome.
Please send bug reports, feature requests or pull requests through
the project page onGitHub.
You can find a detailed guide for contributions inCONTRIBUTING.md.TopDocumentationFor documentation, seecalibrated-explanations.readthedocs.io.TopFurther reading and citingThecalibrated-explanationsmethod for classification is introduced in the paper:Löfström, H.,Löfström, T., Johansson, U., and Sönströd, C. (2024).Calibrated Explanations: with Uncertainty Information and Counterfactuals. Expert Systems with Applications, 1-27.The extensions for regression are introduced in the paper:Löfström, T.,Löfström, H., Johansson, U., Sönströd, C., andMatela, R.Calibrated Explanations for Regression. arXiv preprint arXiv:2308.16245.The paper that originated the idea ofcalibrated-explanationsis:Löfström, H.,Löfström, T., Johansson, U., & Sönströd, C. (2023).Investigating the impact of calibration on the quality of explanations. Annals of Mathematics and Artificial Intelligence, 1-18.Code and results.If you usecalibrated-explanationsfor a scientific publication, you are kindly requested to cite one of the papers above.Bibtex entry for the original paper:@article{lofstrom2024calibrated,title={Calibrated explanations: With uncertainty information and counterfactuals},journal={Expert Systems with Applications},pages={123154},year={2024},issn={0957-4174},doi={https://doi.org/10.1016/j.eswa.2024.123154},url={https://www.sciencedirect.com/science/article/pii/S0957417424000198},author={Helena Löfström and Tuwe Löfström and Ulf Johansson and Cecilia Sönströd},keywords={Explainable AI, Feature importance, Calibrated explanations, Venn-Abers, Uncertainty quantification, Counterfactual explanations},abstract={While local explanations for AI models can offer insights into individual predictions, such as feature importance, they are plagued by issues like instability. The unreliability of feature weights, often skewed due to poorly calibrated ML models, deepens these challenges. Moreover, the critical aspect of feature importance uncertainty remains mostly unaddressed in Explainable AI (XAI). The novel feature importance explanation method presented in this paper, called Calibrated Explanations (CE), is designed to tackle these issues head-on. Built on the foundation of Venn-Abers, CE not only calibrates the underlying model but also delivers reliable feature importance explanations with an exact definition of the feature weights. CE goes beyond conventional solutions by addressing output uncertainty. It accomplishes this by providing uncertainty quantification for both feature weights and the model’s probability estimates. Additionally, CE is model-agnostic, featuring easily comprehensible conditional rules and the ability to generate counterfactual explanations with embedded uncertainty quantification. Results from an evaluation with 25 benchmark datasets underscore the efficacy of CE, making it stand as a fast, reliable, stable, and robust solution.}}Bibtex entry for the regression paper:@misc{cal-expl-regression,title={Calibrated Explanations for Regression},author={L\"ofstr\"om, Tuwe and L\"ofstr\"om, Helena and Johansson, Ulf and S\"onstr\"od, Cecilia and Matela, Rudy},year={2023},eprint={2308.16245},archivePrefix={arXiv},primaryClass={cs.LG}}To cite this software, use the following bibtex entry:@software{Lofstrom_Calibrated_Explanations_2024,author={Löfström, Helena and Löfström, Tuwe and Johansson, Ulf and Sönströd, Cecilia and Matela, Rudy},license={BSD-3-Clause},title={Calibrated Explanations},url={https://github.com/Moffran/calibrated_explanations},version={v0.3.1},month=Feb,year={2024}}TopAcknowledgementsThis research is funded by the Swedish Knowledge Foundation together with industrial partners supporting the research and education environment on Knowledge Intensive Product Realization SPARK at Jönköping University, Sweden, through projects: AFAIR grant no. 20200223 and PREMACOP grant no. 20220187. Helena Löfström was a PhD student in the Industrial Graduate School in Digital Retailing (INSiDR) at the University of Borås, funded by the Swedish Knowledge Foundation, grant no. 20160035.Rudy Matelahas been our git guru and has helped us with the release process.We have used both theConformalPredictiveSystemandDifficultyEstimatorclasses fromHenrik Boströmscrepespackage to provide support for regression.We have used theVennAbersclass fromIvan Petejsvenn-aberspackage to provide support for probabilistic explanations (both classification and probabilistic regression).We have used code fromMarco Tulio Correia Ribeiroslimepackage for theDiscretizerclass.Thecheck_is_fittedandsafe_instancefunctions incalibrated_explanations.utilsare copied fromsklearnandshap.Top