docstr: This function instantiates an explainer which can then be use to explain instances using the `explain` method.
  If no background dataset is passed, the explainer uses the path-dependent feature perturbation algorithm
  to explain the values. As such, only the model raw output can be explained and this should be reflected by
  passing ``model_output='raw'`` when instantiating the explainer. If a background dataset is passed, the
  interventional feature perturbation algorithm is used. Using this algorithm, probability outputs can also be
  explained. Additionally, if the ``model_output='log_loss'`` option is passed to the explainer constructor, then
  the model loss function can be explained by passing the labels as the `y` argument to the explain method.
  A limited number of loss functions are supported, as detailed in the constructor documentation.
  
  Parameters
  -----------
  background_data
      Data used to estimate feature contributions and baseline values for force plots. The rows of the
      background data should represent samples and the columns features.
  summarise_background
      A large background dataset may impact the runtime and memory footprint of the algorithm. By setting
      this argument to ``True``, only `n_background_samples` from the provided data are selected. If the
      `categorical_names` argument has been passed to the constructor, subsampling of the data is used.
      Otherwise, `shap.kmeans` (a wrapper around `sklearn.kmeans` implementation) is used for selection.
      If set to ``'auto'``, a default of `TREE_SHAP_BACKGROUND_WARNING_THRESHOLD` samples is selected.
  n_background_samples
      The number of samples to keep in the background dataset if ``summarise_background=True``.
code: def fit(
      self,  # type: ignore[override]
      background_data: Union[np.ndarray, pd.DataFrame, None] = None,
      summarise_background: Union[bool, str] = False,
      n_background_samples: int = TREE_SHAP_BACKGROUND_WARNING_THRESHOLD,
      **kwargs,
  ) -> "TreeShap":
      """
      This function instantiates an explainer which can then be use to explain instances using the `explain` method.
      If no background dataset is passed, the explainer uses the path-dependent feature perturbation algorithm
      to explain the values. As such, only the model raw output can be explained and this should be reflected by
      passing ``model_output='raw'`` when instantiating the explainer. If a background dataset is passed, the
      interventional feature perturbation algorithm is used. Using this algorithm, probability outputs can also be
      explained. Additionally, if the ``model_output='log_loss'`` option is passed to the explainer constructor, then
      the model loss function can be explained by passing the labels as the `y` argument to the explain method.
      A limited number of loss functions are supported, as detailed in the constructor documentation.
  
      Parameters
      -----------
      background_data
          Data used to estimate feature contributions and baseline values for force plots. The rows of the
          background data should represent samples and the columns features.
      summarise_background
          A large background dataset may impact the runtime and memory footprint of the algorithm. By setting
          this argument to ``True``, only `n_background_samples` from the provided data are selected. If the
          `categorical_names` argument has been passed to the constructor, subsampling of the data is used.
          Otherwise, `shap.kmeans` (a wrapper around `sklearn.kmeans` implementation) is used for selection.
          If set to ``'auto'``, a default of `TREE_SHAP_BACKGROUND_WARNING_THRESHOLD` samples is selected.
      n_background_samples
          The number of samples to keep in the background dataset if ``summarise_background=True``.
      """
  
      np.random.seed(self.seed)
  
      self._fitted = True
      if isinstance(background_data, pd.DataFrame):
          self.feature_names = list(background_data.columns)
      if background_data is not None:
          if (
              isinstance(background_data, np.ndarray)
              and background_data.ndim == 1
          ):
              background_data = np.atleast_2d(background_data)
          if summarise_background:
              n_samples = background_data.shape[0]
              if isinstance(summarise_background, str):
                  if n_samples > TREE_SHAP_BACKGROUND_WARNING_THRESHOLD:
                      background_data = self._summarise_background(
                          background_data,
                          TREE_SHAP_BACKGROUND_WARNING_THRESHOLD,
                      )
              else:
                  if n_samples > n_background_samples:
                      background_data = self._summarise_background(
                          background_data, n_background_samples
                      )
          else:
              self._check_inputs(background_data)
  
          # summarisation can return a DenseData object
          n_samples = (
              background_data.data
              if isinstance(background_data, shap_utils.DenseData)
              else background_data
          ).shape[0]
  
          # Warns the user that TreeShap supports only up to TREE_SHAP_BACKGROUND_SIZE(100) samples in the
          # background dataset. Note that there is a logic above related to the summarisation of the background
          # dataset which uses TREE_SHAP_BACKGROUND_WARNING_THRESHOLD(1000) as (warning) threshold. Although the
          # TREE_SHAP_BACKGROUND_WARNING_THRESHOLD > TREE_SHAP_BACKGROUND_SUPPORTED_SIZE which is contradictory, we
          # leave the logic above untouched. This approach has at least two benefits:
          #   i) minimal refactoring
          #   ii) return the correct result if a newer version of shap which fixes the issue is used before we
          #   update our dependencies in alibi (i.e. just ignore the warning)
          if n_samples > TREE_SHAP_BACKGROUND_SUPPORTED_SIZE:
              logger.warning(
                  f"The upstream implementation of interventional TreeShap supports only up to "
                  f"{TREE_SHAP_BACKGROUND_SUPPORTED_SIZE} samples in the background dataset. "
                  f"A larger background dataset will be sampled with replacement to "
                  f"{TREE_SHAP_BACKGROUND_SUPPORTED_SIZE} instances."
              )
  
      self.perturbation = (
          "interventional"
          if background_data is not None
          else "tree_path_dependent"
      )
      self.background_data = background_data
      self._explainer = self._init_shap_object()
      self.expected_value = self._explainer.expected_value
  
      self.scalar_output = False
      if self._explainer.model.num_outputs == 1:
          if self.task == "classification":
              logger.warning(
                  "Predictor returned a scalar value. Ensure the output represents a probability or decision score "
                  "as opposed to a classification label!"
              )
          self.scalar_output = True
  
      # update metadata
      params = {
          "summarise_background": self.summarise_background,
          "algorithm": self.perturbation,
          "kwargs": kwargs,
      }
      self._update_metadata(params, params=True)
      return self
  
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 2 for calling the TreeShap obj's underlying member method code with example usage: obj.fit(background_data, summarise_background, n_background_samples) and returns: self