-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyEvaluation.py
409 lines (367 loc) · 16.4 KB
/
myEvaluation.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
from scipy.special import softmax
import tensorflow as tf
from sklearn.metrics import precision_recall_curve, auc
import numpy as np
class MyEvaluation:
def __init__(self, label_names, predict, sentence_level, evaluation_level_all=True):
self.label_names = label_names
self.predict = predict
self.sentence_level = sentence_level
self.saved_state = {}
self.evaluation_level_all = evaluation_level_all
def clear_states(self):
"""
This function resets the state memory used by thruthfulness metric
"""
self.saved_state = {}
def fix_instance(self, instance):
"""
This function takes an instance like "The tok ##en ##ized sentence" and transforms it to "The tokenized sentence"
Args:
instance: The input sequence to be fixed from tokenized to original
Return:
new_sentence[1:]: The original sentence
"""
new_sentence = ''
temp_split = instance.split()
for i in range(0,len(temp_split)):
if "##" not in temp_split[i]:
new_sentence = new_sentence + ' ' + temp_split[i]
else:
new_sentence = new_sentence + temp_split[i][2:]
return new_sentence[1:]
def _find_sign(self, weight):
"""
This function identifies the sign of a weight
Args:
weight: The weight of which the sign we want to identify
Return:
sign: The sign of the weights
"""
if weight < 0:
sign = 'negative'
elif weight > 0:
sign = 'positive'
else:
sign = 'neutral'
return sign
def _apply_activation(self, pred1, pred2):
"""
This function identifies the sign of a weight
Args:
weight: The weight of which the sign we want to identify
Return:
predicted_labels: the predicted labels after the softmax or sigmoid functions
"""
if len(self.label_names) == 2:
predicted_labels = softmax([pred1,pred2], axis = 1)
else:
predicted_labels = [pred1,pred2]
a = tf.constant(predicted_labels, dtype = tf.float32)
b = tf.keras.activations.sigmoid(a)
predicted_labels = b.numpy()
return predicted_labels
def nzw(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the nzw/non-zero-weights (complexity) metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
av_nzw: The average nzw score for each interpretation per label
"""
av_nzw = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
if(self.sentence_level == True):
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
non_zero = 0
threshold = 0.01
for i in range(len(interpretation[label])):
if abs(interpretation[label][i]) > threshold:
non_zero += 1
av_nzw.append(non_zero/len(tokens))
else:
av_nzw.append(np.average([]))
return av_nzw
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
non_zero = 0
threshold = 0.000000001
for i in range(len(interpretation[label])):
if abs(interpretation[label][i]) > threshold:
non_zero += 1
av_nzw.append(non_zero/len(tokens[:-2])) # -2 to exclude cls and sep
else:
av_nzw.append(np.average([]))
return av_nzw
def faithfulness(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the faithdulness score (F) metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average faithfulness score for each interpretation per label
"""
avg_diff = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
#print('For label:',self.label_names[label])
absmax_index = np.argmax(interpretation[label])
sign = self._find_sign(interpretation[label][absmax_index])
if sign == 'negative':
absmax_index = np.argmax([abs(i) for i in interpretation[label]])
sign = self._find_sign(interpretation[label][absmax_index])
temp_tokens = tokens.copy()
#print('Argmax:',interpretation[label][absmax_index],'token:',temp_tokens[absmax_index+1])
if self.sentence_level:
temp_tokens[absmax_index] = ''
temp_instance = ' '.join(temp_tokens)
else:
temp_tokens[absmax_index+1] = '[UNK]'
temp_instance = self.fix_instance(' '.join(temp_tokens[1:-1]))
if temp_instance in self.saved_state:
temp_prediction = self.saved_state[temp_instance]
else:
temp_prediction, _, _ = self.predict(temp_instance)
self.saved_state[temp_instance] = temp_prediction
preds = self._apply_activation(prediction, temp_prediction)
if sign == 'positive':
diff = preds[0][label] - preds[1][label]
elif sign == 'negative':
diff = preds[1][label] - preds[0][label]
else: #neutral
diff = (-1)*abs(preds[1][label] - preds[0][label]) #Penalty
avg_diff.append(diff)
else:
avg_diff.append(np.average([]))
return avg_diff
def truthfulness(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the truthfulness metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average truthfulness score for each interpretation per label
"""
avg_diff = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
truthful = 0
my_range = len(tokens) if self.sentence_level else len(tokens)-2
#print('For label:',self.label_names[label])
for token in range(0, my_range):
temp_tokens = tokens.copy()
if self.sentence_level:
temp_tokens[token] = ''
temp_instance = ' '.join(temp_tokens)
else:
temp_tokens[token+1] = '[UNK]'
temp_instance = self.fix_instance(' '.join(temp_tokens[1:-1]))
sign = self._find_sign(interpretation[label][token])
#print('Token:',tokens[token+1],'Sign:',sign,'Weight:',interpretation[label][token])
if temp_instance in self.saved_state:
temp_prediction = self.saved_state[temp_instance]
else:
temp_prediction, _, _ = self.predict(temp_instance)
self.saved_state[temp_instance] = temp_prediction
preds = self._apply_activation(prediction, temp_prediction)
if sign == 'positive':
if preds[0][label] - preds[1][label] > 0:
truthful += 1
elif sign == 'negative':
if preds[1][label] - preds[0][label] > 0:
truthful +=1
else:
if preds[1][label] == preds[0][label]:
truthful +=1
#print('Prevs:',preds[0][label],'Latter:',preds[1][label])
avg_diff.append(truthful/my_range)
else:
avg_diff.append(np.average([]))
return avg_diff
def faithful_truthfulness(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the Faithful Truthfulness score (FT) metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average FT score for each interpretation per label
"""
avg_diff = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all: # :| h gia ola?????? pfff
score = 0
my_range = len(tokens) if self.sentence_level else len(tokens)-2
for token in range(0, my_range):
temp_tokens = tokens.copy()
if self.sentence_level:
temp_tokens[token] = ''
temp_instance = ' '.join(temp_tokens)
else:
temp_tokens[token+1] = '[UNK]'
temp_instance = self.fix_instance(' '.join(temp_tokens[1:-1]))
sign = self._find_sign(interpretation[label][token])
if temp_instance in self.saved_state:
temp_prediction = self.saved_state[temp_instance]
else:
temp_prediction, _, _ = self.predict(temp_instance)
self.saved_state[temp_instance] = temp_prediction
preds = self._apply_activation(prediction, temp_prediction)
if sign == 'positive':
score += preds[0][label] - preds[1][label]
elif sign == 'negative':
score += preds[1][label] - preds[0][label]
else:
score += (-1)*abs(preds[1][label] - preds[0][label]) #Penalty
avg_diff.append(score)
else:
avg_diff.append(np.average([]))
return avg_diff
def faithful_truthfulness_penalty(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the Ranked Faithful Truthfulness score (RFT) metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average RFT score for each interpretation per label
"""
avg_diff = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all: # :| h gia ola?????? pfff
a = interpretation[label]
if np.unique(a).shape[0] == 1:
value_order = {np.unique(a)[0] : a.shape[0]}
else:
order = np.argsort(abs(a))
value_order = dict()
count = 0
size = len(a)
for o in order:
if abs(a[o]) in value_order:
if value_order[abs(a[o])] < size - count:
value_order[abs(a[o])] = size - count
else:
value_order[abs(a[o])] = size - count
count = count + 1
score = 0
my_range = len(tokens) if self.sentence_level else len(tokens)-2
for token in range(0, my_range):
temp_tokens = tokens.copy()
if self.sentence_level:
temp_tokens[token] = ''
temp_instance = ' '.join(temp_tokens)
else:
temp_tokens[token+1] = '[UNK]'
temp_instance = self.fix_instance(' '.join(temp_tokens[1:-1]))
sign = self._find_sign(interpretation[label][token])
if temp_instance in self.saved_state:
temp_prediction = self.saved_state[temp_instance]
else:
temp_prediction, _, _ = self.predict(temp_instance)
self.saved_state[temp_instance] = temp_prediction
preds = self._apply_activation(prediction, temp_prediction)
if sign == 'positive':
score += (preds[0][label] - preds[1][label])/value_order[abs(interpretation[label][token])]
elif sign == 'negative':
score += (preds[1][label] - preds[0][label])/value_order[abs(interpretation[label][token])]
else:
score += (-1)*abs(preds[1][label] - preds[0][label])/value_order[abs(interpretation[label][token])] #Penalty
avg_diff.append(score)
else:
avg_diff.append(np.average([]))
return avg_diff
def robustness(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the Robustness metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average Robustness score for each interpretation per label
"""
avg_diff = []
h = np.linalg.norm(hidden_states[0].mean(axis=0)-t_hidden_states[0].mean(axis=0))
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
diff = interpretation[label]-tweaked_interpretation[label]
norm_l2 = np.linalg.norm(np.array(diff))
if h != 0:
avg_diff.append(norm_l2/h)
else:
avg_diff.append(0)
else:
avg_diff.append(np.average([]))
return avg_diff
def auprc(self, interpretation, tweaked_interpretation, instance, prediction, tokens, hidden_states, t_hidden_states, rationales):
"""
This function evaluates an interpretation uzing the AUPRC metric
Args:
interpretation: The interpretations of the instance's prediction
tweaked_interpretation: The interpretations of the tweaked instance's prediction (useful for robustness)
instance: The input sequence to be fixed from tokenized to original
prediction: The prediction regarding the input sequence
tokens: The input sequence but tokenized
hidden_states: The hidden states reagrding that instance extracted by the model
t_hidden_states: The hidden states reagrding the tweaked instance extracted by the model (useful for robustness)
rationales: The rationales (ground truth explanations - useful for auprc)
Return:
avg_diff: The average AUPRC score for each interpretation per label
"""
aucs = []
predicted_labels = self._apply_activation(prediction, prediction)[0]
for label in range(len(self.label_names)):
if predicted_labels[label]>=0.5 or self.evaluation_level_all:
label_auc = []
if rationales[label] != 0 and sum(rationales[label]) != 0:
precision, recall, _ = precision_recall_curve(rationales[label],interpretation[label])
label_auc.append(auc(recall, precision))
aucs.append(np.average(label_auc))
else:
aucs.append(np.average([]))
return aucs