class_docstr: Counterfactual Reinforcement Learning Tabular. 
class_docstr_tok: ["Counterfactual","Reinforcement","Learning","Tabular","."]
docstr: Generates a set of diverse counterfactuals given a single instance, target and conditioning.
  
  Parameters
  ----------
  X
      Input instance.
  Y_t
      Target label.
  C
      List of conditional dictionaries. If ``None``, it means that no conditioning was used during training
      (i.e. the `conditional_func` returns ``None``).
  num_samples
      Number of counterfactual samples to be generated.
  batch_size
      Batch size used at inference.
  num_samples
      Number of diversity samples to be generated. Considered only if ``diversity=True``.
  batch_size
      Batch size to use when generating counterfactuals.
  patience
      Maximum number of iterations to perform diversity search stops. If -1, the search stops only if
      the desired number of samples has been found.
  tolerance
      Tolerance to distinguish two counterfactual instances.
  
  Returns
  -------
  Explanation object containing the diverse counterfactuals.
docstr_tok: ["Generates","a","set","of","diverse","counterfactuals","given","a","single","instance",",","target","and","conditioning",".","Parameters","--","--","--","--","--","X","Input","instance",".","Y_t","Target","label",".","C","List","of","conditional","dictionaries",".","If","``","None","``",",","it","means","that","no","conditioning","was","used","during","training","(","i.e",".","the","`","conditional_func","`","returns","``","None","``",")",".","num_samples","Number","of","counterfactual","samples","to","be","generated",".","batch_size","Batch","size","used","at","inference",".","num_samples","Number","of","diversity","samples","to","be","generated",".","Considered","only","if","``","diversity=True","``",".","batch_size","Batch","size","to","use","when","generating","counterfactuals",".","patience","Maximum","number","of","iterations","to","perform","diversity","search","stops",".","If","-1",",","the","search","stops","only","if","the","desired","number","of","samples","has","been","found",".","tolerance","Tolerance","to","distinguish","two","counterfactual","instances",".","Returns","--","--","--","-","Explanation","object","containing","the","diverse","counterfactuals","."]
code: def _diversity(
      self,
      X: np.ndarray,
      Y_t: np.ndarray,
      C: Optional[List[Dict[str, List[Union[str, float]]]]],
      num_samples: int = 1,
      batch_size: int = 100,
      patience: int = 1000,
      tolerance: float = 1e-3,
  ) -> Explanation:
      """
      Generates a set of diverse counterfactuals given a single instance, target and conditioning.
  
      Parameters
      ----------
      X
          Input instance.
      Y_t
          Target label.
      C
          List of conditional dictionaries. If ``None``, it means that no conditioning was used during training
          (i.e. the `conditional_func` returns ``None``).
      num_samples
          Number of counterfactual samples to be generated.
      batch_size
          Batch size used at inference.
      num_samples
          Number of diversity samples to be generated. Considered only if ``diversity=True``.
      batch_size
          Batch size to use when generating counterfactuals.
      patience
          Maximum number of iterations to perform diversity search stops. If -1, the search stops only if
          the desired number of samples has been found.
      tolerance
          Tolerance to distinguish two counterfactual instances.
  
      Returns
      -------
      Explanation object containing the diverse counterfactuals.
      """
      # Check if condition. If no conditioning was used during training, the method can not generate a diverse
      # set of counterfactual instances
      if C is None:
          raise ValueError(
              "A diverse set of counterfactual can not be generated if a `None` conditioning is "
              "used during training. Use the `explain` method to generate a counterfactual. The "
              "generation process is deterministic in its core. If conditioning is used during training "
              "a diverse set of counterfactual can be generated by restricting each feature condition "
              "to a subset to remain feasible."
          )
  
      # Check the number of inputs
      if X.shape[0] != 1:
          raise ValueError(
              "Only a single input instance can be passed."
          )
  
      # Check the number of labels.
      if Y_t.shape[0] != 1:
          raise ValueError("Only a single label can be passed.")
  
      # Check the number of conditions.
      if (C is not None) and len(C) > 1:
          raise ValueError("At most, one condition can be passed.")
  
      # Generate a batch of data.
      X_repeated = np.tile(X, (batch_size, 1))
      Y_t = np.tile(np.atleast_2d(Y_t), (batch_size, 1))
  
      # Define counterfactual buffer.
      X_cf_buff = None
  
      for i in tqdm(count()):
          if i == patience:
              break
  
          if (X_cf_buff is not None) and (
              X_cf_buff.shape[0] >= num_samples
          ):
              break
  
          # Generate conditional vector.
          C_vec = get_conditional_vector(
              X=X_repeated,
              condition=C[0] if len(C) else {},
              preprocessor=self.params["encoder_preprocessor"],
              feature_names=self.params["feature_names"],
              category_map=self.params["category_map"],
              stats=self.params["stats"],
              immutable_features=self.params["immutable_features"],
              diverse=True,
          )
  
          # Generate counterfactuals.
          results = self._compute_counterfactual(
              X=X_repeated, Y_t=Y_t, C=C_vec
          )
          X_cf, Y_m_cf, Y_t = results["X_cf"], results["Y_m_cf"], results["Y_t"]  # type: ignore[assignment]
          X_cf = cast(np.ndarray, X_cf)  # help mypy out
  
          # Select only counterfactuals where prediction matches the target.
          X_cf = X_cf[Y_t == Y_m_cf]
          X_cf = cast(np.ndarray, X_cf)  # help mypy out
  
          if X_cf.shape[0] == 0:
              continue
  
          # Find unique counterfactuals.
          _, indices = np.unique(
              np.floor(X_cf / tolerance).astype(int),
              return_index=True,
              axis=0,
          )
  
          # Add them to the unique buffer but make sure not to add duplicates.
          if X_cf_buff is None:
              X_cf_buff = X_cf[indices]
          else:
              X_cf_buff = np.concatenate(
                  [X_cf_buff, X_cf[indices]], axis=0
              )
              _, indices = np.unique(
                  np.floor(X_cf_buff / tolerance).astype(int),
                  return_index=True,
                  axis=0,
              )
              X_cf_buff = X_cf_buff[indices]
  
      # Construct counterfactuals to the explanation.
      X_cf = (
          X_cf_buff[:num_samples]
          if (X_cf_buff is not None)
          else np.array([])
      )
  
      # Compute model's prediction on the counterfactual instances
      Y_m_cf = (
          self.params["predictor"](X_cf)
          if X_cf.shape[0] != 0
          else np.array([])
      )
      if self._is_classification(pred=Y_m_cf):
          Y_m_cf = np.argmax(Y_m_cf, axis=1)
  
      # Compute model's prediction on the original input.
      Y_m = self.params["predictor"](X)
      if self._is_classification(Y_m):
          Y_m = np.argmax(Y_m, axis=1)
  
      # Update target representation if necessary.
      if self._is_classification(Y_t):
          Y_t = np.argmax(Y_t, axis=1)
  
      return self._build_explanation(
          X=X, Y_m=Y_m, X_cf=X_cf, Y_m_cf=Y_m_cf, Y_t=Y_t, C=C
      )
  
imports: from functools import partial
  from itertools import count
  from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Union, cast
  import numpy
  from tqdm import tqdm
  from alibi.api.interfaces import Explainer, Explanation
  from alibi.explainers.backends.cfrl_tabular import get_conditional_vector, get_statistics, sample
  from alibi.explainers.cfrl_base import _PARAM_TYPES, CounterfactualRL, Postprocessing
  from alibi.utils.frameworks import has_pytorch, has_tensorflow
label_desc: Use image node_id 6 for calling the CounterfactualRLTabular obj's underlying member method code with example usage: obj._diversity(X, Y_t, C, num_samples, batch_size, patience, tolerance) and returns: self