docstr: A wrapper around the `shap.KernelExplainer` class. It extends the current `shap` library functionality
  by allowing the user to specify variable groups in order to treat one-hot encoded categorical as one during
  sampling. The user can also specify whether to aggregate the `shap` values estimate for the encoded levels
  of categorical variables as an optional argument to `explain`, if grouping arguments are not passed to `fit`.
  
  Parameters
  ----------
  predictor
      A callable that takes as an input a `samples x features` array and outputs a `samples x n_outputs`
      model outputs. The `n_outputs` should represent model output in margin space. If the model outputs
      probabilities, then the link should be set to ``'logit'`` to ensure correct force plots.
  link
      Valid values are ``'identity'`` or ``'logit'``. A generalized linear model link to connect the feature
      importance values to the model output. Since the feature importance values, :math:`\phi`, sum up to the
      model output, it often makes sense to connect them to the ouput with a link function where
      :math:`link(output - expected\_value) = sum(\phi)`. Therefore, for a model which outputs probabilities,
      ``link='logit'`` makes the feature effects have log-odds (evidence) units and ``link='identity'`` means
      that the feature effects have probability units. Please see this `example`_ for an in-depth discussion 
      about the semantics of explaining the model in the probability or margin space.
  
      .. _example:
         https://github.com/slundberg/shap/blob/master/notebooks/tabular_examples/model_agnostic/Squashing%20Effect.ipynb 
  
  feature_names
      Used to infer group names when categorical data is treated by grouping and `group_names` input to `fit`
      is not specified, assuming it has the same length as the `groups` argument of `fit` method. It is also used
      to compute the `names` field, which appears as a key in each of the values of
      `explanation.data['raw']['importances']`.
  categorical_names
      Keys are feature column indices in the `background_data` matrix (see `fit`). 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 k-means 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
      `explanation.data['raw']['prediction']`
  seed
      Fixes the random number stream, which influences which subsets are sampled during shap value estimation.
  distributed_opts
      A dictionary that controls the algorithm distributed execution. 
      See :py:data:`alibi.explainers.shap_wrappers.DISTRIBUTED_OPTS` documentation for details.
code: def __init__(
      self,
      predictor: Callable[[np.ndarray], np.ndarray],
      link: str = "identity",
      feature_names: Optional[Union[List[str], Tuple[str]]] = None,
      categorical_names: Optional[Dict[int, List[str]]] = None,
      task: str = "classification",
      seed: Optional[int] = None,
      distributed_opts: Optional[Dict] = None,
  ):
      """
      A wrapper around the `shap.KernelExplainer` class. It extends the current `shap` library functionality
      by allowing the user to specify variable groups in order to treat one-hot encoded categorical as one during
      sampling. The user can also specify whether to aggregate the `shap` values estimate for the encoded levels
      of categorical variables as an optional argument to `explain`, if grouping arguments are not passed to `fit`.
  
      Parameters
      ----------
      predictor
          A callable that takes as an input a `samples x features` array and outputs a `samples x n_outputs`
          model outputs. The `n_outputs` should represent model output in margin space. If the model outputs
          probabilities, then the link should be set to ``'logit'`` to ensure correct force plots.
      link
          Valid values are ``'identity'`` or ``'logit'``. A generalized linear model link to connect the feature
          importance values to the model output. Since the feature importance values, :math:`\phi`, sum up to the
          model output, it often makes sense to connect them to the ouput with a link function where
          :math:`link(output - expected\_value) = sum(\phi)`. Therefore, for a model which outputs probabilities,
          ``link='logit'`` makes the feature effects have log-odds (evidence) units and ``link='identity'`` means
          that the feature effects have probability units. Please see this `example`_ for an in-depth discussion
          about the semantics of explaining the model in the probability or margin space.
  
          .. _example:
             https://github.com/slundberg/shap/blob/master/notebooks/tabular_examples/model_agnostic/Squashing%20Effect.ipynb
  
      feature_names
          Used to infer group names when categorical data is treated by grouping and `group_names` input to `fit`
          is not specified, assuming it has the same length as the `groups` argument of `fit` method. It is also used
          to compute the `names` field, which appears as a key in each of the values of
          `explanation.data['raw']['importances']`.
      categorical_names
          Keys are feature column indices in the `background_data` matrix (see `fit`). 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 k-means 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
          `explanation.data['raw']['prediction']`
      seed
          Fixes the random number stream, which influences which subsets are sampled during shap value estimation.
      distributed_opts
          A dictionary that controls the algorithm distributed execution.
          See :py:data:`alibi.explainers.shap_wrappers.DISTRIBUTED_OPTS` documentation for details.
      """  # noqa W605
  
      super().__init__(meta=copy.deepcopy(DEFAULT_META_KERNEL_SHAP))
  
      self.link = link
      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
      self._update_metadata({"task": self.task})
      self._update_metadata({"link": self.link}, params=True)
  
      # if the user specifies groups but no names, the groups are automatically named
      self.use_groups = False
      # changes if feature groups indices are passed but not names
      self.create_group_names = False
      # if sum of groups entries matches first dimension as opposed to second, warn user
      self.transposed = False
      # if weights are not correctly specified, they are ignored
      self.ignore_weights = False
      # 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
      self._fitted = False
  
      self.distributed_opts = copy.deepcopy(DISTRIBUTED_OPTS)
      if distributed_opts:
          self.distributed_opts.update(distributed_opts)
      self.distributed_opts["algorithm"] = "kernel_shap"
      self.distribute = (
          True if self.distributed_opts["n_cpus"] else False
      )
  
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 KernelShap object from inherited base classes: Explainer, FitMixin with example: obj = KernelShap(predictor, link, feature_names, categorical_names, task, seed, distributed_opts)