Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: UnboundLocalError with bar plots using dictionary input #3001

Merged
merged 4 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
([dsgibbons#88](https://github.com/dsgibbons/shap/pull/88) by @thatlittleboy).
- Fixed sampling in `shap.datasets` to sample without replacement
([dsgibbons#36](https://github.com/dsgibbons/shap/pull/36) by @thatlittleboy).
- Fixed an `UnboundLocalError` problem arising from passing a dictionary input to `shap.plots.bar`
([#3001](https://github.com/slundberg/shap/pull/3000) by @thatlittleboy).
- Fixed tensorflow import issue with Pyspark when using `Gradient`
([#2983](https://github.com/slundberg/shap/pull/2983) by @skamdar).
- Fixed deprecation warnings for `numpy>=1.24` from numpy types
Expand Down
31 changes: 25 additions & 6 deletions shap/plots/_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from .. import Cohorts, Explanation
from ..utils import format_value, ordinal_str
from ..utils._exceptions import DimensionError
from . import colors
from ._labels import labels
from ._utils import (
Expand Down Expand Up @@ -54,17 +55,35 @@ def bar(shap_values, max_display=10, order=Explanation.abs, clustering=None, clu
cohorts = {"": shap_values}
elif isinstance(shap_values, Cohorts):
cohorts = shap_values.cohorts
elif isinstance(shap_values, dict):
cohorts = shap_values
else:
assert isinstance(shap_values, dict), "You must pass an Explanation object, Cohorts object, or dictionary to bar plot!"
emsg = (
"The shap_values argument must be an Explanation object, Cohorts "
"object, or dictionary of Explanation objects!"
)
raise TypeError(emsg)
thatlittleboy marked this conversation as resolved.
Show resolved Hide resolved

# unpack our list of Explanation objects we need to plot
cohort_labels = list(cohorts.keys())
cohort_exps = list(cohorts.values())
for i in range(len(cohort_exps)):
if len(cohort_exps[i].shape) == 2:
cohort_exps[i] = cohort_exps[i].abs.mean(0)
assert isinstance(cohort_exps[i], Explanation), "The shap_values paramemter must be a Explanation object, Cohorts object, or dictionary of Explanation objects!"
assert cohort_exps[i].shape == cohort_exps[0].shape, "When passing several Explanation objects they must all have the same shape!"
for i, exp in enumerate(cohort_exps):
if not isinstance(exp, Explanation):
emsg = (
"The shap_values argument must be an Explanation object, Cohorts "
"object, or dictionary of Explanation objects!"
)
raise TypeError(emsg)
connortann marked this conversation as resolved.
Show resolved Hide resolved

if len(exp.shape) == 2:
# collapse the Explanation arrays to be of shape (#features,)
cohort_exps[i] = exp.abs.mean(0)
if cohort_exps[i].shape != cohort_exps[0].shape:
emsg = (
"When passing several Explanation objects, they must all have "
"the same number of feature columns!"
)
raise DimensionError(emsg)
# TODO: check other attributes for equality? like feature names perhaps? probably clustering as well.

# unpack the Explanation object
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
75 changes: 70 additions & 5 deletions tests/plots/test_bar.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,82 @@
''' This file contains tests for the bar plot.
'''
"""This file contains tests for the bar plot.
"""
import matplotlib.pyplot as plt
import numpy as np
import pytest

import shap
from shap.utils._exceptions import DimensionError


@pytest.mark.parametrize(
"unsupported_inputs",
[
[1, 2, 3],
(1, 2, 3),
np.array([1, 2, 3]),
{"a": 1, "b": 2},
],
)
def test_input_shap_values_type(unsupported_inputs):
"""Check that a TypeError is raised when shap_values is not a valid input type."""
emsg = (
"The shap_values argument must be an Explanation object, Cohorts "
"object, or dictionary of Explanation objects!"
)
with pytest.raises(TypeError, match=emsg):
shap.plots.bar(unsupported_inputs, show=False)


def test_input_shap_values_type_2():
"""Check that a DimensionError is raised if the cohort Explanation objects have different shape."""
rs = np.random.RandomState(42)
emsg = (
"When passing several Explanation objects, they must all have "
"the same number of feature columns!"
)
with pytest.raises(DimensionError, match=emsg):
shap.plots.bar(
{
"t1": shap.Explanation(
values=rs.randn(40, 10),
base_values=np.ones(40) * 0.5,
),
"t2": shap.Explanation(
values=rs.randn(20, 5),
base_values=np.ones(20) * 0.5,
),
},
show=False,
)


@pytest.mark.mpl_image_compare
def test_simple_bar(explainer): # pylint: disable=redefined-outer-name
""" Check that the bar plot is unchanged.
"""
def test_simple_bar(explainer):
"""Check that the bar plot is unchanged."""
shap_values = explainer(explainer.data)
fig = plt.figure()
shap.plots.bar(shap_values, show=False)
plt.tight_layout()
return fig


@pytest.mark.mpl_image_compare
def test_simple_bar_with_cohorts_dict():
"""Ensure that bar plots supports dictionary of Explanations as input."""
rs = np.random.RandomState(42)
fig = plt.figure()
shap.plots.bar(
{
"t1": shap.Explanation(
values=rs.randn(40, 5),
base_values=np.ones(40) * 0.5,
),
"t2": shap.Explanation(
values=rs.randn(20, 5),
base_values=np.ones(20) * 0.5,
),
},
show=False,
)
plt.tight_layout()
return fig