shap.Explanation

class shap.Explanation(values: npt.NDArray[Any] | list[Any] | Explanation, base_values: npt.NDArray[Any] | list[Any] | float | None = None, data: npt.NDArray[Any] | pd.DataFrame | list[Any] | None = None, display_data: npt.NDArray[Any] | pd.DataFrame | None = None, instance_names: Sequence[str] | npt.NDArray[Any] | None = None, feature_names: Sequence[str] | npt.NDArray[Any] | Alias | None = None, output_names: Sequence[str] | npt.NDArray[Any] | str | Alias | None = None, output_indexes: npt.NDArray[Any] | None = None, lower_bounds: npt.NDArray[Any] | None = None, upper_bounds: npt.NDArray[Any] | None = None, error_std: npt.NDArray[Any] | None = None, main_effects: npt.NDArray[Any] | None = None, hierarchical_values: npt.NDArray[Any] | list[Any] | None = None, clustering: npt.NDArray[Any] | list[Any] | None = None, compute_time: float | None = None)

A sliceable container holding the output of a SHAP explainer.

An Explanation is the canonical return type of every SHAP explainer. It bundles together the attributions (the SHAP values themselves) with the inputs they were computed on and any metadata that downstream plotting and summarisation functions need.

The shap-additivity relationship for a single sample is

\[f(x) \approx \text{base\_values} + \sum_i \text{values}_i\]

so together base_values and values explain the model output f(x) exactly (up to explainer approximation error).

Parameters:
valuesnumpy.ndarray, list, or Explanation

The SHAP values. Shape depends on the explainer and the model:

  • single-output model: (n_samples, n_features)

  • multi-output model: (n_samples, n_features, n_outputs)

If another Explanation is passed, its values, base_values and data are copied onto this instance.

base_valuesnumpy.ndarray, list, float, or None

The expected model output on the background dataset — i.e. the value that SHAP values are explaining the deviation from. Shape matches the output-trailing shape of values: (n_samples,) for single-output models, (n_samples, n_outputs) for multi-output models.

datanumpy.ndarray, pandas.DataFrame, list, or None

The input data that was explained — typically a copy of the X passed to the explainer’s __call__. Same number of rows as values and used by plot functions to show feature values next to their attributions.

display_datanumpy.ndarray, pandas.DataFrame, or None

A human-readable alternative to data used by plots. For example, use the raw (un-encoded) strings of a categorical feature here while data holds the encoded integers fed to the model. If None, plots fall back to data.

instance_namessequence of str, numpy.ndarray, or None

Optional label for each row (e.g. sample id). Used in some plots as the y-axis tick label.

feature_namessequence of str, numpy.ndarray, Alias, or None

Names of the input features, aligned with the feature axis of values. If None, plot functions fall back to positional names ("Feature 0", "Feature 1", …).

output_namessequence of str, numpy.ndarray, str, Alias, or None

Names of the model outputs — e.g. the class names of a multi-class classifier. Aligned with the output axis of values.

output_indexesnumpy.ndarray or None

For explainers that only compute a subset of outputs (e.g. the top-k ranked outputs), the index of each explained output in the original model’s output vector.

lower_bounds, upper_boundsnumpy.ndarray or None

Confidence bounds on values, shape matching values. Used by plots that support uncertainty display.

error_stdnumpy.ndarray or None

Per-value standard error estimate, shape matching values.

main_effectsnumpy.ndarray or None

The SHAP “main effects” — the single-feature component of the attribution, separate from interaction terms. Shape matches values.

hierarchical_valuesnumpy.ndarray, list, or None

Attributions against a hierarchical (partition) model of the features, rather than flat per-feature. See shap.explainers.PartitionExplainer.

clusteringnumpy.ndarray, list, or None

Partition tree of feature clusters used to compute hierarchical_values. A scipy-style linkage matrix, one row per merge.

compute_timefloat or None

Wall-clock seconds the explainer took, useful for benchmarking.

Attributes:
op_historylist

The chain of operations that have been applied to this Explanation (e.g. via .abs, .mean(0), slicing). Plots read this to label axes and subtitles.

output_dimstuple of int

Which axes of values correspond to model outputs vs. samples and features. Populated automatically from the shape.

Notes

Instance methods such as max() return new Explanation objects with the operation applied.

Class methods (accessed on the class itself, not an instance) such as Explanation.max return OpChain objects that represent a sequence of chained operations without actually running them. OpChains are used as the order= argument to plot functions so the sorting / reduction is deferred until plotting time.

Examples

