class_docstr: Implementation of the partial dependence(PD) variance feature importance and feature interaction for
  tabular datasets. The method measure the importance feature importance as the variance within the PD function.
  Similar, the potential feature interaction is measured by computing the variance within the two-way PD function
  by holding one variable constant and letting the other vary. Supports black-box models and the following `sklearn`
  tree-based models: `GradientBoostingClassifier`, `GradientBoostingRegressor`, `HistGradientBoostingClassifier`,
  `HistGradientBoostingRegressor`, `HistGradientBoostingRegressor`, `DecisionTreeRegressor`,
  `RandomForestRegressor`.
  
  For details of the method see the original paper: https://arxiv.org/abs/1805.04755 .
class_docstr_tok: ["Implementation","of","the","partial","dependence","(","PD",")","variance","feature","importance","and","feature","interaction","for","tabular","datasets",".","The","method","measure","the","importance","feature","importance","as","the","variance","within","the","PD","function",".","Similar",",","the","potential","feature","interaction","is","measured","by","computing","the","variance","within","the","two-way","PD","function","by","holding","one","variable","constant","and","letting","the","other","vary",".","Supports","black-box","models","and","the","following","`","sklearn","`","tree-based","models",":","`","GradientBoostingClassifier","`",",","`","GradientBoostingRegressor","`",",","`","HistGradientBoostingClassifier","`",",","`","HistGradientBoostingRegressor","`",",","`","HistGradientBoostingRegressor","`",",","`","DecisionTreeRegressor","`",",","`","RandomForestRegressor","`",".","For","details","of","the","method","see","the","original","paper",":","https",":","\/\/arxiv.org\/abs\/1805.04755","."]
docstr: Calculates the variance partial dependence feature importance for each feature with respect to the all targets
  and the reference dataset `X`.
  
  Parameters
  ----------
  X
      A `N x F` tabular dataset used to calculate partial dependence curves. This is typically the
      training dataset or a representative sample.
  features
      A list of features for which to compute the feature importance or a list of feature pairs
      for which to compute the feature interaction. Some example of `features` would be: ``[0, 1, 3]``,
      ``[(0, 1), (0, 3), (1, 3)]``, where ``0``,``1``, and ``3`` correspond to the columns 0, 1, and 3 in `X`.
      If not provided, the feature importance or the feature interaction will be computed for every
      feature or for every combination of feature pairs, depending on the parameter `method`.
  method
      Flag to specify whether to compute the feature importance or the feature interaction of the elements
      provided in `features`. Supported values: ``'importance'`` | ``'interaction'``.
  percentiles
      Lower and upper percentiles used to limit the feature values to potentially remove outliers from
      low-density regions. Note that for features with not many data points with large/low values, the
      PD estimates are less reliable in those extreme regions. The values must be in [0, 1]. Only used
      with `grid_resolution`.
  grid_resolution
      Number of equidistant points to split the range of each target feature. Only applies if the number of
      unique values of a target feature in the reference dataset `X` is greater than the `grid_resolution` value.
      For example, consider a case where a feature can take the following values:
      ``[0.1, 0.3, 0.35, 0.351, 0.4, 0.41, 0.44, ..., 0.5, 0.54, 0.56, 0.6, 0.65, 0.7, 0.9]``, and we are not
      interested in evaluating the marginal effect at every single point as it can become computationally costly
      (assume hundreds/thousands of points) without providing any additional information for nearby points
      (e.g., 0.35 and 351). By setting ``grid_resolution=5``, the marginal effect is computed for the values
      ``[0.1, 0.3, 0.5, 0.7, 0.9]`` instead, which is less computationally demanding and can provide similar
      insights regarding the model's behaviour. Note that the extreme values of the grid can be controlled
      using the `percentiles` argument.
  grid_points
      Custom grid points. Must be a `dict` where the keys are the target features indices and the values are
      monotonically increasing arrays defining the grid points for a numerical feature, and a subset of
      categorical feature values for a categorical feature. If the `grid_points` are not specified,
      then the grid will be constructed based on the unique target feature values available in the
      dataset `X`, or based on the `grid_resolution` and `percentiles` (check `grid_resolution` to see when
      it applies). For categorical features, the corresponding value in the `grid_points` can be
      specified either as array of strings or array of integers corresponding the label encodings.
      Note that the label encoding must match the ordering of the values provided in the `categorical_names`.
  
  Returns
  -------
  explanation
      An `Explanation` object containing the data and the metadata of the calculated partial dependence
      curves and feature importance/interaction. See usage at `Partial dependence variance examples`_ for details
  
      .. _Partial dependence variance examples:
          https://docs.seldon.io/projects/alibi/en/stable/methods/PartialDependenceVariance.html
