class_docstr: Uses Shapley values to explain any machine learning model or python function.
  
  This is the primary explainer interface for the SHAP library. It takes any combination
  of a model and masker and returns a callable subclass object that implements
  the particular estimation algorithm that was chosen.
docstr: Build a new explainer for the passed model.
  
  Parameters
  ----------
  model : object or function
      User supplied function or model object that takes a dataset of samples and
      computes the output of the model for those samples.
  
  masker : function, numpy.array, pandas.DataFrame, tokenizer, None, or a list of these for each model input
      The function used to "mask" out hidden features of the form `masked_args = masker(*model_args, mask=mask)`.
      It takes input in the same form as the model, but for just a single sample with a binary
      mask, then returns an iterable of masked samples. These
      masked samples will then be evaluated using the model function and the outputs averaged.
      As a shortcut for the standard masking using by SHAP you can pass a background data matrix
      instead of a function and that matrix will be used for masking. Domain specific masking
      functions are available in shap such as shap.ImageMasker for images and shap.TokenMasker
      for text. In addition to determining how to replace hidden features, the masker can also
      constrain the rules of the cooperative game used to explain the model. For example
      shap.TabularMasker(data, hclustering="correlation") will enforce a hierarchical clustering
      of coalitions for the game (in this special case the attributions are known as the Owen values).
  
  link : function
      The link function used to map between the output units of the model and the SHAP value units. By
      default it is shap.links.identity, but shap.links.logit can be useful so that expectations are
      computed in probability units while explanations remain in the (more naturally additive) log-odds
      units. For more details on how link functions work see any overview of link functions for generalized
      linear models.
  
  algorithm : "auto", "permutation", "partition", "tree", or "linear"
      The algorithm used to estimate the Shapley values. There are many different algorithms that
      can be used to estimate the Shapley values (and the related value for constrained games), each
      of these algorithms have various tradeoffs and are preferable in different situations. By
      default the "auto" options attempts to make the best choice given the passed model and masker,
      but this choice can always be overridden by passing the name of a specific algorithm. The type of
      algorithm used will determine what type of subclass object is returned by this constructor, and
      you can also build those subclasses directly if you prefer or need more fine grained control over
      their options.
  
  output_names : None or list of strings
      The names of the model outputs. For example if the model is an image classifier, then output_names would
      be the names of all the output classes. This parameter is optional. When output_names is None then
      the Explanation objects produced by this explainer will not have any output_names, which could effect
      downstream plots.
  
  seed: None or int
      seed for reproducibility
