docstr: Explain instance and return anchor with metadata.
  
  Parameters
  ----------
  text
      Text instance to be explained.
  threshold
      Minimum anchor precision threshold. The algorithm tries to find an anchor that maximizes the coverage
      under precision constraint. The precision constraint is formally defined as
      :math:`P(prec(A) \ge t) \ge 1 - \delta`, where :math:`A` is an anchor, :math:`t` is the `threshold`
      parameter, :math:`\delta` is the `delta` parameter, and :math:`prec(\cdot)` denotes the precision
      of an anchor. In other words, we are seeking for an anchor having its precision greater or equal than
      the given `threshold` with a confidence of `(1 - delta)`. A higher value guarantees that the anchors are
      faithful to the model, but also leads to more computation time. Note that there are cases in which the
      precision constraint cannot be satisfied due to the quantile-based discretisation of the numerical
      features. If that is the case, the best (i.e. highest coverage) non-eligible anchor is returned.
  delta
      Significance threshold. `1 - delta` represents the confidence threshold for the anchor precision
      (see `threshold`) and the selection of the best anchor candidate in each iteration (see `tau`).
  tau
      Multi-armed bandit parameter used to select candidate anchors in each iteration. The multi-armed bandit
      algorithm tries to find within a tolerance `tau` the most promising (i.e. according to the precision)
      `beam_size` candidate anchor(s) from a list of proposed anchors. Formally, when the `beam_size=1`,
      the multi-armed bandit algorithm seeks to find an anchor :math:`A` such that
      :math:`P(prec(A) \ge prec(A^\star) - \tau) \ge 1 - \delta`, where :math:`A^\star` is the anchor
      with the highest true precision (which we don't know), :math:`\tau` is the `tau` parameter,
      :math:`\delta` is the `delta` parameter, and :math:`prec(\cdot)` denotes the precision of an anchor.
      In other words, in each iteration, the algorithm returns with a probability of at least `1 - delta` an
      anchor :math:`A` with a precision within an error tolerance of `tau` from the precision of the
      highest true precision anchor :math:`A^\star`. A bigger value for `tau` means faster convergence but also
      looser anchor conditions.
  batch_size
      Batch size used for sampling. The Anchor algorithm will query the black-box model in batches of size
      `batch_size`. A larger `batch_size` gives more confidence in the anchor, again at the expense of
      computation time since it involves more model prediction calls.
  coverage_samples
      Number of samples used to estimate coverage from during anchor search.
  beam_size
      Number of candidate anchors selected by the multi-armed bandit algorithm in each iteration from a list of
      proposed anchors. A bigger beam  width can lead to a better overall anchor (i.e. prevents the algorithm
      of getting stuck in a local maximum) at the expense of more computation time.
  stop_on_first
      If ``True``, the beam search algorithm will return the first anchor that has satisfies the
      probability constraint.
  max_anchor_size
      Maximum number of features to include in an anchor.
  min_samples_start
      Number of samples used for anchor search initialisation.
  n_covered_ex
      How many examples where anchors apply to store for each anchor sampled during search
      (both examples where prediction on samples agrees/disagrees with predicted label are stored).
  binary_cache_size
      The anchor search pre-allocates `binary_cache_size` batches for storing the boolean arrays
      returned during sampling.
  cache_margin
      When only ``max(cache_margin, batch_size)`` positions in the binary cache remain empty, a new cache
      of the same size is pre-allocated to continue buffering samples.
  verbose
      Display updates during the anchor search iterations.
  verbose_every
      Frequency of displayed iterations during anchor search process.
  **kwargs
      Other keyword arguments passed to the anchor beam search and the text sampling and perturbation functions.
  
  Returns
  -------
  `Explanation` object containing the anchor explaining the instance with additional metadata as attributes.         Contains the following data-related attributes
  
   - `anchor` : ``List[str]`` - a list of words in the proposed anchor.
  
   - `precision` : ``float`` - the fraction of times the sampled instances where the anchor holds yields          the same prediction as the original instance. The precision will always be  threshold for a valid anchor.
  
   - `coverage` : ``float`` - the fraction of sampled instances the anchor applies to.
docstr_tok: ["Explain","instance","and","return","anchor","with","metadata",".","Parameters","--","--","--","--","--","text","Text","instance","to","be","explained",".","threshold","Minimum","anchor","precision","threshold",".","The","algorithm","tries","to","find","an","anchor","that","maximizes","the","coverage","under","precision","constraint",".","The","precision","constraint","is","formally","defined","as",":","math",":","`","P","(","prec","(","A",")","\\ge","t",")","\\ge","1","-","\\delta","`",",","where",":","math",":","`","A","`","is","an","anchor",",",":","math",":","`","t","`","is","the","`","threshold","`","parameter",",",":","math",":","`","\\delta","`","is","the","`","delta","`","parameter",",","and",":","math",":","`","prec","(","\\cdot",")","`","denotes","the","precision","of","an","anchor",".","In","other","words",",","we","are","seeking","for","an","anchor","having","its","precision","greater","or","equal","than","the","given","`","threshold","`","with","a","confidence","of","`","(","1","-","delta",")","`",".","A","higher","value","guarantees","that","the","anchors","are","faithful","to","the","model",",","but","also","leads","to","more","computation","time",".","Note","that","there","are","cases","in","which","the","precision","constraint","can","not","be","satisfied","due","to","the","quantile-based","discretisation","of","the","numerical","features",".","If","that","is","the","case",",","the","best","(","i.e",".","highest","coverage",")","non-eligible","anchor","is","returned",".","delta","Significance","threshold",".","`","1","-","delta","`","represents","the","confidence","threshold","for","the","anchor","precision","(","see","`","threshold","`",")","and","the","selection","of","the","best","anchor","candidate","in","each","iteration","(","see","`","tau","`",")",".","tau","Multi-armed","bandit","parameter","used","to","select","candidate","anchors","in","each","iteration",".","The","multi-armed","bandit","algorithm","tries","to","find","within","a","tolerance","`","tau","`","the","most","promising","(","i.e",".","according","to","the","precision",")","`","beam_size","`","candidate","anchor","(","s",")","from","a","list","of","proposed","anchors",".","Formally",",","when","the","`","beam_size=1","`",",","the","multi-armed","bandit","algorithm","seeks","to","find","an","anchor",":","math",":","`","A","`","such","that",":","math",":","`","P","(","prec","(","A",")","\\ge","prec","(","A^\\star",")","-","\\tau",")","\\ge","1","-","\\delta","`",",","where",":","math",":","`","A^\\star","`","is","the","anchor","with","the","highest","true","precision","(","which","we","do","n't","know",")",",",":","math",":","`","\\tau","`","is","the","`","tau","`","parameter",",",":","math",":","`","\\delta","`","is","the","`","delta","`","parameter",",","and",":","math",":","`","prec","(","\\cdot",")","`","denotes","the","precision","of","an","anchor",".","In","other","words",",","in","each","iteration",",","the","algorithm","returns","with","a","probability","of","at","least","`","1","-","delta","`","an","anchor",":","math",":","`","A","`","with","a","precision","within","an","error","tolerance","of","`","tau","`","from","the","precision","of","the","highest","true","precision","anchor",":","math",":","`","A^\\star","`",".","A","bigger","value","for","`","tau","`","means","faster","convergence","but","also","looser","anchor","conditions",".","batch_size","Batch","size","used","for","sampling",".","The","Anchor","algorithm","will","query","the","black-box","model","in","batches","of","size","`","batch_size","`",".","A","larger","`","batch_size","`","gives","more","confidence","in","the","anchor",",","again","at","the","expense","of","computation","time","since","it","involves","more","model","prediction","calls",".","coverage_samples","Number","of","samples","used","to","estimate","coverage","from","during","anchor","search",".","beam_size","Number","of","candidate","anchors","selected","by","the","multi-armed","bandit","algorithm","in","each","iteration","from","a","list","of","proposed","anchors",".","A","bigger","beam","width","can","lead","to","a","better","overall","anchor","(","i.e",".","prevents","the","algorithm","of","getting","stuck","in","a","local","maximum",")","at","the","expense","of","more","computation","time",".","stop_on_first","If","``","True","``",",","the","beam","search","algorithm","will","return","the","first","anchor","that","has","satisfies","the","probability","constraint",".","max_anchor_size","Maximum","number","of","features","to","include","in","an","anchor",".","min_samples_start","Number","of","samples","used","for","anchor","search","initialisation",".","n_covered_ex","How","many","examples","where","anchors","apply","to","store","for","each","anchor","sampled","during","search","(","both","examples","where","prediction","on","samples","agrees\/disagrees","with","predicted","label","are","stored",")",".","binary_cache_size","The","anchor","search","pre-allocates","`","binary_cache_size","`","batches","for","storing","the","boolean","arrays","returned","during","sampling",".","cache_margin","When","only","``","max","(","cache_margin",",","batch_size",")","``","positions","in","the","binary","cache","remain","empty",",","a","new","cache","of","the","same","size","is","pre-allocated","to","continue","buffering","samples",".","verbose","Display","updates","during","the","anchor","search","iterations",".","verbose_every","Frequency","of","displayed","iterations","during","anchor","search","process",".","*","*","kwargs","Other","keyword","arguments","passed","to","the","anchor","beam","search","and","the","text","sampling","and","perturbation","functions",".","Returns","--","--","--","-","`","Explanation","`","object","containing","the","anchor","explaining","the","instance","with","additional","metadata","as","attributes",".","Contains","the","following","data-related","attributes","-","`","anchor","`",":","``","List","[","str","]","``","-","a","list","of","words","in","the","proposed","anchor",".","-","`","precision","`",":","``","float","``","-","the","fraction","of","times","the","sampled","instances","where","the","anchor","holds","yields","the","same","prediction","as","the","original","instance",".","The","precision","will","always","be","threshold","for","a","valid","anchor",".","-","`","coverage","`",":","``","float","``","-","the","fraction","of","sampled","instances","the","anchor","applies","to","."]
code: def explain(
      self,  # type: ignore[override]
      text: str,
      threshold: float = 0.95,
      delta: float = 0.1,
      tau: float = 0.15,
      batch_size: int = 100,
      coverage_samples: int = 10000,
      beam_size: int = 1,
      stop_on_first: bool = True,
      max_anchor_size: Optional[int] = None,
      min_samples_start: int = 100,
      n_covered_ex: int = 10,
      binary_cache_size: int = 10000,
      cache_margin: int = 1000,
      verbose: bool = False,
      verbose_every: int = 1,
      **kwargs: Any,
  ) -> Explanation:
      """
          Explain instance and return anchor with metadata.
  
          Parameters
          ----------
          text
              Text instance to be explained.
          threshold
              Minimum anchor precision threshold. The algorithm tries to find an anchor that maximizes the coverage
              under precision constraint. The precision constraint is formally defined as
              :math:`P(prec(A) \\ge t) \\ge 1 - \\delta`, where :math:`A` is an anchor, :math:`t` is the `threshold`
              parameter, :math:`\\delta` is the `delta` parameter, and :math:`prec(\\cdot)` denotes the precision
              of an anchor. In other words, we are seeking for an anchor having its precision greater or equal than
              the given `threshold` with a confidence of `(1 - delta)`. A higher value guarantees that the anchors are
              faithful to the model, but also leads to more computation time. Note that there are cases in which the
              precision constraint cannot be satisfied due to the quantile-based discretisation of the numerical
              features. If that is the case, the best (i.e. highest coverage) non-eligible anchor is returned.
          delta
              Significance threshold. `1 - delta` represents the confidence threshold for the anchor precision
              (see `threshold`) and the selection of the best anchor candidate in each iteration (see `tau`).
          tau
              Multi-armed bandit parameter used to select candidate anchors in each iteration. The multi-armed bandit
              algorithm tries to find within a tolerance `tau` the most promising (i.e. according to the precision)
              `beam_size` candidate anchor(s) from a list of proposed anchors. Formally, when the `beam_size=1`,
              the multi-armed bandit algorithm seeks to find an anchor :math:`A` such that
              :math:`P(prec(A) \\ge prec(A^\\star) - \\tau) \\ge 1 - \\delta`, where :math:`A^\\star` is the anchor
              with the highest true precision (which we don't know), :math:`\\tau` is the `tau` parameter,
              :math:`\\delta` is the `delta` parameter, and :math:`prec(\\cdot)` denotes the precision of an anchor.
              In other words, in each iteration, the algorithm returns with a probability of at least `1 - delta` an
              anchor :math:`A` with a precision within an error tolerance of `tau` from the precision of the
              highest true precision anchor :math:`A^\\star`. A bigger value for `tau` means faster convergence but also
              looser anchor conditions.
          batch_size
              Batch size used for sampling. The Anchor algorithm will query the black-box model in batches of size
              `batch_size`. A larger `batch_size` gives more confidence in the anchor, again at the expense of
              computation time since it involves more model prediction calls.
          coverage_samples
              Number of samples used to estimate coverage from during anchor search.
          beam_size
              Number of candidate anchors selected by the multi-armed bandit algorithm in each iteration from a list of
              proposed anchors. A bigger beam  width can lead to a better overall anchor (i.e. prevents the algorithm
              of getting stuck in a local maximum) at the expense of more computation time.
          stop_on_first
              If ``True``, the beam search algorithm will return the first anchor that has satisfies the
              probability constraint.
          max_anchor_size
              Maximum number of features to include in an anchor.
          min_samples_start
              Number of samples used for anchor search initialisation.
          n_covered_ex
              How many examples where anchors apply to store for each anchor sampled during search
              (both examples where prediction on samples agrees/disagrees with predicted label are stored).
          binary_cache_size
              The anchor search pre-allocates `binary_cache_size` batches for storing the boolean arrays
              returned during sampling.
          cache_margin
              When only ``max(cache_margin, batch_size)`` positions in the binary cache remain empty, a new cache
              of the same size is pre-allocated to continue buffering samples.
          verbose
              Display updates during the anchor search iterations.
          verbose_every
              Frequency of displayed iterations during anchor search process.
          **kwargs
              Other keyword arguments passed to the anchor beam search and the text sampling and perturbation functions.
  
          Returns
          -------
          `Explanation` object containing the anchor explaining the instance with additional metadata as attributes. \
          Contains the following data-related attributes
  
           - `anchor` : ``List[str]`` - a list of words in the proposed anchor.
  
           - `precision` : ``float`` - the fraction of times the sampled instances where the anchor holds yields \
           the same prediction as the original instance. The precision will always be  threshold for a valid anchor.
  
           - `coverage` : ``float`` - the fraction of sampled instances the anchor applies to.
          """
      # get params for storage in meta
      params = locals()
      remove = ["text", "self"]
      for key in remove:
          params.pop(key)
  
      params = deepcopy(
          params
      )  # Get a reference to itself if not deepcopy for LM sampler
  
      # store n_covered_ex positive/negative examples for each anchor
      self.n_covered_ex = n_covered_ex
      self.instance_label = self.predictor([text])[0]
  
      # set sampler
      self.perturbation.set_text(text)
  
      # get anchors and add metadata
      mab = AnchorBaseBeam(
          samplers=[self.sampler],
          sample_cache_size=binary_cache_size,
          cache_margin=cache_margin,
          **kwargs,
      )
  
      result: Any = mab.anchor_beam(
          delta=delta,
          epsilon=tau,
          batch_size=batch_size,
          desired_confidence=threshold,
          max_anchor_size=max_anchor_size,
          min_samples_start=min_samples_start,
          beam_size=beam_size,
          coverage_samples=coverage_samples,
          stop_on_first=stop_on_first,
          verbose=verbose,
          verbose_every=verbose_every,
          **kwargs,
      )
  
      if self.sampling_strategy == self.SAMPLING_LANGUAGE_MODEL:
          # take the whole word (this points just to the first part of the word)
          result["positions"] = [
              self.perturbation.ids_mapping[i]
              for i in result["feature"]
          ]
          result["names"] = [
              self.perturbation.model.select_word(
                  self.perturbation.head_tokens,
                  idx_feature,
                  self.perturbation.perturb_opts["punctuation"],
              )
              for idx_feature in result["positions"]
          ]
      else:
          result["names"] = [
              self.perturbation.words[x] for x in result["feature"]
          ]
          result["positions"] = [
              self.perturbation.positions[x] for x in result["feature"]
          ]
  
      # set mab
      self.mab = mab
      return self._build_explanation(
          text, result, self.instance_label, params
      )
  
imports: import copy
  import logging
  import string
  from copy import deepcopy
  from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
  import numpy
  import spacy
  from alibi.utils.missing_optional_dependency import import_optional
  from alibi.api.defaults import DEFAULT_DATA_ANCHOR, DEFAULT_META_ANCHOR
  from alibi.api.interfaces import Explainer, Explanation
  from alibi.exceptions import PredictorCallError, PredictorReturnTypeError
  from alibi.utils.wrappers import ArgmaxTransformer
  from .anchor_base import AnchorBaseBeam
  from .anchor_explanation import AnchorExplanation
  from .text_samplers import UnknownSampler, SimilaritySampler, load_spacy_lexeme_prob
label_desc: Use image node_id 5 for calling the AnchorText obj's underlying member method code with example usage: obj.explain(text, threshold, delta, tau, batch_size, coverage_samples, beam_size, stop_on_first, max_anchor_size, min_samples_start, n_covered_ex, binary_cache_size, cache_margin, verbose, verbose_every) and returns: self