alibi.explainers.pd_variance module

class alibi.explainers.pd_variance.Method(value)[source]

Bases: str, Enum

Enumeration of supported methods.

IMPORTANCE = 'importance'
INTERACTION = 'interaction'
class alibi.explainers.pd_variance.PartialDependenceVariance(predictor, feature_names=None, categorical_names=None, target_names=None, verbose=False)[source]

Bases: Explainer

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 .

__init__(predictor, feature_names=None, categorical_names=None, target_names=None, verbose=False)[source]

Initialize black-box/tree-based model implementation for the partial dependence variance feature importance.

Parameters:
  • predictor (Union[BaseEstimator, Callable[[ndarray], ndarray]]) – A sklearn estimator or a prediction function which receives as input a numpy array of size N x F and outputs a numpy array of size N (i.e. (N, )) or N x T, where N is the number of input instances, F is the number of features and T is the number of targets.

  • feature_names (Optional[List[str]]) – A list of feature names used for displaying results.E

  • categorical_names (Optional[Dict[int, List[str]]]) –

    Dictionary where keys are feature columns and values are the categories for the feature. Necessary to identify the categorical features in the dataset. An example for categorical_names would be:

    category_map = {0: ["married", "divorced"], 3: ["high school diploma", "master's degree"]}
    

  • target_names (Optional[List[str]]) – A list of target/output names used for displaying results.

  • verbose (bool) – Whether to print the progress of the explainer.

Notes

The length of the target_names should match the number of columns returned by a call to the predictor. For example, in the case of a binary classifier, if the predictor outputs a decision score (i.e. uses the decision_function method) which returns one column, then the length of the target_names should be one. On the other hand, if the predictor outputs a prediction probability (i.e. uses the predict_proba method) which returns two columns (one for the negative class and one for the positive class), then the length of the target_names should be two.

explain(X, features=None, method='importance', percentiles=(0.0, 1.0), grid_resolution=100, grid_points=None)[source]

Calculates the variance partial dependence feature importance for each feature with respect to the all targets and the reference dataset X.

Parameters:
  • X (ndarray) – A N x F tabular dataset used to calculate partial dependence curves. This is typically the training dataset or a representative sample.

  • features (Union[List[int], List[Tuple[int, int]], None]) – 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 (Literal[‘importance’, ‘interaction’]) – Flag to specify whether to compute the feature importance or the feature interaction of the elements provided in features. Supported values: 'importance' | 'interaction'.

  • percentiles (Tuple[float, float]) – 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 (int) – 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 (Optional[Dict[int, Union[List, ndarray]]]) – 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.

Return type:

Explanation

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

alibi.explainers.pd_variance.plot_pd_variance(exp, features='all', targets='all', summarise=True, n_cols=3, sort=True, top_k=None, plot_limits=None, ax=None, sharey='all', bar_kw=None, line_kw=None, fig_kw=None)[source]

Plot feature importance and feature interaction based on partial dependence curves on matplotlib axes.

Parameters:
  • exp (Explanation) – An Explanation object produced by a call to the alibi.explainers.pd_variance.PartialDependenceVariance.explain() method.

  • features (Union[List[int], Literal[‘all’]]) – A list of features entries provided in feature_names argument to the alibi.explainers.pd_variance.PartialDependenceVariance.explain() method, or 'all' to plot all the explained features. For example, if feature_names = ['temp', 'hum', 'windspeed'] and we want to plot the values only for the 'temp' and 'windspeed', then we would set features=[0, 2]. Defaults to 'all'.

  • targets (Union[List[Union[int, str]], Literal[‘all’]]) – A target name/index, or a list of target names/indices, for which to plot the feature importance/interaction, or 'all'. Can be a mix of integers denoting target index or strings denoting entries in exp.meta[‘params’][‘target_names’]. By default 'all' to plot the importance for all features or to plot all the feature interactions.

  • summarise (bool) – Whether to plot only the summary of the feature importance/interaction as a bar plot, or plot comprehensive exposition including partial dependence plots and conditional importance plots.

  • n_cols (int) – Number of columns to organize the resulting plot into.

  • sort (bool) – Boolean flag whether to sort the values in descending order.

  • top_k (Optional[int]) – Number of top k values to be displayed if the sort=True. If not provided, then all values will be displayed.

  • plot_limits (Optional[Tuple[float, float]]) – Minimum and maximum y-limits for all the line plots. If None will be automatically inferred.

  • ax (Union[Axes, ndarray, None]) – A matplotlib axes object or a numpy array of matplotlib axes to plot on.

  • sharey (Optional[Literal[‘all’, ‘row’]]) – A parameter specifying whether the y-axis of the PD and ICE curves should be on the same scale for several features. Possible values are: 'all' | 'row' | None.

  • bar_kw (Optional[dict]) – Keyword arguments passed to the matplotlib.pyplot.barh function.

  • line_kw (Optional[dict]) – Keyword arguments passed to the matplotlib.pyplot.plot function.

  • fig_kw (Optional[dict]) –

    Keyword arguments passed to the matplotlib.figure.set function.

Returns:

plt.Axes with the summary/detailed exposition plot of the feature importance or feature interaction.