docstr: A wrapper around the `shap.TreeExplainer` class. It adds the following functionality:
  
      1. Input summarisation options to allow control over background dataset size and hence runtime
      2. Output summarisation for sklearn models with one-hot encoded categorical variables.
  
  Users are strongly encouraged to familiarise themselves with the algorithm by reading the method
  overview in the documentation.
  
  Parameters
  ----------
  predictor
      A fitted model to be explained. `XGBoost`, `LightGBM`, `CatBoost` and most tree-based
      `scikit-learn` models are supported. In the future, `Pyspark` could also be supported.
      Please open an issue if this is a use case for you.
  model_output
      Supported values are: ``'raw'``, ``'probability'``, ``'probability_doubled'``, ``'log_loss'``: 
  
          - ``'raw'`` - the raw model of the output, which varies by task, is explained. This option                 should always be used if the `fit` is called without arguments. It should also be set to compute                 shap interaction values. For regression models it is the standard output, for binary classification                 in `XGBoost` it is the log odds ratio. 
          - ``'probability'`` - the probability output is explained. This option should only be used if `fit`                 was called with the `background_data` argument set. The effect of specifying this parameter is that                 the `shap` library will use this information to transform the shap values computed in margin space                 (aka using the raw output) to shap values that sum to the probability output by the model plus the                 model expected output probability. This requires knowledge of the type of output for `predictor`                 which is inferred by the `shap` library from the model type (e.g., most sklearn models with exception                 of `sklearn.tree.DecisionTreeClassifier`, `sklearn.ensemble.RandomForestClassifier`,                 `sklearn.ensemble.ExtraTreesClassifier` output logits) or on the basis of the mapping implemented in                 the `shap.TreeEnsemble` constructor. Only trees that output log odds and probabilities are supported                 currently.  
  
          - ``'probability_doubled'`` - used for binary classification problem in situations where the model                 outputs the logits/probabilities for the positive class but shap values for both outcomes are desired.                 This option should be used only if `fit` was called with the `background_data` argument set. In                 this case the expected value for the negative class is 1 - expected_value for positive class and                 the shap values for the negative class are the negative values of the positive class shap values.                 As before, the explanation happens in the margin space, and the shap values are subsequently adjusted.                 convert the model output to probabilities. The same considerations as for `probability` apply for this                 output type too. 
  
          - ``'log_loss'`` - logarithmic loss is explained. This option shoud be used only if `fit` was called                 with the `background_data` argument set and requires specifying labels, `y`, when calling `explain`.                 If the objective is squared error, then the transformation :math:`(output - y)^2` is applied. For                 binary cross-entropy objective, the transformation :math:`log(1 + exp(output)) - y * output` with                  :math:`y \in \{0, 1\}`. Currently only binary cross-entropy and squared error losses can be explained. 
  feature_names
      Used to compute the `names` field, which appears as a key in each of the values of the `importances`
      sub-field of the response `raw` field.
  categorical_names
      Keys are feature column indices. Each value contains strings with the names of the categories
      for the feature. Used to select the method for background data summarisation (if specified,
      subsampling is performed as opposed to kmeans clustering). In the future it may be used for visualisation.
  task
      Can have values ``'classification'`` and ``'regression'``. It is only used to set the contents of the 
      `prediction` field in the `data['raw']` response field.
  
  Notes
  -----
  Tree SHAP is an additive attribution method so it is best suited to explaining output in margin space
  (the entire real line). For discussion related to explaining models in output vs probability space, please
  consult this  resource_.
  
  .. _resource: https://github.com/slundberg/shap/blob/master/notebooks/tabular_examples/model_agnostic/Squashing%20Effect.ipynb
