{ "cells": [ { "cell_type": "markdown", "id": "b1db8c9a", "metadata": {}, "source": [ "# Contrastive Reasons" ] }, { "cell_type": "markdown", "id": "dc23fadf", "metadata": {}, "source": [ "{: .attention }\n", "> The algorithms to compute contrastive reasons for multi-class classification problems are still under development and should be available in the next versions of PyXAI (however, the contrastive reasons for binary classification can be calculated)." ] }, { "cell_type": "markdown", "id": "514a5144", "metadata": {}, "source": "Unlike abductive explanations that explain why an instance $x$ is classified as belonging to a given class, the **contrastive explanations** explains why $x$ has not been classified by the ML model as expected.\n\nLet 𝑓 be a Boolean function represented by a random forest 𝑅𝐹, 𝑥 be an instance and 1 (resp. 0) the prediction of 𝑅𝐹 on 𝑥 (𝑓(𝑥)=1 (resp $f(x)=0$)), a **contrastive reason** for $x$ is a term $t$ such that:\n* $t \\subseteq t_{x}$, $t_{x} \\setminus t$ is not an implicant of $f;$ \n* for every $\\ell \\in t$, $t \\setminus \\{\\ell\\}$ does not satisfy this previous condition (i.e., $t$ is minimal w.r.t. set inclusion).\n\nFormally, a **contrastive reason** for $x$ is a subset $t$ of the characteristics of $x$ that is minimal w.r.t. set inclusion among those such that at least one instance $x'$ that coincides with $x$ except on the characteristics from $t$ is not classified by the decision tree as $x$ is. Stated otherwise, a **contrastive reason** represents adjustments of the features that we have to do to change the prediction for an instance. \n\nA contrastive reason is minimal w.r.t. set inclusion, i.e. there is no subset of this reason which is also a contrastive reason. A **minimal contrastive reason** for $x$ is a contrastive reason for $x$ that contains a minimal number of literals. In other words, a **minimal contrastive reason** has a minimal size. \n\nMore information about contrastive reasons can be found in the paper [On the Explanatory Power of Decision Trees](https://arxiv.org/abs/2108.05266).\n\nThe function ```ExplainerRF.minimal_contrastive_reason``` allows computing this kind of explanation.\n\nThe library also provides a way to check that a reason is contrastive using the function ```is_contrastive_reason```." }, { "cell_type": "markdown", "id": "56693e24", "metadata": {}, "source": [ "{: .note}\n", "For random forests, PyXAI can only compute minimal contrastive reasons." ] }, { "cell_type": "markdown", "id": "b151176d", "metadata": {}, "source": [ "The PyXAI library provides a way to check that a reason is contrastive:" ] }, { "cell_type": "markdown", "id": "2b240b8f", "metadata": {}, "source": [ "The basic methods ([``initialize``](/documentation/api/modules/explaining/), ```set_instance```, ```to_features```, ```is_reason```, ...) of the ```Explainer``` module used in the next examples are described in the [Explainer Principles](/documentation/explainer/) page." ] }, { "cell_type": "markdown", "id": "c8f0eead", "metadata": {}, "source": [ "## Example from Hand-Crafted Trees" ] }, { "cell_type": "markdown", "id": "ad910b80", "metadata": {}, "source": [ "For this example, we take the random forest of the [Building Models](/documentation/learning/builder/RFbuilder/) page consisting of $4$ binary features ($x_1$, $x_2$, $x_3$ and $x_4$). \n", "\n", "The following figure shows the new instance $x' = (1,1,1,0)$ created from the contrastive reason $(x_4)$ in red for the instance $x = (1,1,1,1)$. Thus, the instance $(1,1,1,0)$ that differs with $x$ only on $x_4$ is not classified by $T$ as $x$ is. More precisely, $x'$ is classified as a negative instance while $x$ is classified as a positive instance. Indeed, in this figure, $T_1(x') = 0$, $T_2(x') = 1$ and $T_3(x') = 0$, so $f(x') = 0$. \n", "\n", "\"RFcontrastive\"\n", "\n", "Now, we show how to get them with PyXAI. We start by building the random forest: " ] }, { "cell_type": "code", "execution_count": 1, "id": "a7a88ebf", "metadata": {}, "outputs": [], "source": [ "from pyxai import Builder, Explaining\n", "\n", "nodeT1_1 = Builder.DecisionNode(1, left=0, right=1)\n", "nodeT1_3 = Builder.DecisionNode(3, left=0, right=nodeT1_1)\n", "nodeT1_2 = Builder.DecisionNode(2, left=1, right=nodeT1_3)\n", "nodeT1_4 = Builder.DecisionNode(4, left=0, right=nodeT1_2)\n", "\n", "tree1 = Builder.DecisionTree(4, nodeT1_4, force_features_equal_to_binaries=True)\n", "\n", "nodeT2_4 = Builder.DecisionNode(4, left=0, right=1)\n", "nodeT2_1 = Builder.DecisionNode(1, left=0, right=nodeT2_4)\n", "nodeT2_2 = Builder.DecisionNode(2, left=nodeT2_1, right=1)\n", "\n", "tree2 = Builder.DecisionTree(4, nodeT2_2, force_features_equal_to_binaries=True) #4 features but only 3 used\n", "\n", "nodeT3_1_1 = Builder.DecisionNode(1, left=0, right=1)\n", "nodeT3_1_2 = Builder.DecisionNode(1, left=0, right=1)\n", "nodeT3_4_1 = Builder.DecisionNode(4, left=0, right=nodeT3_1_1)\n", "nodeT3_4_2 = Builder.DecisionNode(4, left=0, right=1)\n", "\n", "nodeT3_2_1 = Builder.DecisionNode(2, left=nodeT3_1_2, right=nodeT3_4_1)\n", "nodeT3_2_2 = Builder.DecisionNode(2, left=0, right=nodeT3_4_2)\n", "\n", "nodeT3_3_1 = Builder.DecisionNode(3, left=nodeT3_2_1, right=nodeT3_2_2)\n", "\n", "tree3 = Builder.DecisionTree(4, nodeT3_3_1, force_features_equal_to_binaries=True)\n", "forest = Builder.RandomForest([tree1, tree2, tree3], n_classes=2)" ] }, { "cell_type": "markdown", "id": "c177fc1f", "metadata": {}, "source": [ "We compute the contrastive reasons for these two instances: " ] }, { "cell_type": "code", "execution_count": 2, "id": "f0733b41", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Contrastives: ((4,),)\n", "-------------------------------\n", "Contrastives: ((-1, -4),)\n" ] } ], "source": [ "explainer = Explaining.initialize(forest)\n", "explainer.set_instance((1,1,1,1))\n", "\n", "contrastives = explainer.minimal_contrastive_reason(n=Explaining.ALL)\n", "print(\"Contrastives:\", contrastives)\n", "for contrastive in contrastives:\n", " assert explainer.is_contrastive_reason(contrastive), \"It is not a contrastive reason !\"\n", "\n", "print(\"-------------------------------\")\n", "\n", "explainer.set_instance((0,0,0,0))\n", "\n", "contrastives = explainer.minimal_contrastive_reason(n=Explaining.ALL)\n", "print(\"Contrastives:\", contrastives)\n", "for contrastive in contrastives:\n", " assert explainer.is_contrastive_reason(contrastive), \"It is not a contrastive reason !\"" ] }, { "cell_type": "markdown", "id": "c75f8563", "metadata": {}, "source": [ "## Example from a Real Dataset" ] }, { "cell_type": "markdown", "id": "ed0ed888", "metadata": {}, "source": [ "For this example, we take the [mnist49](/assets/notebooks/dataset/mnist49.csv) dataset. We create a model using the hold-out approach (by default, the test size is set to 30%) and select a well-classified instance. " ] }, { "cell_type": "code", "execution_count": 3, "id": "bbeb5462", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-------------- Information ---------------\n", "Problem type: classification\n", "Instances type: tabular\n", "Labels type: classes\n", "\n", "Dataset path: ../../../dataset/mnist49.csv\n", "nFeatures (nAttributes, with the labels): 784\n", "nInstances (nObservations): 13782\n", "nLabels: 2\n", "--------------- Model creation, fitting and evaluation ---------------\n", "Splitting method: hold-out\n", "Problem type: classification\n", "Models type: random-forest\n", "model_parameters: {}\n", "--------- Evaluation Information ---------\n", "For the evaluation number 0:\n", "Metrics:\n", " sklearn_confusion_matrix: [[1689, 26], [25, 1706]]\n", " accuracy: 98.52002321532211\n", "Number of Training instances: 10336\n", "Number of Testing instances: 3446\n", "\n", "--------------- Explainer ----------------\n", "For the split number 0:\n", "**Random Forest Model**\n", "nClasses: 2\n", "nTrees: 100\n", "nVariables: 29013\n", "\n", "--------------- Instances ----------------\n", "Number of instances selected: 1\n", "----------------------------------------------\n" ] } ], "source": [ "from pyxai import Learning, Explaining\n", "\n", "learner = Learning.Scikitlearn(\"../../../dataset/mnist49.csv\", problem_type='classification')\n", "model = learner.evaluate(splitting_method=Learning.HOLD_OUT, model_type=Learning.RF)\n", "instance, prediction = learner.get_instances(model, n=1, is_correct=True)" ] }, { "cell_type": "markdown", "id": "0bc4b271", "metadata": {}, "source": [ "We compute one contrastive reason. Since it is a hard task, we put a time_limit. If ```time_limit``` is reached, we obtain either an approximation of a contrastive reason (some literals can be redundant) or the empty list if no contrastive reason was found: " ] }, { "cell_type": "code", "execution_count": 4, "id": "c2a2d7f1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "instance prediction: 4\n", "\n", "minimal_contrastive_reason: end by time_limit or 'n' reached.\n", "this is an approximation\n", "constrative: ['153 <= 1.5', '158 <= 2.5', '161 > 0.5', '162 > 0.5', '180 <= 253.5', '185 <= 1.0', '186 <= 2.5', '189 in ]0.5, 252.5]', '208 <= 41.5', '209 <= 232.5', '210 <= 251.5', '211 <= 31.5', '212 <= 56.5', '213 <= 20.0', '215 <= 10.5', '216 > 0.5', '234 <= 0.5', '235 <= 253.5', '236 <= 1.5', '237 <= 253.5', '238 <= 3.0', '239 <= 248.5', '240 <= 254.5', '241 <= 1.5', '242 <= 12.5', '262 <= 1.5', '267 <= 0.5', '273 > 3.5', '295 <= 251.5', '319 <= 202.5', '323 <= 179.5', '325 <= 253.5', '343 <= 252.5', '347 <= 38.0', '379 <= 251.5', '401 <= 252.5', '429 > 252.5', '431 > 231.5', '463 <= 1.0', '466 > 0.5', '492 <= 0.5', '493 <= 254.5', '575 <= 254.5', '603 <= 253.5', '606 > 253.5', '611 <= 45.5', '623 <= 253.5', '656 <= 253.5', '661 <= 252.5', '664 <= 252.5', '710 <= 0.5', '717 <= 5.0', '739 <= 0.5', '740 <= 2.5', '746 <= 4.5', '747 <= 22.0', '748 <= 15.0']\n" ] } ], "source": [ "explainer = Explaining.initialize(model, instance)\n", "print(\"instance prediction:\", prediction)\n", "print()\n", "\n", "contrastive_reason = explainer.minimal_contrastive_reason(n=1, time_limit=10)\n", "if explainer.elapsed_time == Explaining.TIMEOUT: \n", " print('this is an approximation')\n", "if len(contrastive_reason) > 0: \n", " print(\"constrative: \", explainer.to_features(contrastive_reason, contrastive=True))\n", "else: \n", " print('No contrative reason found')" ] }, { "cell_type": "markdown", "id": "318185c1", "metadata": {}, "source": [ "Other types of explanations are presented in the [Explanations Computation](/documentation/explanations/RFexplanations/) page." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.7" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 5 }