docstr: Generates diverse counterfactual explanations
  
  :param query_instance: A dictionary of feature names and values. Test point of interest.
  :param total_CFs: Total number of counterfactuals required.
  :param desired_range: For regression problems. Contains the outcome range to generate counterfactuals in.
  :param desired_class: Desired counterfactual class - can take 0 or 1. Default value is "opposite" to the
                        outcome class of query_instance for binary classification.
  :param features_to_vary: Either a string "all" or a list of feature names to vary.
  :param permitted_range: Dictionary with continuous feature names as keys and permitted min-max range in
                          list as values. Defaults to the range inferred from training data.
                          If None, uses the parameters initialized in data_interface.
  :param sparsity_weight: Parameter to determine how much importance to give to sparsity
  :param feature_weights: Either "inverse_mad" or a dictionary with feature names as keys and corresponding
                          weights as values. Default option is "inverse_mad" where the weight for a continuous
                          feature is the inverse of the Median Absolute Devidation (MAD) of the feature's
                          values in the training set; the weight for a categorical feature is equal to 1 by default.
  :param stopping_threshold: Minimum threshold for counterfactuals target class probability.
  :param posthoc_sparsity_param: Parameter for the post-hoc operation on continuous features to enhance sparsity.
  :param posthoc_sparsity_algorithm: Perform either linear or binary search. Takes "linear" or "binary".
                                     Prefer binary search when a feature range is large (for instance, income
                                     varying from 10k to 1000k) and only if the features share a monotonic
                                     relationship with predicted outcome in the model.
  :param verbose: Parameter to determine whether to print 'Diverse Counterfactuals found!'
  :param limit_steps_ls: Defines an upper limit for the linear search step in the posthoc_sparsity_enhancement
  
  :return: A CounterfactualExamples object to store and visualize the resulting counterfactual explanations
           (see diverse_counterfactuals.py).
