|
| 1 | +# |
| 2 | +# Copyright (c) 2022 salesforce.com, inc. |
| 3 | +# All rights reserved. |
| 4 | +# SPDX-License-Identifier: BSD-3-Clause |
| 5 | +# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | +# |
| 7 | +""" |
| 8 | +The SHAP explainer for global feature importance. |
| 9 | +""" |
| 10 | +import shap |
| 11 | +import numpy as np |
| 12 | +from typing import Callable, List |
| 13 | + |
| 14 | +from ..base import TabularExplainer |
| 15 | +from ....data.tabular import Tabular |
| 16 | +from ....explanations.tabular.feature_importance import GlobalFeatureImportance |
| 17 | + |
| 18 | + |
| 19 | +class GlobalShapTabular(TabularExplainer): |
| 20 | + """ |
| 21 | + The SHAP explainer for global feature importance. |
| 22 | + If using this explainer, please cite the original work: https://github.com/slundberg/shap. |
| 23 | + """ |
| 24 | + |
| 25 | + explanation_type = "global" |
| 26 | + alias = ["shap_global"] |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + training_data: Tabular, |
| 31 | + predict_function: Callable, |
| 32 | + mode: str = "classification", |
| 33 | + ignored_features: List = None, |
| 34 | + **kwargs |
| 35 | + ): |
| 36 | + """ |
| 37 | + :param training_data: The data used to initialize a SHAP explainer. ``training_data`` |
| 38 | + can be the training dataset for training the machine learning model. If the training |
| 39 | + dataset is large, please set parameter ``nsamples``, e.g., ``nsamples = 100``. |
| 40 | + :param predict_function: The prediction function corresponding to the model to explain. |
| 41 | + When the model is for classification, the outputs of the ``predict_function`` |
| 42 | + are the class probabilities. When the model is for regression, the outputs of |
| 43 | + the ``predict_function`` are the estimated values. |
| 44 | + :param mode: The task type, e.g., `classification` or `regression`. |
| 45 | + :param ignored_features: The features ignored in computing feature importance scores. |
| 46 | + :param kwargs: Additional parameters to initialize `shap.KernelExplainer`, e.g., ``nsamples``. |
| 47 | + Please refer to the doc of `shap.KernelExplainer`. |
| 48 | + """ |
| 49 | + super().__init__(training_data=training_data, predict_function=predict_function, mode=mode, **kwargs) |
| 50 | + self.ignored_features = set(ignored_features) if ignored_features is not None else set() |
| 51 | + if self.target_column is not None: |
| 52 | + assert self.target_column not in self.ignored_features, \ |
| 53 | + f"The target column {self.target_column} cannot be in the ignored feature list." |
| 54 | + self.valid_indices = [i for i, f in enumerate(self.feature_columns) if f not in self.ignored_features] |
| 55 | + |
| 56 | + if "nsamples" not in kwargs: |
| 57 | + kwargs["nsamples"] = 100 |
| 58 | + self.background_data = shap.sample(self.data, nsamples=kwargs["nsamples"]) |
| 59 | + self.sampled_data = shap.sample(self.data, nsamples=kwargs["nsamples"]) |
| 60 | + |
| 61 | + def _explain_global(self, X, **kwargs) -> GlobalFeatureImportance: |
| 62 | + if "nsamples" not in kwargs: |
| 63 | + kwargs["nsamples"] = 100 |
| 64 | + instances = self.sampled_data if X is None else \ |
| 65 | + self.transformer.transform(X.remove_target_column()) |
| 66 | + |
| 67 | + explanations = GlobalFeatureImportance() |
| 68 | + explainer = shap.KernelExplainer( |
| 69 | + self.predict_fn, self.background_data, |
| 70 | + link="logit" if self.mode == "classification" else "identity", **kwargs |
| 71 | + ) |
| 72 | + shap_values = explainer.shap_values(instances, **kwargs) |
| 73 | + |
| 74 | + if self.mode == "classification": |
| 75 | + values = 0 |
| 76 | + for v in shap_values: |
| 77 | + values += np.abs(v) |
| 78 | + values /= len(shap_values) |
| 79 | + shap_values = values |
| 80 | + |
| 81 | + importance_scores = np.mean(np.abs(shap_values), axis=0) |
| 82 | + explanations.add( |
| 83 | + feature_names=self.feature_columns, |
| 84 | + importance_scores=importance_scores, |
| 85 | + sort=True |
| 86 | + ) |
| 87 | + return explanations |
| 88 | + |
| 89 | + def explain( |
| 90 | + self, |
| 91 | + X: Tabular = None, |
| 92 | + **kwargs |
| 93 | + ): |
| 94 | + """ |
| 95 | + Generates the global SHAP explanations. |
| 96 | +
|
| 97 | + :param X: The data will be used to compute global SHAP values, i.e., the mean of the absolute |
| 98 | + SHAP value for each feature. If `X` is None, a set of training samples will be used. |
| 99 | + :param kwargs: Additional parameters for `shap.KernelExplainer.shap_values`, |
| 100 | + e.g., ``nsamples`` -- the number of times to re-evaluate the model when explaining each prediction. |
| 101 | + :return: The global feature importance explanations. |
| 102 | + """ |
| 103 | + return self._explain_global(X=X, **kwargs) |
| 104 | + |
| 105 | + def save( |
| 106 | + self, |
| 107 | + directory: str, |
| 108 | + filename: str = None, |
| 109 | + **kwargs |
| 110 | + ): |
| 111 | + """ |
| 112 | + Saves the initialized explainer. |
| 113 | +
|
| 114 | + :param directory: The folder for the dumped explainer. |
| 115 | + :param filename: The filename (the explainer class name if it is None). |
| 116 | + """ |
| 117 | + super().save( |
| 118 | + directory=directory, |
| 119 | + filename=filename, |
| 120 | + ignored_attributes=["data"], |
| 121 | + **kwargs |
| 122 | + ) |
0 commit comments