Skip to content

Commit

Permalink
fix: ruff rule F841 (unused variable) (#90)
Browse files Browse the repository at this point in the history
* chore: remove F841 from ruff ignore

* fix violations

* fix: clear out remaining violation
  • Loading branch information
thatlittleboy authored Jun 1, 2023
1 parent c266372 commit 5e45770
Show file tree
Hide file tree
Showing 11 changed files with 16 additions and 36 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ select = ["F"]
# For now, deselect rules that do not pass
ignore = [
"F811", # Redefinition of unused variable
"F841", # Local variables assigned but unused
]

[tool.ruff.per-file-ignores]
Expand Down
2 changes: 0 additions & 2 deletions shap/_explanation.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,6 @@ def compute_output_dims(values, base_values, data, output_names):
output_shape = tuple()

interaction_order = len(values_shape) - len(data_shape) - len(output_shape)
values_dims = list(range(len(values_shape)))
output_dims = range(len(data_shape) + interaction_order, len(values_shape))
return tuple(output_dims)

Expand Down Expand Up @@ -867,7 +866,6 @@ def _auto_cohorts(shap_values, max_cohorts):

# group instances by their decision paths
paths = m.decision_path(shap_values.data).toarray()
unique_paths = np.unique(m.decision_path(shap_values.data).todense(), axis=0)
path_names = []

# mark each instance with a path name
Expand Down
4 changes: 1 addition & 3 deletions shap/explainers/_sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,9 @@ def __call__(self, X, y=None, nsamples=2000):
feature_names = None # we can make self.feature_names from background data eventually if we have it

v = self.shap_values(X, nsamples=nsamples)
output_shape = tuple()
if type(v) is list:
output_shape = (len(v),)
v = np.stack(v, axis=-1) # put outputs at the end
e = Explanation(v, self.expected_value, X, feature_names=feature_names)#, output_shape=output_shape)
e = Explanation(v, self.expected_value, X, feature_names=feature_names)
return e

def explain(self, incoming_instance, **kwargs):
Expand Down
8 changes: 4 additions & 4 deletions shap/plots/_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def bar(shap_values, max_display=10, order=Explanation.abs, clustering=None, clu
ax = pl.gca()
#xticks = ax.get_xticks()
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
width = bbox.width
bbox_to_xscale = xlen/width

for i in range(len(values)):
Expand All @@ -233,7 +233,7 @@ def bar(shap_values, max_display=10, order=Explanation.abs, clustering=None, clu
# put horizontal lines for each feature row
for i in range(num_features):
pl.axhline(i+1, color="#888888", lw=0.5, dashes=(1, 5), zorder=-1)

if features is not None:
features = list(features)

Expand All @@ -244,7 +244,7 @@ def bar(shap_values, max_display=10, order=Explanation.abs, clustering=None, clu
features[i] = int(features[i])
except:
pass # features[i] must not be a number

pl.gca().xaxis.set_ticks_position('bottom')
pl.gca().yaxis.set_ticks_position('none')
pl.gca().spines['right'].set_visible(False)
Expand Down Expand Up @@ -399,4 +399,4 @@ def bar_legacy(shap_values, features=None, feature_names=None, max_display=None,
pl.xlabel("SHAP value (impact on model output)")

if show:
pl.show()
pl.show()
6 changes: 2 additions & 4 deletions shap/plots/_beeswarm.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ def beeswarm(shap_values, max_display=10, order=Explanation.abs.mean(0),

# here we build our feature names, accounting for the fact that some features might be merged together
feature_inds = feature_order[:max_display]
y_pos = np.arange(len(feature_inds), 0, -1)
feature_names_new = []
for pos,inds in enumerate(orig_inds):
if len(inds) == 1:
Expand Down Expand Up @@ -444,7 +443,6 @@ def summary_legacy(shap_values, features=None, feature_names=None, max_display=N
# support passing an explanation object
if str(type(shap_values)).endswith("Explanation'>"):
shap_exp = shap_values
base_value = shap_exp.base_values
shap_values = shap_exp.values
if features is None:
features = shap_exp.data
Expand Down Expand Up @@ -701,7 +699,7 @@ def summary_legacy(shap_values, features=None, feature_names=None, max_display=N
ds /= np.max(ds) * 3

values = features[:, i]
window_size = max(10, len(values) // 20)
# window_size = max(10, len(values) // 20)
smooth_values = np.zeros(len(xs) - 1)
sort_inds = np.argsort(shaps)
trailing_pos = 0
Expand Down Expand Up @@ -790,7 +788,7 @@ def summary_legacy(shap_values, features=None, feature_names=None, max_display=N
# order the feature data so we can apply percentiling
order = np.argsort(feature)
# x axis is located at y0 = pos, with pos being there for offset
y0 = np.ones(num_x_points) * pos
# y0 = np.ones(num_x_points) * pos
# calculate kdes:
ys = np.zeros((nbins, num_x_points))
for i in range(nbins):
Expand Down
4 changes: 2 additions & 2 deletions shap/plots/_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ def image(shap_values: Explanation or np.ndarray,
if labels is None:
labels = shap_exp.output_names

multi_output = True
# multi_output = True
if not isinstance(shap_values, list):
multi_output = False
# multi_output = False
shap_values = [shap_values]

if len(shap_values[0].shape) == 3:
Expand Down
2 changes: 1 addition & 1 deletion shap/plots/_scatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def scatter(shap_values, color="#1E88E5", hist=True, axis_color="#333333", cmap=
ymin = nan_min - (nan_max - nan_min)/20
if ymax is None:
ymax = nan_max + (nan_max - nan_min)/20
f = pl.subplots(1, len(inds), figsize=(min(6 * len(inds), 15), 5))
_ = pl.subplots(1, len(inds), figsize=(min(6 * len(inds), 15), 5))
for i in inds:
ax = pl.subplot(1,len(inds),i+1)
scatter(shap_values[:,i], color=color, show=False, ax=ax, ymin=ymin, ymax=ymax)
Expand Down
2 changes: 0 additions & 2 deletions shap/plots/_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,6 @@ def values_min_max(values, base_values):

# build out HTML output one word one at a time
top_inds = np.argsort(-np.abs(values))[:num_starting_labels]
maxv = values.max()
minv = values.min()
out = ""
# ev_str = str(shap_values.base_values)
# vsum_str = str(values.sum())
Expand Down
8 changes: 2 additions & 6 deletions shap/plots/_violin.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ def violin(shap_values, features=None, feature_names=None, max_display=None, plo
# support passing an explanation object
if str(type(shap_values)).endswith("Explanation'>"):
shap_exp = shap_values
base_value = shap_exp.expected_value
shap_values = shap_exp.values
if features is None:
features = shap_exp.data
Expand Down Expand Up @@ -98,13 +97,10 @@ def violin(shap_values, features=None, feature_names=None, max_display=None, plo
else:
color = colors.blue_rgb

idx2cat = None
# convert from a DataFrame or other types
if str(type(features)) == "<class 'pandas.core.frame.DataFrame'>":
if feature_names is None:
feature_names = features.columns
# feature index to category flag
idx2cat = features.dtypes.astype(str).isin(["object", "category"]).tolist()
features = features.values
elif isinstance(features, list):
if feature_names is None:
Expand Down Expand Up @@ -169,7 +165,7 @@ def violin(shap_values, features=None, feature_names=None, max_display=None, plo
ds /= np.max(ds) * 3

values = features[:, i]
window_size = max(10, len(values) // 20)
# window_size = max(10, len(values) // 20)
smooth_values = np.zeros(len(xs) - 1)
sort_inds = np.argsort(shaps)
trailing_pos = 0
Expand Down Expand Up @@ -249,7 +245,7 @@ def violin(shap_values, features=None, feature_names=None, max_display=None, plo
# order the feature data so we can apply percentiling
order = np.argsort(feature)
# x axis is located at y0 = pos, with pos being there for offset
y0 = np.ones(num_x_points) * pos
# y0 = np.ones(num_x_points) * pos
# calculate kdes:
ys = np.zeros((nbins, num_x_points))
for i in range(nbins):
Expand Down
10 changes: 2 additions & 8 deletions shap/plots/_waterfall.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,10 @@ def waterfall(shap_values, max_display=10, show=True):
pos_inds.append(0)
pos_widths.append(-remaining_impact)
pos_lefts.append(loc + remaining_impact)
c = colors.red_rgb
else:
neg_inds.append(0)
neg_widths.append(-remaining_impact)
neg_lefts.append(loc + remaining_impact)
c = colors.blue_rgb

points = pos_lefts + list(np.array(pos_lefts) + np.array(pos_widths)) + neg_lefts + \
list(np.array(neg_lefts) + np.array(neg_widths))
Expand All @@ -161,9 +159,8 @@ def waterfall(shap_values, max_display=10, show=True):
xlen = plt.xlim()[1] - plt.xlim()[0]
fig = plt.gcf()
ax = plt.gca()
xticks = ax.get_xticks()
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
width = bbox.width
bbox_to_xscale = xlen/width
hl_scaled = bbox_to_xscale * head_length
renderer = fig.canvas.get_renderer()
Expand Down Expand Up @@ -443,12 +440,10 @@ def waterfall_legacy(expected_value, shap_values=None, features=None, feature_na
pos_inds.append(0)
pos_widths.append(-remaining_impact)
pos_lefts.append(loc + remaining_impact)
c = colors.red_rgb
else:
neg_inds.append(0)
neg_widths.append(-remaining_impact)
neg_lefts.append(loc + remaining_impact)
c = colors.blue_rgb

points = pos_lefts + list(np.array(pos_lefts) + np.array(pos_widths)) + neg_lefts + \
list(np.array(neg_lefts) + np.array(neg_widths))
Expand All @@ -468,9 +463,8 @@ def waterfall_legacy(expected_value, shap_values=None, features=None, feature_na
xlen = plt.xlim()[1] - plt.xlim()[0]
fig = plt.gcf()
ax = plt.gca()
xticks = ax.get_xticks()
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width, bbox.height
width = bbox.width
bbox_to_xscale = xlen/width
hl_scaled = bbox_to_xscale * head_length
renderer = fig.canvas.get_renderer()
Expand Down
5 changes: 2 additions & 3 deletions shap/utils/_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,9 @@ def potential_interactions(shap_values_column, shap_values_matrix):
index values for SHAP see the interaction_contribs option implemented in XGBoost.
"""

# ignore inds that are identical to the column
# ignore inds that are identical to the column
ignore_inds = np.where((shap_values_matrix.values.T - shap_values_column.values).T.std(0) < 1e-8)

values = shap_values_matrix.values

X = shap_values_matrix.data

if X.shape[0] > 10000:
Expand Down

0 comments on commit 5e45770

Please sign in to comment.