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 initialization: Method to use to initialize the population of the genetic algorithm
  :param desired_range: For regression problems. Contains the outcome range to generate counterfactuals in.
  :param desired_class: For classification problems. Desired counterfactual class - can take 0 or 1.
                        Default value is "opposite" to the outcome class of query_instance for binary classification.
  :param proximity_weight: A positive float. Larger this weight, more close the counterfactuals are to the
                           query_instance.
  :param sparsity_weight: A positive float. Larger this weight, less features are changed from the query_instance.
  :param diversity_weight: A positive float. Larger this weight, more diverse the counterfactuals are.
  :param categorical_penalty: A positive float. A weight to ensure that all levels of a categorical variable sums to 1.
  :param algorithm: Counterfactual generation algorithm. Either "DiverseCF" or "RandomInitCF".
  :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 yloss_type: Metric for y-loss of the optimization function. Takes "l2_loss" or "log_loss" or "hinge_loss".
  :param diversity_loss_type: Metric for diversity loss of the optimization function.
                              Takes "avg_dist" or "dpp_style:inverse_dist".
  :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 maxiterations: Maximum iterations to run the genetic algorithm for.
  :param thresh: The genetic algorithm stops when the difference between the previous best loss and current
                 best loss is less than thresh
  :param verbose: Parameter to determine whether to print 'Diverse Counterfactuals found!'
  
  :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","initialization",":","Method","to","use","to","initialize","the","population","of","the","genetic","algorithm",":","param","desired_range",":","For","regression","problems",".","Contains","the","outcome","range","to","generate","counterfactuals","in",".",":","param","desired_class",":","For","classification","problems",".","Desired","counterfactual","class","-","can","take","0","or","1",".","Default","value","is","``","opposite","''","to","the","outcome","class","of","query_instance","for","binary","classification",".",":","param","proximity_weight",":","A","positive","float",".","Larger","this","weight",",","more","close","the","counterfactuals","are","to","the","query_instance",".",":","param","sparsity_weight",":","A","positive","float",".","Larger","this","weight",",","less","features","are","changed","from","the","query_instance",".",":","param","diversity_weight",":","A","positive","float",".","Larger","this","weight",",","more","diverse","the","counterfactuals","are",".",":","param","categorical_penalty",":","A","positive","float",".","A","weight","to","ensure","that","all","levels","of","a","categorical","variable","sums","to","1.",":","param","algorithm",":","Counterfactual","generation","algorithm",".","Either","``","DiverseCF","''","or","``","RandomInitCF","''",".",":","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","yloss_type",":","Metric","for","y-loss","of","the","optimization","function",".","Takes","``","l2_loss","''","or","``","log_loss","''","or","``","hinge_loss","''",".",":","param","diversity_loss_type",":","Metric","for","diversity","loss","of","the","optimization","function",".","Takes","``","avg_dist","''","or","``","dpp_style",":","inverse_dist","''",".",":","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","maxiterations",":","Maximum","iterations","to","run","the","genetic","algorithm","for",".",":","param","thresh",":","The","genetic","algorithm","stops","when","the","difference","between","the","previous","best","loss","and","current","best","loss","is","less","than","thresh",":","param","verbose",":","Parameter","to","determine","whether","to","print","'Diverse","Counterfactuals","found","!","'",":","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,
      initialization="kdtree",
      desired_range=None,
      desired_class="opposite",
      proximity_weight=0.2,
      sparsity_weight=0.2,
      diversity_weight=5.0,
      categorical_penalty=0.1,
      algorithm="DiverseCF",
      features_to_vary="all",
      permitted_range=None,
      yloss_type="hinge_loss",
      diversity_loss_type="dpp_style:inverse_dist",
      feature_weights="inverse_mad",
      stopping_threshold=0.5,
      posthoc_sparsity_param=0.1,
      posthoc_sparsity_algorithm="binary",
      maxiterations=500,
      thresh=1e-2,
      verbose=False,
  ):
      """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 initialization: Method to use to initialize the population of the genetic algorithm
      :param desired_range: For regression problems. Contains the outcome range to generate counterfactuals in.
      :param desired_class: For classification problems. Desired counterfactual class - can take 0 or 1.
                            Default value is "opposite" to the outcome class of query_instance for binary classification.
      :param proximity_weight: A positive float. Larger this weight, more close the counterfactuals are to the
                               query_instance.
      :param sparsity_weight: A positive float. Larger this weight, less features are changed from the query_instance.
      :param diversity_weight: A positive float. Larger this weight, more diverse the counterfactuals are.
      :param categorical_penalty: A positive float. A weight to ensure that all levels of a categorical variable sums to 1.
      :param algorithm: Counterfactual generation algorithm. Either "DiverseCF" or "RandomInitCF".
      :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 yloss_type: Metric for y-loss of the optimization function. Takes "l2_loss" or "log_loss" or "hinge_loss".
      :param diversity_loss_type: Metric for diversity loss of the optimization function.
                                  Takes "avg_dist" or "dpp_style:inverse_dist".
      :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 maxiterations: Maximum iterations to run the genetic algorithm for.
      :param thresh: The genetic algorithm stops when the difference between the previous best loss and current
                     best loss is less than thresh
      :param verbose: Parameter to determine whether to print 'Diverse Counterfactuals found!'
  
      :return: A CounterfactualExamples object to store and visualize the resulting counterfactual explanations
               (see diverse_counterfactuals.py).
      """
  
      if (
          not hasattr(self.data_interface, "data_df")
          and initialization == "kdtree"
      ):
          raise UserConfigValidationException(
              "kd-tree initialization is not supported for private data"
              " interface because training data to build kd-tree is not available."
          )
  
      self.population_size = 10 * total_CFs
  
      self.start_time = timeit.default_timer()
  
      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
      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
      )
      # number of output nodes of ML model
      self.num_output_nodes = None
      if self.model.model_type == ModelTypes.Classifier:
          self.num_output_nodes = self.model.get_num_output_nodes2(
              query_instance
          )
  
      query_instance = self.label_encode(query_instance)
      query_instance = np.array(query_instance.values[0])
      self.x1 = query_instance
  
      # find the predicted value of query_instance
      test_pred = self.predict_fn_scores(query_instance)
  
      self.test_pred = test_pred
      desired_class = self.misc_init(
          stopping_threshold, desired_class, desired_range, test_pred[0]
      )
  
      query_instance_df_dummies = pd.get_dummies(query_instance_orig)
      for col in self.data_interface.get_all_dummy_colnames():
          if col not in query_instance_df_dummies.columns:
              query_instance_df_dummies[col] = 0
  
      self.do_param_initializations(
          total_CFs,
          initialization,
          desired_range,
          desired_class,
          query_instance,
          query_instance_df_dummies,
          algorithm,
          features_to_vary,
          permitted_range,
          yloss_type,
          diversity_loss_type,
          feature_weights,
          proximity_weight,
          sparsity_weight,
          diversity_weight,
          categorical_penalty,
          verbose,
      )
  
      query_instance_df = self.find_counterfactuals(
          query_instance,
          desired_range,
          desired_class,
          features_to_vary,
          maxiterations,
          thresh,
          verbose,
      )
  
      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,
          test_instance_df=query_instance_df,
          final_cfs_df=self.final_cfs_df,
          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,
      )
  
imports: import copy
  import random
  import timeit
  import numpy
  import pandas
  from raiutils.exceptions import UserConfigValidationException
  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 8 for calling the DiceGenetic obj's underlying member method code with example usage: obj._generate_counterfactuals(query_instance, total_CFs, initialization, desired_range, desired_class, proximity_weight, sparsity_weight, diversity_weight, categorical_penalty, algorithm, features_to_vary, permitted_range, yloss_type, diversity_loss_type, feature_weights, stopping_threshold, posthoc_sparsity_param, posthoc_sparsity_algorithm, maxiterations, thresh, verbose) and returns: exp