forked from shap/shap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_sequential.py
328 lines (270 loc) · 13 KB
/
_sequential.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
from shap.utils import safe_isinstance, MaskedModel
from shap.maskers import Independent, Partition, Impute, Text, Image, FixedComposite
from shap import Explanation, links
import matplotlib.pyplot as pl
import sklearn
import numpy as np
from tqdm.auto import tqdm
import time
import pandas as pd
from . import BenchmarkResult
class SequentialMasker():
def __init__(self, mask_type, sort_order, masker, model, *model_args, batch_size=500):
for arg in model_args:
if isinstance(arg, pd.DataFrame):
raise TypeError("DataFrame arguments dont iterate correctly, pass numpy arrays instead!")
# convert any DataFrames to numpy arrays
# self.model_arg_cols = []
# self.model_args = []
# self.has_df = False
# for arg in model_args:
# if isinstance(arg, pd.DataFrame):
# self.model_arg_cols.append(arg.columns)
# self.model_args.append(arg.values)
# self.has_df = True
# else:
# self.model_arg_cols.append(None)
# self.model_args.append(arg)
# if self.has_df:
# given_model = model
# def new_model(*args):
# df_args = []
# for i, arg in enumerate(args):
# if self.model_arg_cols[i] is not None:
# df_args.append(pd.DataFrame(arg, columns=self.model_arg_cols[i]))
# else:
# df_args.append(arg)
# return given_model(*df_args)
# model = new_model
self.inner = SequentialPerturbation(
model, masker, sort_order, mask_type
)
self.model_args = model_args
self.batch_size = batch_size
def __call__(self, explanation, name, **kwargs):
return self.inner(name, explanation, *self.model_args, batch_size=self.batch_size, **kwargs)
class SequentialPerturbation():
def __init__(self, model, masker, sort_order, perturbation, linearize_link=False):
# self.f = lambda masked, x, index: model.predict(masked)
self.model = model if callable(model) else model.predict
self.masker = masker
self.sort_order = sort_order
self.perturbation = perturbation
self.linearize_link = linearize_link
# define our sort order
if self.sort_order == "positive":
self.sort_order_map = lambda x: np.argsort(-x)
elif self.sort_order == "negative":
self.sort_order_map = lambda x: np.argsort(x)
elif self.sort_order == "absolute":
self.sort_order_map = lambda x: np.argsort(-abs(x))
else:
raise ValueError("sort_order must be either \"positive\", \"negative\", or \"absolute\"!")
# user must give valid masker
underlying_masker = masker.masker if isinstance(masker, FixedComposite) else masker
if isinstance(underlying_masker, Text):
self.data_type = "text"
elif isinstance(underlying_masker, Image):
self.data_type = "image"
else:
self.data_type = "tabular"
#raise ValueError("masker must be for \"tabular\", \"text\", or \"image\"!")
self.score_values = []
self.score_aucs = []
self.labels = []
def __call__(self, name, explanation, *model_args, percent=0.01, indices=[], y=None, label=None, silent=False, debug_mode=False, batch_size=10):
# if explainer is already the attributions
if safe_isinstance(explanation, "numpy.ndarray"):
attributions = explanation
elif isinstance(explanation, Explanation):
attributions = explanation.values
else:
raise ValueError("The passed explanation must be either of type numpy.ndarray or shap.Explanation!")
assert len(attributions) == len(model_args[0]), "The explanation passed must have the same number of rows as the model_args that were passed!"
if label is None:
label = "Score %d" % len(self.score_values)
# convert dataframes
# if safe_isinstance(X, "pandas.core.series.Series") or safe_isinstance(X, "pandas.core.frame.DataFrame"):
# X = X.values
# convert all single-sample vectors to matrices
# if not hasattr(attributions[0], "__len__"):
# attributions = np.array([attributions])
# if not hasattr(X[0], "__len__") and self.data_type == "tabular":
# X = np.array([X])
pbar = None
start_time = time.time()
svals = []
mask_vals = []
for i, args in enumerate(zip(*model_args)):
# if self.data_type == "image":
# x_shape, y_shape = attributions[i].shape[0], attributions[i].shape[1]
# feature_size = np.prod([x_shape, y_shape])
# sample_attributions = attributions[i].mean(2).reshape(feature_size, -1)
# data = X[i].flatten()
# mask_shape = X[i].shape
# else:
feature_size = np.prod(attributions[i].shape)
sample_attributions = attributions[i].flatten()
# data = X[i]
# mask_shape = feature_size
self.masked_model = MaskedModel(self.model, self.masker, links.identity, self.linearize_link, *args)
masks = []
mask = np.ones(feature_size, dtype=np.bool) * (self.perturbation == "remove")
masks.append(mask.copy())
ordered_inds = self.sort_order_map(sample_attributions)
increment = max(1,int(feature_size*percent))
for j in range(0, feature_size, increment):
oind_list = [ordered_inds[l] for l in range(j, min(feature_size, j+increment))]
for oind in oind_list:
if not ((self.sort_order == "positive" and sample_attributions[oind] <= 0) or \
(self.sort_order == "negative" and sample_attributions[oind] >= 0)):
mask[oind] = self.perturbation == "keep"
masks.append(mask.copy())
mask_vals.append(masks)
# mask_size = len(range(0, feature_size, increment)) + 1
values = []
masks_arr = np.array(masks)
for j in range(0, len(masks_arr), batch_size):
values.append(self.masked_model(masks_arr[j:j + batch_size]))
values = np.concatenate(values)
svals.append(values)
if pbar is None and time.time() - start_time > 5:
pbar = tqdm(total=len(model_args[0]), disable=silent, leave=False, desc="SequentialMasker")
pbar.update(i+1)
if pbar is not None:
pbar.update(1)
if pbar is not None:
pbar.close()
self.score_values.append(np.array(svals))
# if self.sort_order == "negative":
# curve_sign = -1
# else:
curve_sign = 1
self.labels.append(label)
xs = np.linspace(0, 1, 100)
curves = np.zeros((len(self.score_values[-1]), len(xs)))
for j in range(len(self.score_values[-1])):
xp = np.linspace(0, 1, len(self.score_values[-1][j]))
yp = self.score_values[-1][j]
curves[j,:] = np.interp(xs, xp, yp)
ys = curves.mean(0)
std = curves.std(0)
auc = sklearn.metrics.auc(np.linspace(0, 1, len(ys)), curve_sign*(ys-ys[0]))
if not debug_mode:
return BenchmarkResult(self.perturbation + " " + self.sort_order, name, curve_x=xs, curve_y=ys, curve_y_std=std)
else:
aucs = []
for j in range(len(self.score_values[-1])):
curve = curves[j,:]
auc = sklearn.metrics.auc(np.linspace(0, 1, len(curve)), curve_sign*(curve-curve[0]))
aucs.append(auc)
return mask_vals, curves, aucs
def score(self, explanation, X, percent=0.01, y=None, label=None, silent=False, debug_mode=False):
'''
Will be deprecated once MaskedModel is in complete support
'''
# if explainer is already the attributions
if safe_isinstance(explanation, "numpy.ndarray"):
attributions = explanation
elif isinstance(explanation, Explanation):
attributions = explanation.values
if label is None:
label = "Score %d" % len(self.score_values)
# convert dataframes
if safe_isinstance(X, "pandas.core.series.Series") or safe_isinstance(X, "pandas.core.frame.DataFrame"):
X = X.values
# convert all single-sample vectors to matrices
if not hasattr(attributions[0], "__len__"):
attributions = np.array([attributions])
if not hasattr(X[0], "__len__") and self.data_type == "tabular":
X = np.array([X])
pbar = None
start_time = time.time()
svals = []
mask_vals = []
for i in range(len(X)):
if self.data_type == "image":
x_shape, y_shape = attributions[i].shape[0], attributions[i].shape[1]
feature_size = np.prod([x_shape, y_shape])
sample_attributions = attributions[i].mean(2).reshape(feature_size, -1)
else:
feature_size = attributions[i].shape[0]
sample_attributions = attributions[i]
if len(attributions[i].shape) == 1 or self.data_type == "tabular":
output_size = 1
else:
output_size = attributions[i].shape[-1]
for k in range(output_size):
if self.data_type == "image":
mask_shape = X[i].shape
else:
mask_shape = feature_size
mask = np.ones(mask_shape, dtype=np.bool) * (self.perturbation == "remove")
masks = [mask.copy()]
values = np.zeros(feature_size+1)
# masked, data = self.masker(mask, X[i])
masked = self.masker(mask, X[i])
data = None
curr_val = self.f(masked, data, k).mean(0)
values[0] = curr_val
if output_size != 1:
test_attributions = sample_attributions[:,k]
else:
test_attributions = sample_attributions
ordered_inds = self.sort_order_map(test_attributions)
increment = max(1,int(feature_size*percent))
for j in range(0, feature_size, increment):
oind_list = [ordered_inds[l] for l in range(j, min(feature_size, j+increment))]
for oind in oind_list:
if not ((self.sort_order == "positive" and test_attributions[oind] <= 0) or \
(self.sort_order == "negative" and test_attributions[oind] >= 0)):
if self.data_type == "image":
xoind, yoind = oind // attributions[i].shape[1], oind % attributions[i].shape[1]
mask[xoind][yoind] = self.perturbation == "keep"
else:
mask[oind] = self.perturbation == "keep"
masks.append(mask.copy())
# masked, data = self.masker(mask, X[i])
masked = self.masker(mask, X[i])
curr_val = self.f(masked, data, k).mean(0)
for l in range(j, min(feature_size, j+increment)):
values[l+1] = curr_val
svals.append(values)
mask_vals.append(masks)
if pbar is None and time.time() - start_time > 5:
pbar = tqdm(total=len(X), disable=silent, leave=False)
pbar.update(i+1)
if pbar is not None:
pbar.update(1)
if pbar is not None:
pbar.close()
self.score_values.append(np.array(svals))
if self.sort_order == "negative":
curve_sign = -1
else:
curve_sign = 1
self.labels.append(label)
xs = np.linspace(0, 1, 100)
curves = np.zeros((len(self.score_values[-1]), len(xs)))
for j in range(len(self.score_values[-1])):
xp = np.linspace(0, 1, len(self.score_values[-1][j]))
yp = self.score_values[-1][j]
curves[j,:] = np.interp(xs, xp, yp)
ys = curves.mean(0)
if debug_mode:
aucs = []
for j in range(len(self.score_values[-1])):
curve = curves[j,:]
auc = sklearn.metrics.auc(np.linspace(0, 1, len(curve)), curve_sign*(curve-curve[0]))
aucs.append(auc)
return mask_vals, curves, aucs
else:
auc = sklearn.metrics.auc(np.linspace(0, 1, len(ys)), curve_sign*(ys-ys[0]))
return xs, ys, auc
def plot(self, xs, ys, auc):
pl.plot(xs, ys, label="AUC %0.4f" % auc)
pl.legend()
xlabel = "Percent Unmasked" if self.perturbation == "keep" else "Percent Masked"
pl.xlabel(xlabel)
pl.ylabel("Model Output")
pl.show()