>>> import numpy as np
>>> import shap
>>> rng = np.random.default_rng(0)
>>> exp = shap.Explanation(
...     values=rng.standard_normal((4, 3)),
...     base_values=np.full(4, 0.5),
...     data=rng.standard_normal((4, 3)),
...     feature_names=["a", "b", "c"],
... )
>>> exp.values.shape
(4, 3)
>>> exp[0].values.shape  # explanation of the first sample
(3,)
>>> exp[:, 0].feature_names  # explanation restricted to feature "a"
'a'
__init__(values: npt.NDArray[Any] | list[Any] | Explanation, base_values: npt.NDArray[Any] | list[Any] | float | None = None, data: npt.NDArray[Any] | pd.DataFrame | list[Any] | None = None, display_data: npt.NDArray[Any] | pd.DataFrame | None = None, instance_names: Sequence[str] | npt.NDArray[Any] | None = None, feature_names: Sequence[str] | npt.NDArray[Any] | Alias | None = None, output_names: Sequence[str] | npt.NDArray[Any] | str | Alias | None = None, output_indexes: npt.NDArray[Any] | None = None, lower_bounds: npt.NDArray[Any] | None = None, upper_bounds: npt.NDArray[Any] | None = None, error_std: npt.NDArray[Any] | None = None, main_effects: npt.NDArray[Any] | None = None, hierarchical_values: npt.NDArray[Any] | list[Any] | None = None, clustering: npt.NDArray[Any] | list[Any] | None = None, compute_time: float | None = None) → None

Build an Explanation. See the class docstring for full parameter details.

Methods

__init__(values[, base_values, data, ...])

Build an Explanation.

cohorts(cohorts)

Split this explanation into several cohorts.

hstack(other)

Stack two explanations column-wise.

percentile(q[, axis])

Attributes

abs

argsort

base_values

The expected model output on the background dataset.

clustering

Pass-through from the underlying slicer object.

data

The input data the explanation was computed on.

display_data

A human-readable alternative to data for use in plots.

error_std

Per-value standard error estimate, same shape as values, or None.

feature_names

Names of the input features, aligned with the feature axis of values.

flip

hclust

hierarchical_values

Pass-through from the underlying slicer object.

identity

instance_names

Optional label for each row (e.g. sample id).

lower_bounds

Lower confidence bound on values, same shape as values, or None.

main_effects

The main-effect component of the SHAP values, same shape as values.

max

mean

min

output_indexes

For ranked-output explainers, the original-model index of each explained output.

output_names

Names of the model outputs — e.g. class labels.

sample

shape

Compute the shape over potentially complex data nesting.

sum

upper_bounds

Upper confidence bound on values, same shape as values, or None.

values

The SHAP values themselves.

property base_values

The expected model output on the background dataset.

This is what SHAP values explain the deviation from. For a single-output model it has shape (n_samples,) and every row typically holds the same scalar; for a multi-output model the shape is (n_samples, n_outputs).

property clustering

Pass-through from the underlying slicer object.

cohorts(cohorts: int | list[int] | tuple[int] | ndarray) → Cohorts

Split this explanation into several cohorts.

Parameters:
cohortsint or array

If this is an integer then we auto build that many cohorts using a decision tree. If this is an array then we treat that as an array of cohort names/ids for each instance.

Returns:
Cohorts object
property data

The input data the explanation was computed on.

Typically a copy of the X passed to the explainer — same number of rows as values. Plot functions read this so they can display feature values alongside their attributions.

property display_data

A human-readable alternative to data for use in plots.

Useful when the model was fed an encoded representation (e.g. integer category codes) but you want plots to show the original strings. If unset, plots fall back to data.

property error_std

Per-value standard error estimate, same shape as values, or None.

property feature_names

Names of the input features, aligned with the feature axis of values.

None means plot functions fall back to positional names like "Feature 0".

property hierarchical_values

Pass-through from the underlying slicer object.

hstack(other: Explanation) → Explanation

Stack two explanations column-wise.

Parameters:
othershap.Explanation

The other Explanation object to stack with.

Returns:
expshap.Explanation

A new Explanation object representing the stacked explanations.

property instance_names

Optional label for each row (e.g. sample id).

Used by some plots as the y-axis tick label.

property lower_bounds

Lower confidence bound on values, same shape as values, or None.

property main_effects

The main-effect component of the SHAP values, same shape as values.

When the explainer also computes interactions, values = main_effects + interaction terms. None otherwise.

property output_indexes

For ranked-output explainers, the original-model index of each explained output.

Populated when the explainer was called with ranked_outputs=k rather than explaining every output. Lets callers map back from explained-output position to original class index.

property output_names

Names of the model outputs — e.g. class labels.

Aligned with the output axis of values. Plots use these for legend entries and subtitles.

property shape: tuple[int, ...]

Compute the shape over potentially complex data nesting.

property upper_bounds

Upper confidence bound on values, same shape as values, or None.

property values

The SHAP values themselves.

Shape (n_samples, n_features) for single-output models, or (n_samples, n_features, n_outputs) for multi-output models. Together with base_values these reconstruct the model output: base_values + values.sum(axis=feature_axis) ≈ model(data).