docstr_tok: ["Build","a","new","explainer","for","the","passed","model",".","Parameters","--","--","--","--","--","model",":","object","or","function","User","supplied","function","or","model","object","that","takes","a","dataset","of","samples","and","computes","the","output","of","the","model","for","those","samples",".","masker",":","function",",","numpy.array",",","pandas.DataFrame",",","tokenizer",",","None",",","or","a","list","of","these","for","each","model","input","The","function","used","to","``","mask","''","out","hidden","features","of","the","form","`","masked_args","=","masker","(","*","model_args",",","mask=mask",")","`",".","It","takes","input","in","the","same","form","as","the","model",",","but","for","just","a","single","sample","with","a","binary","mask",",","then","returns","an","iterable","of","masked","samples",".","These","masked","samples","will","then","be","evaluated","using","the","model","function","and","the","outputs","averaged",".","As","a","shortcut","for","the","standard","masking","using","by","SHAP","you","can","pass","a","background","data","matrix","instead","of","a","function","and","that","matrix","will","be","used","for","masking",".","Domain","specific","masking","functions","are","available","in","shap","such","as","shap.ImageMasker","for","images","and","shap.TokenMasker","for","text",".","In","addition","to","determining","how","to","replace","hidden","features",",","the","masker","can","also","constrain","the","rules","of","the","cooperative","game","used","to","explain","the","model",".","For","example","shap.TabularMasker","(","data",",","hclustering=","''","correlation","''",")","will","enforce","a","hierarchical","clustering","of","coalitions","for","the","game","(","in","this","special","case","the","attributions","are","known","as","the","Owen","values",")",".","link",":","function","The","link","function","used","to","map","between","the","output","units","of","the","model","and","the","SHAP","value","units",".","By","default","it","is","shap.links.identity",",","but","shap.links.logit","can","be","useful","so","that","expectations","are","computed","in","probability","units","while","explanations","remain","in","the","(","more","naturally","additive",")","log-odds","units",".","For","more","details","on","how","link","functions","work","see","any","overview","of","link","functions","for","generalized","linear","models",".","algorithm",":","``","auto","''",",","``","permutation","''",",","``","partition","''",",","``","tree","''",",","or","``","linear","''","The","algorithm","used","to","estimate","the","Shapley","values",".","There","are","many","different","algorithms","that","can","be","used","to","estimate","the","Shapley","values","(","and","the","related","value","for","constrained","games",")",",","each","of","these","algorithms","have","various","tradeoffs","and","are","preferable","in","different","situations",".","By","default","the","``","auto","''","options","attempts","to","make","the","best","choice","given","the","passed","model","and","masker",",","but","this","choice","can","always","be","overridden","by","passing","the","name","of","a","specific","algorithm",".","The","type","of","algorithm","used","will","determine","what","type","of","subclass","object","is","returned","by","this","constructor",",","and","you","can","also","build","those","subclasses","directly","if","you","prefer","or","need","more","fine","grained","control","over","their","options",".","output_names",":","None","or","list","of","strings","The","names","of","the","model","outputs",".","For","example","if","the","model","is","an","image","classifier",",","then","output_names","would","be","the","names","of","all","the","output","classes",".","This","parameter","is","optional",".","When","output_names","is","None","then","the","Explanation","objects","produced","by","this","explainer","will","not","have","any","output_names",",","which","could","effect","downstream","plots",".","seed",":","None","or","int","seed","for","reproducibility"]
code: def __init__(
      self,
      model,
      masker=None,
      link=links.identity,
      algorithm="auto",
      output_names=None,
      feature_names=None,
      linearize_link=True,
      seed=None,
      **kwargs,
  ):
      """Build a new explainer for the passed model.
  
      Parameters
      ----------
      model : object or function
          User supplied function or model object that takes a dataset of samples and
          computes the output of the model for those samples.
  
      masker : function, numpy.array, pandas.DataFrame, tokenizer, None, or a list of these for each model input
          The function used to "mask" out hidden features of the form `masked_args = masker(*model_args, mask=mask)`.
          It takes input in the same form as the model, but for just a single sample with a binary
          mask, then returns an iterable of masked samples. These
          masked samples will then be evaluated using the model function and the outputs averaged.
          As a shortcut for the standard masking using by SHAP you can pass a background data matrix
          instead of a function and that matrix will be used for masking. Domain specific masking
          functions are available in shap such as shap.ImageMasker for images and shap.TokenMasker
          for text. In addition to determining how to replace hidden features, the masker can also
          constrain the rules of the cooperative game used to explain the model. For example
          shap.TabularMasker(data, hclustering="correlation") will enforce a hierarchical clustering
          of coalitions for the game (in this special case the attributions are known as the Owen values).
  
      link : function
          The link function used to map between the output units of the model and the SHAP value units. By
          default it is shap.links.identity, but shap.links.logit can be useful so that expectations are
          computed in probability units while explanations remain in the (more naturally additive) log-odds
          units. For more details on how link functions work see any overview of link functions for generalized
          linear models.
  
      algorithm : "auto", "permutation", "partition", "tree", or "linear"
          The algorithm used to estimate the Shapley values. There are many different algorithms that
          can be used to estimate the Shapley values (and the related value for constrained games), each
          of these algorithms have various tradeoffs and are preferable in different situations. By
          default the "auto" options attempts to make the best choice given the passed model and masker,
          but this choice can always be overridden by passing the name of a specific algorithm. The type of
          algorithm used will determine what type of subclass object is returned by this constructor, and
          you can also build those subclasses directly if you prefer or need more fine grained control over
          their options.
  
      output_names : None or list of strings
          The names of the model outputs. For example if the model is an image classifier, then output_names would
          be the names of all the output classes. This parameter is optional. When output_names is None then
          the Explanation objects produced by this explainer will not have any output_names, which could effect
          downstream plots.
  
      seed: None or int
          seed for reproducibility
  
      """
  
      self.model = model
      self.output_names = output_names
      self.feature_names = feature_names
  
      # wrap the incoming masker object as a shap.Masker object
      if isinstance(masker, pd.DataFrame) or (
          (
              isinstance(masker, np.ndarray)
              or scipy.sparse.issparse(masker)
          )
          and len(masker.shape) == 2
      ):
          if algorithm == "partition":
              self.masker = maskers.Partition(masker)
          else:
              self.masker = maskers.Independent(masker)
      elif safe_isinstance(
          masker,
          [
              "transformers.PreTrainedTokenizer",
              "transformers.tokenization_utils_base.PreTrainedTokenizerBase",
          ],
      ):
          if is_transformers_lm(self.model):
              # auto assign text infilling if model is a transformer model with lm head
              self.masker = maskers.Text(
                  masker, mask_token="...", collapse_mask_token=True
              )
          else:
              self.masker = maskers.Text(masker)
      elif (masker is list or masker is tuple) and masker[0] is not str:
          self.masker = maskers.Composite(*masker)
      elif (masker is dict) and ("mean" in masker):
          self.masker = maskers.Independent(masker)
      elif masker is None and isinstance(
          self.model, models.TransformersPipeline
      ):
          return self.__init__(
              self.model,
              self.model.inner_model.tokenizer,
              link=link,
              algorithm=algorithm,
              output_names=output_names,
              feature_names=feature_names,
              linearize_link=linearize_link,
              **kwargs,
          )
      else:
          self.masker = masker
  
      # Check for transformer pipeline objects and wrap them
      if safe_isinstance(self.model, "transformers.pipelines.Pipeline"):
          if is_transformers_lm(self.model.model):
              return self.__init__(
                  self.model.model,
                  self.model.tokenizer
                  if self.masker is None
                  else self.masker,
                  link=link,
                  algorithm=algorithm,
                  output_names=output_names,
                  feature_names=feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          else:
              return self.__init__(
                  models.TransformersPipeline(self.model),
                  self.masker,
                  link=link,
                  algorithm=algorithm,
                  output_names=output_names,
                  feature_names=feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
  
      # wrap self.masker and self.model for output text explanation algorithm
      if is_transformers_lm(self.model):
          self.model = models.TeacherForcing(
              self.model, self.masker.tokenizer
          )
          self.masker = maskers.OutputComposite(
              self.masker, self.model.text_generate
          )
      elif safe_isinstance(
          self.model, "shap.models.TeacherForcing"
      ) and safe_isinstance(
          self.masker, ["shap.maskers.Text", "shap.maskers.Image"]
      ):
          self.masker = maskers.OutputComposite(
              self.masker, self.model.text_generate
          )
      elif safe_isinstance(
          self.model, "shap.models.TopKLM"
      ) and safe_isinstance(self.masker, "shap.maskers.Text"):
          self.masker = maskers.FixedComposite(self.masker)
  
      # self._brute_force_fallback = explainers.BruteForce(self.model, self.masker)
  
      # validate and save the link function
      if callable(link):
          self.link = link
      else:
          raise TypeError(
              "The passed link function needs to be callable!"
          )
      self.linearize_link = linearize_link
  
      # if we are called directly (as opposed to through super()) then we convert ourselves to the subclass
      # that implements the specific algorithm that was chosen
      if self.__class__ is Explainer:
          # do automatic algorithm selection
          # from .. import explainers
          if algorithm == "auto":
              # use implementation-aware methods if possible
              if explainers.LinearExplainer.supports_model_with_masker(
                  model, self.masker
              ):
                  algorithm = "linear"
              elif explainers.TreeExplainer.supports_model_with_masker(
                  model, self.masker
              ):  # TODO: check for Partition?
                  algorithm = "tree"
              elif explainers.AdditiveExplainer.supports_model_with_masker(
                  model, self.masker
              ):
                  algorithm = "additive"
  
              # otherwise use a model agnostic method
              elif callable(self.model):
                  if issubclass(type(self.masker), maskers.Independent):
                      if self.masker.shape[1] <= 10:
                          algorithm = "exact"
                      else:
                          algorithm = "permutation"
                  elif issubclass(type(self.masker), maskers.Partition):
                      if self.masker.shape[1] <= 32:
                          algorithm = "exact"
                      else:
                          algorithm = "permutation"
                  elif (
                      getattr(self.masker, "text_data", False)
                      or getattr(self.masker, "image_data", False)
                  ) and hasattr(self.masker, "clustering"):
                      algorithm = "partition"
                  else:
                      algorithm = "permutation"
  
              # if we get here then we don't know how to handle what was given to us
              else:
                  raise TypeError(
                      "The passed model is not callable and cannot be analyzed directly with the given masker! Model: "
                      + str(model)
                  )
  
          # build the right subclass
          if algorithm == "exact":
              self.__class__ = explainers.ExactExplainer
              explainers.ExactExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          elif algorithm == "permutation":
              self.__class__ = explainers.PermutationExplainer
              explainers.PermutationExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  seed=seed,
                  **kwargs,
              )
          elif algorithm == "partition":
              self.__class__ = explainers.PartitionExplainer
              explainers.PartitionExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  output_names=self.output_names,
                  **kwargs,
              )
          elif algorithm == "tree":
              self.__class__ = explainers.TreeExplainer
              explainers.TreeExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          elif algorithm == "additive":
              self.__class__ = explainers.AdditiveExplainer
              explainers.AdditiveExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          elif algorithm == "linear":
              self.__class__ = explainers.LinearExplainer
              explainers.LinearExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          elif algorithm == "deep":
              self.__class__ = explainers.DeepExplainer
              explainers.DeepExplainer.__init__(
                  self,
                  self.model,
                  self.masker,
                  link=self.link,
                  feature_names=self.feature_names,
                  linearize_link=linearize_link,
                  **kwargs,
              )
          else:
              raise InvalidAlgorithmError(
                  "Unknown algorithm type passed: %s!" % algorithm
              )
  
imports: import copy
  import time
  import numpy
  import pandas
  import scipy.sparse
  from ..None import explainers, links, maskers, models
  from .._explanation import Explanation
  from .._serializable import Deserializer, Serializable, Serializer
  from ..maskers import Masker
  from ..models import Model
  from ..utils import safe_isinstance, show_progress
  from ..utils._exceptions import InvalidAlgorithmError
  from ..utils.transformers import is_transformers_lm
label_desc: Use image node_id 1 to create a new Explainer object from inherited base classes: Serializable with example: obj = Explainer(model, masker, link, algorithm, output_names, feature_names, linearize_link, seed)