-
Notifications
You must be signed in to change notification settings - Fork 7
/
interpreters.py
336 lines (271 loc) · 11.3 KB
/
interpreters.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
329
330
331
332
333
334
335
336
import numpy as np
from keras import backend as K
from innvestigate.analyzer import BoundedDeepTaylor, GuidedBackprop
import innvestigate.utils as iutils
from keras.layers import Lambda, Layer
from skimage.transform import resize
import tensorflow as tf
epsilon = 1e-20 #20
epsilon_small = 1e-20 #20
class _SoftMax(Layer):
def call(self, x):
return [K.softmax(tmp) for tmp in iutils.to_list(x)]
class _MaskedGuidedBackprop(GuidedBackprop):
def __init__(self,
model,
R_mask,
**kwargs):
super(_MaskedGuidedBackprop, self).__init__(model, neuron_selection_mode="all", **kwargs)
self.initialize_r_mask(R_mask)
def initialize_r_mask(self, R_mask):
"""0か1のベクトルでRが通れる道をターゲットのみに限定
Arguments:
initial_R_mask {[type]} -- [description]
"""
self.R_mask = K.constant(R_mask)
def _head_mapping(self, X):
"""
初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定
"""
initial_R = Lambda(lambda x: (x * self.R_mask))(X)
return initial_R
class GBP(_MaskedGuidedBackprop):
def __init__(self,
model,
target_id,
relu=False,
**kwargs):
"""ターゲット:predictionの値,それ以外0
Arguments:
model {[type]} -- [description]
target_id {[type]} -- [description]
predictions {[type]} -- [description]
"""
self.relu=relu
R_mask = np.zeros(model.output_shape[1])
R_mask[target_id] = 1
super(GBP, self).__init__(model, R_mask=R_mask, **kwargs)
def analyze(self, inputs):
if self.relu:
return np.maximum(super(GBP, self).analyze(inputs), 0)
else:
return super(GBP, self).analyze(inputs)
class _MaskedDeepTaylor(BoundedDeepTaylor):
"""Give any specific path to the DTD
"""
def __init__(self, model, R_mask, **kwargs):
super(_MaskedDeepTaylor, self).__init__(
model, neuron_selection_mode="all", **kwargs)
self.initialize_r_mask(R_mask)
def initialize_r_mask(self, R_mask):
"""Mask R road
Arguments:
initial_R_mask {[type]} -- [description]
"""
self.R_mask = K.constant(R_mask)
def _head_mapping(self, X):
"""Multiplication with the initialized one-hot vector
"""
initial_R = Lambda(lambda x: (x * self.R_mask))(X)
return initial_R
class LRP(_MaskedDeepTaylor):
def __init__(self,
model,
target_id,
relu=False,
low=-1.,
high=1.,
**kwargs):
"""Target value:same as prediction,otherwise:0
Arguments:
model {[type]} -- [description]
target_id {[type]} -- [description]
predictions {[type]} -- [description]
"""
self.relu = relu
R_mask = np.zeros((model.output_shape[1]))
R_mask[target_id] = 1
super(LRP, self).__init__(model, R_mask=R_mask, low=low, high=high, **kwargs)
def analyze(self, inputs):
if self.relu:
return np.maximum(super(LRP, self).analyze(inputs), 0)
else:
return super(LRP, self).analyze(inputs)
class _LRPSubtraction(object):
def __init__(self,
model,
target_id,
scaling=True,
**kwargs):
self.model = model
self.target_id = target_id
self.scaling = scaling
self.target_analyzer = self._get_target_analyzer(**kwargs)
self.others_analyzer = self._get_others_analyzer(**kwargs)
def _get_target_analyzer(self, **kwargs):
raise NotImplementedError
def _get_others_analyzer(self, **kwargs):
raise NotImplementedError
def analyze_target(self, inputs):
return self.target_analyzer.analyze(inputs)
def analyze_others(self, inputs):
return self.others_analyzer.analyze(inputs)
def analyze(self, inputs):
analysis_target = self.analyze_target(inputs)
analysis_others = self.analyze_others(inputs)
# 画像毎にスケーリング調整
equal_magnification = 1
if self.scaling:
#equal_magnification = analysis_target.sum(axis=(1, 2, 3), keepdims=True) / analysis_others.sum(axis=(1, 2, 3), keepdims=True)
equal_magnification = tf.reduce_sum(analysis_target, axis=(1, 2, 3), keepdims=True) / (tf.reduce_sum(analysis_others, axis=(1, 2, 3), keepdims=True) + epsilon)
analysis = analysis_target - analysis_others * equal_magnification
return analysis
class _CLRPBase(BoundedDeepTaylor):
def __init__(self,
model,
target_id,
**kwargs):
super(_CLRPBase, self).__init__(
model, neuron_selection_mode="all", **kwargs)
self.target_id = target_id
self.class_num = model.output_shape[1]
self.initialize_r_mask()
def initialize_r_mask(self):
raise NotImplementedError
def _head_mapping(self, X):
target_value = Lambda(lambda x: (x[:, self.target_id]))(X)
X = Lambda(lambda x: (x[:, None] * self.R_mask))(target_value)
return X
class _CLRPTarget(_CLRPBase):
def initialize_r_mask(self):
R_mask = np.zeros(self.class_num)
R_mask[self.target_id] = 1
self.R_mask = K.constant(R_mask)
class _CLRPOthers(_CLRPBase):
"""R dual for CLRP1
"""
def initialize_r_mask(self):
R_mask = np.ones(self.class_num)
R_mask[self.target_id] = 0
R_mask /= self.class_num - 1
self.R_mask = K.constant(R_mask)
class CLRP(_LRPSubtraction):
def __init__(self,
model,
target_id,
relu=False,
low=-1.,
high=1.,
**kwargs):
super(CLRP, self).__init__(model, target_id=target_id, low=low, high=high, **kwargs)
self.relu = relu
def _get_target_analyzer(self, **kwargs):
return _CLRPTarget(self.model, target_id=self.target_id, **kwargs)
def _get_others_analyzer(self, **kwargs):
return _CLRPOthers(self.model, target_id=self.target_id, **kwargs)
def analyze(self, inputs):
if self.relu:
return np.maximum(super(CLRP, self).analyze(inputs), 0)
else:
return super(CLRP, self).analyze(inputs)
class _SGLRPBase(BoundedDeepTaylor):
"""Initialize R with Softmax Gradient
"""
def __init__(self,
model,
target_id,
**kwargs):
super(_SGLRPBase, self).__init__(model, neuron_selection_mode="all", **kwargs)
self.target_id = target_id
self.class_num = model.output_shape[1]
self.initialize_r_mask()
def initialize_r_mask(self):
raise NotImplementedError
def _head_mapping(self, X):
"""
target:yt,others:ytyj/(1-yt)
"""
#Kronecker_delta = tf.zeros(self.class_num)#np.zeros(self.class_num)
Kronecker_delta = tf.where(tf.equal(tf.range(self.class_num), tf.cast(self.target_id, tf.int32)), tf.ones(self.class_num), tf.zeros(self.class_num))#Kronecker_delta[self.target_id] = 1
#Kronecker_delta = K.constant(Kronecker_delta)
#Inv_Kronecker_delta = tf.ones(self.class_num)#np.ones(self.class_num)
Inv_Kronecker_delta = tf.where(tf.equal(tf.range(self.class_num), tf.cast(self.target_id, tf.int32)), tf.zeros(self.class_num), tf.ones(self.class_num))#Inv_Kronecker_delta[self.target_id] = 0
#Inv_Kronecker_delta = K.constant(Inv_Kronecker_delta)
target_value = Lambda(lambda x: (x[:, self.target_id]))(X)
X = _SoftMax()(X)
X = Lambda(
lambda x: x * (Kronecker_delta) - x * (Inv_Kronecker_delta) * target_value[:, None] / (1 + epsilon - target_value[:, None]),######
output_shape=lambda input_shape: (None, int(input_shape[1])))(X)
# targetかdualかでマスクが変わる
X = Lambda(lambda x: (self.R_mask * x))(X)
return X
class _SGLRPTarget(_SGLRPBase):
def initialize_r_mask(self):
#R_mask = np.zeros(self.class_num)
R_mask = tf.where(tf.equal(tf.range(self.class_num), tf.cast(self.target_id, tf.int32)), tf.ones(self.class_num), tf.zeros(self.class_num))#R_mask[self.target_id] = 1
self.R_mask = R_mask#K.constant(R_mask)
class _SGLRPDual(_SGLRPBase):
def initialize_r_mask(self):
#R_mask = np.ones(self.class_num)
R_mask = tf.where(tf.equal(tf.range(self.class_num), tf.cast(self.target_id, tf.int32)), tf.zeros(self.class_num), tf.ones(self.class_num))#R_mask[self.target_id] = 0
self.R_mask = R_mask#K.constant(R_mask)
class SGLRP(_LRPSubtraction):
def __init__(self,
model,
target_id,
relu=False,
low=-1.,
high=1.,
**kwargs):
super(SGLRP, self).__init__(model, target_id=target_id, low=low, high=high, **kwargs)
self.relu = relu
def _get_target_analyzer(self, **kwargs):
return _SGLRPTarget(self.model, target_id=self.target_id, **kwargs)
def _get_others_analyzer(self, **kwargs):
return _SGLRPDual(self.model, target_id=self.target_id, **kwargs)
def analyze(self, inputs):
if self.relu:
return tf.maximum(super(SGLRP, self).analyze(inputs), epsilon_small)#np.maximum
else:
return super(SGLRP, self).analyze(inputs)
class GradCAM(object):
def __init__(self,
model,
target_id,
layer_name="block5_pool",
relu=False,
**kwargs):
class_output = model.output[:, target_id]
conv_output = model.get_layer(
layer_name).output
grads = K.gradients(class_output, conv_output)[
0]
self.gradient_function = K.function(
[model.input],
[conv_output, grads],
)
self.relu = relu
def analyze(self, inputs):
outputs, grads_vals = self.gradient_function([inputs])
weights = np.mean(grads_vals, axis=(1, 2))
cams = (outputs * weights[:, np.newaxis, np.newaxis, :]).sum(
axis=3, keepdims=True)
resized_cams = resize(cams, np.shape(inputs), mode='reflect', anti_aliasing=True)
if self.relu:
return np.maximum(resized_cams, 0)
else:
return resized_cams
class GuidedGradCAM(object):
def __init__(self,
model,
target_id,
layer_name="block5_pool",
relu=False,
**kwargs):
self.model = model
self.target_id = target_id
self.relu = relu
self.gradcam = GradCAM(self.model, target_id=self.target_id, layer_name=layer_name, relu=relu, **kwargs)
self.guidedbackprop = GBP(self.model, target_id=self.target_id, relu=relu, **kwargs)
def analyze(self, inputs):
return self.gradcam.analyze(inputs) * self.guidedbackprop.analyze(inputs)