code: def __init__(
      self,
      predictor: Any,
      model_output: str = "raw",
      feature_names: Optional[Union[List[str], Tuple[str]]] = None,
      categorical_names: Optional[Dict[int, List[str]]] = None,
      task: str = "classification",
      seed: Optional[int] = None,
  ):
      """
          A wrapper around the `shap.TreeExplainer` class. It adds the following functionality:
  
              1. Input summarisation options to allow control over background dataset size and hence runtime
              2. Output summarisation for sklearn models with one-hot encoded categorical variables.
  
          Users are strongly encouraged to familiarise themselves with the algorithm by reading the method
          overview in the documentation.
  
          Parameters
          ----------
          predictor
              A fitted model to be explained. `XGBoost`, `LightGBM`, `CatBoost` and most tree-based
              `scikit-learn` models are supported. In the future, `Pyspark` could also be supported.
              Please open an issue if this is a use case for you.
          model_output
              Supported values are: ``'raw'``, ``'probability'``, ``'probability_doubled'``, ``'log_loss'``: 
  
                  - ``'raw'`` - the raw model of the output, which varies by task, is explained. This option \
                  should always be used if the `fit` is called without arguments. It should also be set to compute \
                  shap interaction values. For regression models it is the standard output, for binary classification \
                  in `XGBoost` it is the log odds ratio. \
  
                  - ``'probability'`` - the probability output is explained. This option should only be used if `fit` \
                  was called with the `background_data` argument set. The effect of specifying this parameter is that \
                  the `shap` library will use this information to transform the shap values computed in margin space \
                  (aka using the raw output) to shap values that sum to the probability output by the model plus the \
                  model expected output probability. This requires knowledge of the type of output for `predictor` \
                  which is inferred by the `shap` library from the model type (e.g., most sklearn models with exception \
                  of `sklearn.tree.DecisionTreeClassifier`, `sklearn.ensemble.RandomForestClassifier`, \
                  `sklearn.ensemble.ExtraTreesClassifier` output logits) or on the basis of the mapping implemented in \
                  the `shap.TreeEnsemble` constructor. Only trees that output log odds and probabilities are supported \
                  currently.  
  
                  - ``'probability_doubled'`` - used for binary classification problem in situations where the model \
                  outputs the logits/probabilities for the positive class but shap values for both outcomes are desired. \
                  This option should be used only if `fit` was called with the `background_data` argument set. In \
                  this case the expected value for the negative class is 1 - expected_value for positive class and \
                  the shap values for the negative class are the negative values of the positive class shap values. \
                  As before, the explanation happens in the margin space, and the shap values are subsequently adjusted. \
                  convert the model output to probabilities. The same considerations as for `probability` apply for this \
                  output type too. 
  
                  - ``'log_loss'`` - logarithmic loss is explained. This option shoud be used only if `fit` was called \
                  with the `background_data` argument set and requires specifying labels, `y`, when calling `explain`. \
                  If the objective is squared error, then the transformation :math:`(output - y)^2` is applied. For \
                  binary cross-entropy objective, the transformation :math:`log(1 + exp(output)) - y * output` with  \
                  :math:`y \in \{0, 1\}`. Currently only binary cross-entropy and squared error losses can be explained. \
  
          feature_names
              Used to compute the `names` field, which appears as a key in each of the values of the `importances`
              sub-field of the response `raw` field.
          categorical_names
              Keys are feature column indices. Each value contains strings with the names of the categories
              for the feature. Used to select the method for background data summarisation (if specified,
              subsampling is performed as opposed to kmeans clustering). In the future it may be used for visualisation.
          task
              Can have values ``'classification'`` and ``'regression'``. It is only used to set the contents of the 
              `prediction` field in the `data['raw']` response field.
  
          Notes
          -----
          Tree SHAP is an additive attribution method so it is best suited to explaining output in margin space
          (the entire real line). For discussion related to explaining models in output vs probability space, please
          consult this  resource_.
  
          .. _resource: https://github.com/slundberg/shap/blob/master/notebooks/tabular_examples/model_agnostic/Squashing%20Effect.ipynb
      """  # noqa W605
  
      super().__init__(meta=copy.deepcopy(DEFAULT_META_TREE_SHAP))
      if model_output in TREE_SHAP_MODEL_OUTPUT:
          self.model_output = model_output
      else:
          logger.warning(
              f"Unrecognised model output {model_output}. Defaulting to model_output='raw'"
          )
          self.model_output = "raw"
      self.predictor = predictor
      self.feature_names = feature_names if feature_names else []
      self.categorical_names = (
          categorical_names if categorical_names else {}
      )
      self.task = task
      self.seed = seed
  
      # sums up shap values for each level of categorical var
      self.summarise_result = False
      # selects a subset of the background data to avoid excessively slow runtimes
      self.summarise_background = False
      # checks if it has been fitted:
      self._fitted = False
  
      self._update_metadata({"task": self.task})
      self._update_metadata(
          {"model_output": self.model_output}, params=True
      )
  
imports: import copy
  import logging
  from functools import partial
  from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
  import numpy
  import pandas
  import shap
  import shap.utils._legacy
  from scipy import sparse
  from scipy.special import expit
  from shap import KernelExplainer
  from alibi.api.defaults import DEFAULT_DATA_KERNEL_SHAP, DEFAULT_DATA_TREE_SHAP, DEFAULT_META_KERNEL_SHAP, DEFAULT_META_TREE_SHAP
  from alibi.api.interfaces import Explainer, Explanation, FitMixin
  from alibi.utils.wrappers import methdispatch
label_desc: Use image node_id 1 to create a new TreeShap object from inherited base classes: Explainer, FitMixin with example: obj = TreeShap(predictor, model_output, feature_names, categorical_names, task, seed)