docstr_tok: ["Generates","diverse","counterfactual","explanations",":","param","query_instance",":","A","dictionary","of","feature","names","and","values",".","Test","point","of","interest",".",":","param","total_CFs",":","Total","number","of","counterfactuals","required",".",":","param","desired_range",":","For","regression","problems",".","Contains","the","outcome","range","to","generate","counterfactuals","in",".",":","param","desired_class",":","Desired","counterfactual","class","-","can","take","0","or","1",".","Default","value","is","``","opposite","''","to","the","outcome","class","of","query_instance","for","binary","classification",".",":","param","features_to_vary",":","Either","a","string","``","all","''","or","a","list","of","feature","names","to","vary",".",":","param","permitted_range",":","Dictionary","with","continuous","feature","names","as","keys","and","permitted","min-max","range","in","list","as","values",".","Defaults","to","the","range","inferred","from","training","data",".","If","None",",","uses","the","parameters","initialized","in","data_interface",".",":","param","sparsity_weight",":","Parameter","to","determine","how","much","importance","to","give","to","sparsity",":","param","feature_weights",":","Either","``","inverse_mad","''","or","a","dictionary","with","feature","names","as","keys","and","corresponding","weights","as","values",".","Default","option","is","``","inverse_mad","''","where","the","weight","for","a","continuous","feature","is","the","inverse","of","the","Median","Absolute","Devidation","(","MAD",")","of","the","feature's","values","in","the","training","set",";","the","weight","for","a","categorical","feature","is","equal","to","1","by","default",".",":","param","stopping_threshold",":","Minimum","threshold","for","counterfactuals","target","class","probability",".",":","param","posthoc_sparsity_param",":","Parameter","for","the","post-hoc","operation","on","continuous","features","to","enhance","sparsity",".",":","param","posthoc_sparsity_algorithm",":","Perform","either","linear","or","binary","search",".","Takes","``","linear","''","or","``","binary","''",".","Prefer","binary","search","when","a","feature","range","is","large","(","for","instance",",","income","varying","from","10k","to","1000k",")","and","only","if","the","features","share","a","monotonic","relationship","with","predicted","outcome","in","the","model",".",":","param","verbose",":","Parameter","to","determine","whether","to","print","'Diverse","Counterfactuals","found","!","'",":","param","limit_steps_ls",":","Defines","an","upper","limit","for","the","linear","search","step","in","the","posthoc_sparsity_enhancement",":","return",":","A","CounterfactualExamples","object","to","store","and","visualize","the","resulting","counterfactual","explanations","(","see","diverse_counterfactuals.py",")","."]
code: def _generate_counterfactuals(
      self,
      query_instance,
      total_CFs,
      desired_range=None,
      desired_class="opposite",
      features_to_vary="all",
      permitted_range=None,
      sparsity_weight=1,
      feature_weights="inverse_mad",
      stopping_threshold=0.5,
      posthoc_sparsity_param=0.1,
      posthoc_sparsity_algorithm="linear",
      verbose=False,
      limit_steps_ls=10000,
  ):
      """Generates diverse counterfactual explanations
  
      :param query_instance: A dictionary of feature names and values. Test point of interest.
      :param total_CFs: Total number of counterfactuals required.
      :param desired_range: For regression problems. Contains the outcome range to generate counterfactuals in.
      :param desired_class: Desired counterfactual class - can take 0 or 1. Default value is "opposite" to the
                            outcome class of query_instance for binary classification.
      :param features_to_vary: Either a string "all" or a list of feature names to vary.
      :param permitted_range: Dictionary with continuous feature names as keys and permitted min-max range in
                              list as values. Defaults to the range inferred from training data.
                              If None, uses the parameters initialized in data_interface.
      :param sparsity_weight: Parameter to determine how much importance to give to sparsity
      :param feature_weights: Either "inverse_mad" or a dictionary with feature names as keys and corresponding
                              weights as values. Default option is "inverse_mad" where the weight for a continuous
                              feature is the inverse of the Median Absolute Devidation (MAD) of the feature's
                              values in the training set; the weight for a categorical feature is equal to 1 by default.
      :param stopping_threshold: Minimum threshold for counterfactuals target class probability.
      :param posthoc_sparsity_param: Parameter for the post-hoc operation on continuous features to enhance sparsity.
      :param posthoc_sparsity_algorithm: Perform either linear or binary search. Takes "linear" or "binary".
                                         Prefer binary search when a feature range is large (for instance, income
                                         varying from 10k to 1000k) and only if the features share a monotonic
                                         relationship with predicted outcome in the model.
      :param verbose: Parameter to determine whether to print 'Diverse Counterfactuals found!'
      :param limit_steps_ls: Defines an upper limit for the linear search step in the posthoc_sparsity_enhancement
  
      :return: A CounterfactualExamples object to store and visualize the resulting counterfactual explanations
               (see diverse_counterfactuals.py).
      """
      data_df_copy = self.data_interface.data_df.copy()
  
      features_to_vary = self.setup(
          features_to_vary,
          permitted_range,
          query_instance,
          feature_weights,
      )
  
      # Prepares user defined query_instance for DiCE.
      query_instance_orig = query_instance.copy()
      query_instance_orig = self.data_interface.prepare_query_instance(
          query_instance=query_instance_orig
      )
      query_instance = self.data_interface.prepare_query_instance(
          query_instance=query_instance
      )
  
      # find the predicted value of query_instance
      test_pred = self.predict_fn_scores(query_instance)
      query_instance[
          self.data_interface.outcome_name
      ] = self.get_model_output_from_scores(test_pred)
      desired_class = self.misc_init(
          stopping_threshold, desired_class, desired_range, test_pred[0]
      )
  
      if (
          desired_class == "opposite"
          and self.model.model_type == ModelTypes.Classifier
      ):
          if self.num_output_nodes == 2:
              desired_class = 1.0 - test_pred
  
          elif self.num_output_nodes > 2:
              raise ValueError(
                  "Desired class can't be opposite if the number of classes is more than 2."
              )
  
      if (
          isinstance(desired_class, int)
          and desired_class > self.num_output_nodes - 1
      ):
          raise ValueError(
              "Desired class should be within 0 and num_classes-1."
          )
  
      # Partitioned dataset and KD Tree for each class (binary) of the dataset
      (
          self.dataset_with_predictions,
          self.KD_tree,
          self.predictions,
      ) = self.build_KD_tree(
          data_df_copy,
          desired_range,
          desired_class,
          self.predicted_outcome_name,
      )
      query_instance, cfs_preds = self.find_counterfactuals(
          data_df_copy,
          query_instance,
          query_instance_orig,
          desired_range,
          desired_class,
          total_CFs,
          features_to_vary,
          permitted_range,
          sparsity_weight,
          stopping_threshold,
          posthoc_sparsity_param,
          posthoc_sparsity_algorithm,
          verbose,
          limit_steps_ls,
      )
      self.cfs_preds = cfs_preds
      if self.final_cfs_df is not None:
          self.final_cfs_df[
              self.data_interface.outcome_name
          ] = self.cfs_preds
  
      # decoding to original label
      (
          query_instance,
          self.final_cfs_df,
          self.final_cfs_df_sparse,
      ) = self.decode_to_original_labels(
          query_instance, self.final_cfs_df, self.final_cfs_df_sparse
      )
      desired_class_param = (
          self.decode_model_output(pd.Series(self.target_cf_class[0]))[
              0
          ]
          if hasattr(self, "target_cf_class")
          else desired_class
      )
      return exp.CounterfactualExamples(
          data_interface=self.data_interface,
          final_cfs_df=self.final_cfs_df,
          test_instance_df=query_instance,
          final_cfs_df_sparse=self.final_cfs_df_sparse,
          posthoc_sparsity_param=posthoc_sparsity_param,
          desired_range=desired_range,
          desired_class=desired_class_param,
          model_type=self.model.model_type,
      )
  
file_path: DiCE/dice_ml/explainer_interfaces/dice_KD.py
imports: import copy
  import timeit
  import numpy
  import pandas
  from dice_ml import diverse_counterfactuals
  from dice_ml.constants import ModelTypes
  from dice_ml.explainer_interfaces.explainer_base import ExplainerBase
label_desc: Use image node_id 2 for calling the DiceKD obj's underlying member method code with example usage: obj._generate_counterfactuals(query_instance, total_CFs, desired_range, desired_class, features_to_vary, permitted_range, sparsity_weight, feature_weights, stopping_threshold, posthoc_sparsity_param, posthoc_sparsity_algorithm, verbose, limit_steps_ls) and returns: exp