docstr_tok: ["Calculates","the","variance","partial","dependence","feature","importance","for","each","feature","with","respect","to","the","all","targets","and","the","reference","dataset","`","X","`",".","Parameters","--","--","--","--","--","X","A","`","N","x","F","`","tabular","dataset","used","to","calculate","partial","dependence","curves",".","This","is","typically","the","training","dataset","or","a","representative","sample",".","features","A","list","of","features","for","which","to","compute","the","feature","importance","or","a","list","of","feature","pairs","for","which","to","compute","the","feature","interaction",".","Some","example","of","`","features","`","would","be",":","``","[","0",",","1",",","3","]","``",",","``","[","(","0",",","1",")",",","(","0",",","3",")",",","(","1",",","3",")","]","``",",","where","``","0","``",",","``","1","``",",","and","``","3","``","correspond","to","the","columns","0",",","1",",","and","3","in","`","X","`",".","If","not","provided",",","the","feature","importance","or","the","feature","interaction","will","be","computed","for","every","feature","or","for","every","combination","of","feature","pairs",",","depending","on","the","parameter","`","method","`",".","method","Flag","to","specify","whether","to","compute","the","feature","importance","or","the","feature","interaction","of","the","elements","provided","in","`","features","`",".","Supported","values",":","``","'importance","'","``","|","``","'interaction","'","``",".","percentiles","Lower","and","upper","percentiles","used","to","limit","the","feature","values","to","potentially","remove","outliers","from","low-density","regions",".","Note","that","for","features","with","not","many","data","points","with","large\/low","values",",","the","PD","estimates","are","less","reliable","in","those","extreme","regions",".","The","values","must","be","in","[","0",",","1","]",".","Only","used","with","`","grid_resolution","`",".","grid_resolution","Number","of","equidistant","points","to","split","the","range","of","each","target","feature",".","Only","applies","if","the","number","of","unique","values","of","a","target","feature","in","the","reference","dataset","`","X","`","is","greater","than","the","`","grid_resolution","`","value",".","For","example",",","consider","a","case","where","a","feature","can","take","the","following","values",":","``","[","0.1",",","0.3",",","0.35",",","0.351",",","0.4",",","0.41",",","0.44",",","...",",","0.5",",","0.54",",","0.56",",","0.6",",","0.65",",","0.7",",","0.9","]","``",",","and","we","are","not","interested","in","evaluating","the","marginal","effect","at","every","single","point","as","it","can","become","computationally","costly","(","assume","hundreds\/thousands","of","points",")","without","providing","any","additional","information","for","nearby","points","(","e.g.",",","0.35","and","351",")",".","By","setting","``","grid_resolution=5","``",",","the","marginal","effect","is","computed","for","the","values","``","[","0.1",",","0.3",",","0.5",",","0.7",",","0.9","]","``","instead",",","which","is","less","computationally","demanding","and","can","provide","similar","insights","regarding","the","model","'s","behaviour",".","Note","that","the","extreme","values","of","the","grid","can","be","controlled","using","the","`","percentiles","`","argument",".","grid_points","Custom","grid","points",".","Must","be","a","`","dict","`","where","the","keys","are","the","target","features","indices","and","the","values","are","monotonically","increasing","arrays","defining","the","grid","points","for","a","numerical","feature",",","and","a","subset","of","categorical","feature","values","for","a","categorical","feature",".","If","the","`","grid_points","`","are","not","specified",",","then","the","grid","will","be","constructed","based","on","the","unique","target","feature","values","available","in","the","dataset","`","X","`",",","or","based","on","the","`","grid_resolution","`","and","`","percentiles","`","(","check","`","grid_resolution","`","to","see","when","it","applies",")",".","For","categorical","features",",","the","corresponding","value","in","the","`","grid_points","`","can","be","specified","either","as","array","of","strings","or","array","of","integers","corresponding","the","label","encodings",".","Note","that","the","label","encoding","must","match","the","ordering","of","the","values","provided","in","the","`","categorical_names","`",".","Returns","--","--","--","-","explanation","An","`","Explanation","`","object","containing","the","data","and","the","metadata","of","the","calculated","partial","dependence","curves","and","feature","importance\/interaction",".","See","usage","at","`","Partial","dependence","variance","examples","`","_","for","details","..","_Partial","dependence","variance","examples",":","https",":","\/\/docs.seldon.io\/projects\/alibi\/en\/stable\/methods\/PartialDependenceVariance.html"]
code: def explain(
      self,
      X: np.ndarray,
      features: Optional[
          Union[List[int], List[Tuple[int, int]]]
      ] = None,
      method: Literal["importance", "interaction"] = "importance",
      percentiles: Tuple[float, float] = (0.0, 1.0),
      grid_resolution: int = 100,
      grid_points: Optional[Dict[int, Union[List, np.ndarray]]] = None,
  ) -> Explanation:
      """
      Calculates the variance partial dependence feature importance for each feature with respect to the all targets
      and the reference dataset `X`.
  
      Parameters
      ----------
      X
          A `N x F` tabular dataset used to calculate partial dependence curves. This is typically the
          training dataset or a representative sample.
      features
          A list of features for which to compute the feature importance or a list of feature pairs
          for which to compute the feature interaction. Some example of `features` would be: ``[0, 1, 3]``,
          ``[(0, 1), (0, 3), (1, 3)]``, where ``0``,``1``, and ``3`` correspond to the columns 0, 1, and 3 in `X`.
          If not provided, the feature importance or the feature interaction will be computed for every
          feature or for every combination of feature pairs, depending on the parameter `method`.
      method
          Flag to specify whether to compute the feature importance or the feature interaction of the elements
          provided in `features`. Supported values: ``'importance'`` | ``'interaction'``.
      percentiles
          Lower and upper percentiles used to limit the feature values to potentially remove outliers from
          low-density regions. Note that for features with not many data points with large/low values, the
          PD estimates are less reliable in those extreme regions. The values must be in [0, 1]. Only used
          with `grid_resolution`.
      grid_resolution
          Number of equidistant points to split the range of each target feature. Only applies if the number of
          unique values of a target feature in the reference dataset `X` is greater than the `grid_resolution` value.
          For example, consider a case where a feature can take the following values:
          ``[0.1, 0.3, 0.35, 0.351, 0.4, 0.41, 0.44, ..., 0.5, 0.54, 0.56, 0.6, 0.65, 0.7, 0.9]``, and we are not
          interested in evaluating the marginal effect at every single point as it can become computationally costly
          (assume hundreds/thousands of points) without providing any additional information for nearby points
          (e.g., 0.35 and 351). By setting ``grid_resolution=5``, the marginal effect is computed for the values
          ``[0.1, 0.3, 0.5, 0.7, 0.9]`` instead, which is less computationally demanding and can provide similar
          insights regarding the model's behaviour. Note that the extreme values of the grid can be controlled
          using the `percentiles` argument.
      grid_points
          Custom grid points. Must be a `dict` where the keys are the target features indices and the values are
          monotonically increasing arrays defining the grid points for a numerical feature, and a subset of
          categorical feature values for a categorical feature. If the `grid_points` are not specified,
          then the grid will be constructed based on the unique target feature values available in the
          dataset `X`, or based on the `grid_resolution` and `percentiles` (check `grid_resolution` to see when
          it applies). For categorical features, the corresponding value in the `grid_points` can be
          specified either as array of strings or array of integers corresponding the label encodings.
          Note that the label encoding must match the ordering of the values provided in the `categorical_names`.
  
      Returns
      -------
      explanation
          An `Explanation` object containing the data and the metadata of the calculated partial dependence
          curves and feature importance/interaction. See usage at `Partial dependence variance examples`_ for details
  
          .. _Partial dependence variance examples:
              https://docs.seldon.io/projects/alibi/en/stable/methods/PartialDependenceVariance.html
      """
      if method not in Method.__members__.values():
          raise ValueError(
              f"Unknown method. Received ``method={method}``. "
              f"Accepted `method` names are: {_get_options_string(Method)}"
          )
  
      # get number of features
      n_features = X.shape[1]
  
      # construct features if not provided based on the method
      if features is None:
          features = list(range(n_features))
  
          if method == Method.INTERACTION:
              features = list(itertools.combinations(features, 2))
  
      # compute partial dependence functions
      params = {
          "X": X,
          "features": features,
          "percentiles": percentiles,
          "grid_resolution": grid_resolution,
          "grid_points": grid_points,
      }
  
      if not isinstance(self.pd_explainer.predictor, BaseEstimator):
          params.update({"kind": Kind.AVERAGE.value})  # type: ignore[dict-item]
  
      # compute partial dependence for each feature
      pd_explanation = self.pd_explainer.explain(**params)  # type: ignore[arg-type]
  
      if method == Method.IMPORTANCE:
          if not all(
              [isinstance(f, numbers.Integral) for f in features]
          ):
              raise ValueError(
                  f"For ``method='{Method.IMPORTANCE.value}'`` all features must be integers."
              )
          # compute feature importance
          buffers = self._compute_feature_importance(
              pd_explanation=pd_explanation, features=features
          )
      else:
          if not all(
              [
                  isinstance(fs, tuple) and len(fs) == 2
                  for fs in features
              ]
          ):
              raise ValueError(
                  f"For ``method='{Method.INTERACTION.value}'`` all features must be "
                  f"tuples of length 2."
              )
          # compute feature interaction
          buffers = self._compute_feature_interaction(
              pd_explanation=pd_explanation, features=features
          )  # type: ignore[arg-type]
  
      # update `meta['params'] with the `pd_explainer.meta['params'], remove 'kind', and include 'method'
      self.meta["params"].update(self.pd_explainer.meta["params"])
      self.meta["params"].pop("kind")
      self.meta["params"].update({"method": method})
  
      # build and return the explanation object
      return self._build_explanation(buffers=buffers)
  
imports: import copy
  import itertools
  import logging
  import math
  import numbers
  import sys
  from enum import Enum
  from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  import matplotlib.pyplot
  import numpy
  from sklearn.base import BaseEstimator
  from alibi.api.defaults import DEFAULT_DATA_PD, DEFAULT_DATA_PDVARIANCE, DEFAULT_META_PDVARIANCE
  from alibi.api.interfaces import Explainer, Explanation
  from alibi.explainers import plot_pd
  from alibi.explainers.partial_dependence import Kind, PartialDependence, TreePartialDependence
  from alibi.utils import _get_options_string
label_desc: Use image node_id 2 for calling the PartialDependenceVariance obj's underlying member method code with example usage: obj.explain(X, features, method, percentiles, grid_resolution, grid_points) and returns: self