-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
1401 lines (1275 loc) · 59.7 KB
/
train.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Taken from this tutorial: https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html
import os
from typing import Tuple
import torch
from torch import nn, optim
import yaml
import argparse
import random
import os
import numpy as np
import torch.nn.functional as F
import re
from src.utils.utils import (
proto_loss,
load_model_and_dataloader,
get_optimizer,
get_scheduler,
project,
prototype_visualization,
get_nearest,
mean_pooling,
)
import IPython
from tqdm import tqdm
from src.models.models import ProtoNet
from transformers import AutoTokenizer, AutoModel
import pandas as pd
def set_seed(seed):
"""Set all random seeds
Args:
seed (int): integer for reproducible experiments
"""
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
def main(config, random_state=0, run_nr=0):
"""Main function
Args:
config: configuration dictionary
random_state (default = 0): integer for reproducible experiments
"""
use_cuda = torch.cuda.is_available()
print("Cuda is available: ", use_cuda)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
set_seed(random_state)
verbose = config["train"]["verbose"]
gpt2_bert_lm = config["model"]["name"] in ["gpt2", "bert_baseline"]
val_loss_min = float("inf")
# load model and data
(
model,
train_loader,
val_loader,
test_loader,
train_ds,
train_loader_unshuffled,
test_ds,
) = load_model_and_dataloader(config, device)
# prepare teh optimizer
optimizer = get_optimizer(model, config)
scheduler = get_scheduler(optimizer, config)
# loss function
criterion = nn.CrossEntropyLoss()
# training loop
epochs = config["train"]["epochs"]
if config["train"]["run_training"]:
for epoch in range(epochs):
# training loop
train(
model,
train_loader,
optimizer,
criterion,
epoch,
epochs,
device,
verbose,
gpt2_bert_lm,
)
# Validation loop
val_loss = val(
model,
val_loader,
criterion,
epoch,
epochs,
device,
verbose,
gpt2_bert_lm,
)
if isinstance(model, ProtoNet):
# project prototypes all 5 Epochs. Start projection after 50% of epochs and let last 3 epochs be only final layer training
if (
(epoch + 1) % 5 == 0
and config["model"]["project"]
and (epochs * 5 // 10) < (epoch + 1) < (epochs - 3)
):
with torch.no_grad():
model = project(config, model, train_loader, device, False)
assert model.protolayer.requires_grad == True
# final projection, train only classification layer
if (epoch + 1) == (epochs - 3):
with torch.no_grad():
model = project(config, model, train_loader, device, True)
model.protolayer.requires_grad = False
if hasattr(model, "dim_weights"):
model.dim_weights.requires_grad = False
scheduler.step()
torch.save(
model.state_dict(),
f"./saved_models_{config['model']['submodel']}/best_"
+ config["name"]
+ "_"
+ str(run_nr)
+ ".pth",
)
model.load_state_dict(
torch.load(f"./saved_models_{config['model']['submodel']}/best_" + config["name"] + "_" + str(run_nr) + ".pth")
)
test_accuracy, comp, suff = test(model, test_loader, criterion, device, verbose, abstractive=True)
#if config["explain"]["manual_input"] != True:
# comp_extract, suff_extract = comp_and_suff(config, model, test_ds, train_ds, test_loader, train_loader_unshuffled, device)
# Visualize the prototypes
if config["model"]["embedding"] == "sentence" and config["prototype_visualisation"]:
important_words = prototype_visualization(
config, model, train_ds, train_loader_unshuffled, device
)
# Create explanation CSV
explain(
config,
model,
test_ds,
train_ds,
test_loader,
train_loader_unshuffled,
important_words,
device,
)
# Check the faithfullness. Only if we did not add manual sentences as otherwise faithfulness is distorted by them
if config["explain"]["manual_input"] != True:
for i in range(1, 4):
faithful(config, model, test_ds, test_loader, device, k=i)
return test_accuracy, comp, suff
def train(
model,
train_loader,
optimizer,
criterion,
epoch,
epochs,
device,
verbose,
gpt2_bert_lm,
):
"""Main training loop, where the network is trained
Args:
model: our pytorch model
train_loader: loader with the training data
optimizer: optimizer for backpropagation
criterion: loss function
epoch: current epoch
epochs: max number of epochs
device: current device (cpu or gpu)
verbose: if the training is printed
gpt2_bert_lm: true if we use such backbones
"""
if verbose:
train_loader = tqdm(train_loader)
total_acc, total_count = 0, 0
# Training Loop
model.train()
for idx, (label, text, mask) in enumerate(train_loader):
text, label, mask = text.to(device), label.to(device), mask.to(device)
optimizer.zero_grad()
if isinstance(model, ProtoNet):
predicted_label, prototype_distances = model(text, mask)
else:
predicted_label = model(text, mask)
ce_loss = criterion(predicted_label, label)
if isinstance(model, ProtoNet):
distr_loss, clust_loss, sep_loss, divers_loss, l1_loss = proto_loss(
prototype_distances, label, model, config, device
)
loss = (
ce_loss
+ config["loss"]["lambda1"] * distr_loss
+ config["loss"]["lambda2"] * clust_loss
+ config["loss"]["lambda3"] * sep_loss
+ config["loss"]["lambda4"] * divers_loss
+ config["loss"]["lambda5"] * l1_loss
)
else:
loss = ce_loss
loss.backward()
optimizer.step()
if isinstance(model, ProtoNet):
with torch.no_grad():
model.fc.weight.copy_(model.fc.weight.clamp(max=0.0))
if hasattr(model, "dim_weights"):
model.dim_weights.copy_(model.dim_weights.clamp(min=0.0))
# calculate metric
total_acc += (predicted_label.argmax(1) == label).sum().item()
total_count += label.size(0)
if verbose:
train_loader.set_description(f"Epoch [{epoch}/{epochs}]")
train_loader.set_postfix(loss=loss.item(), acc=total_acc / total_count)
"""print(
"| epoch {:3d} | training accuracy {:8.3f}".format(
epoch, total_acc / total_count
)
)"""
def val(model, val_loader, criterion, epoch, epochs, device, verbose, gpt2_bert_lm):
"""Main validation loop, where the network is validated during trianing
Args:
model: our pytorch model
val_loader: loader with the validation data
criterion: loss function
epoch: current epoch
epochs: max number of epochs
device: current device (cpu or gpu)
verbose: if the training is printed
gpt2_bert_lm: true if we use such backbones
"""
val_total_acc, val_total_count, val_losses = 0, 0, []
if verbose:
val_loader = tqdm(val_loader)
# Validation Loop
model.eval()
with torch.no_grad():
for idx, (label, text, mask) in enumerate(val_loader):
text, label, mask = text.to(device), label.to(device), mask.to(device)
if isinstance(model, ProtoNet):
predicted_label, prototype_distances = model(text, mask)
else:
predicted_label = model(text, mask)
"""predicted_label = (
predicted_label.logits if gpt2_bert_lm else predicted_label
)"""
# calc loss
val_ce_loss = criterion(predicted_label, label)
if isinstance(model, ProtoNet):
distr_loss, clust_loss, sep_loss, divers_loss, l1_loss = proto_loss(
prototype_distances, label, model, config, device
)
val_loss = (
val_ce_loss
+ config["loss"]["lambda1"] * distr_loss
+ config["loss"]["lambda2"] * clust_loss
+ config["loss"]["lambda3"] * sep_loss
+ config["loss"]["lambda4"] * divers_loss
+ config["loss"]["lambda5"] * l1_loss
)
else:
val_loss = val_ce_loss
val_losses.append(val_loss)
val_total_acc += (predicted_label.argmax(1) == label).sum().item()
val_total_count += label.size(0)
if verbose:
val_loader.set_description(f"Epoch [{epoch}/{epochs}]")
val_loader.set_postfix(
loss=val_loss.item(), acc=val_total_acc / val_total_count
)
val_loss = sum(val_losses) / len(val_losses)
# end of epoch
"""print(
"| epoch {:3d} | validation accuracy {:8.3f}".format(
epoch, val_total_acc / val_total_count
)
)"""
return val_loss
def test(model, test_loader, criterion, device, verbose, abstractive=False):
"""Main test loop, where the network is tested in the end
Args:
model: our pytorch model
test_loader: loader with the validation data
criterion: loss function
device: current device (cpu or gpu)
verbose: if the training is printed
k: top prototype to remove
"""
# Test the model
if verbose:
test_loader = tqdm(test_loader)
model.eval()
total_acc, total_count = 0, 0
test_losses = []
with torch.no_grad():
df = pd.DataFrame()
outcomes = []
predictions = []
for idx, (label, text, mask) in enumerate(test_loader):
text, label, mask = text.to(device), label.to(device), mask.to(device)
if isinstance(model, ProtoNet):
predicted_label, prototype_distances = model(text, mask)
else:
predicted_label = model(text, mask)
test_ce_loss = criterion(predicted_label, label)
if isinstance(model, ProtoNet):
distr_loss, clust_loss, sep_loss, divers_loss, l1_loss = proto_loss(
prototype_distances, label, model, config, device
)
test_loss = (
test_ce_loss
+ config["loss"]["lambda1"] * distr_loss
+ config["loss"]["lambda2"] * clust_loss
+ config["loss"]["lambda3"] * sep_loss
+ config["loss"]["lambda4"] * divers_loss
+ config["loss"]["lambda5"] * l1_loss
)
else:
test_loss = test_ce_loss
test_losses.append(test_loss)
total_acc += (predicted_label.argmax(1) == label).sum().item()
predictions.append(predicted_label.argmax(1))
outcomes.append(label)
total_count += label.size(0)
predictions = torch.concat(predictions)
outcomes = torch.concat(outcomes)
df["outcomes"] = outcomes.cpu().numpy()
df["predictions"] = predictions.cpu().numpy()
lower, upper = bootstrap(df)
print("Test Loss: ", sum(test_losses) / len(test_losses))
print(
f"Test Accuracy: {total_acc / total_count:.4f} (95%-CI: {lower: .4f}, {upper:.4f})",
)
if abstractive:
prediction_proba = []
prediction_proba_perturbed = []
prediction_proba_onlyprototype = []
weights = model.fc.weight.detach().clone()
labels = []
for idx, (label, text, mask) in enumerate(test_loader):
model.fc.weight.copy_(weights)
text, label, mask = text.to(device), label.to(device), mask.to(device)
# Extract the similarity score and the top prototype
predicted_label_k, prototype_distances_k = model(text, mask)
predicted = (
torch.argmax(predicted_label_k, dim=-1).squeeze().cpu().detach()
)
prediction_proba.append(torch.softmax(predicted_label_k, axis=1))
# Remove prototype
weights_new = weights.clone()
similarity_score = (
prototype_distances_k.squeeze()
* weights_new[predicted, :]
)
top_k = torch.argsort(similarity_score, descending=True)[0]
# set the weights of the best prototype to zero and make a prediction
weights_new[:,top_k] = torch.zeros(config["model"]["n_classes"]).to(
device
)
model.fc.weight.copy_(weights_new)
# Rerun predictions with new weights
predicted_label_k, prototype_distances_k = model(text, mask)
prediction_proba_perturbed.append(torch.softmax(predicted_label_k, axis=1))
# set the weights of the best prototype to zero and make a prediction
weights_new = weights.clone()
top_k = torch.argsort(similarity_score, descending=True)[1:]
weights_new[:,top_k] = torch.zeros(config["model"]["n_classes"], 10*config["model"]["n_classes"]-1).to(
device
)
model.fc.weight.copy_(weights_new)
# Rerun predictions with new weights
predicted_label_k, prototype_distances_k = model(text, mask)
prediction_proba_onlyprototype.append(torch.softmax(predicted_label_k, axis=1))
prediction_proba = torch.concat(prediction_proba)
prediction_proba_perturbed = torch.concat(prediction_proba_perturbed)
prediction_proba_onlyprototype = torch.concat(prediction_proba_onlyprototype)
predicted_classes = torch.argmax(prediction_proba, axis=1)
predicted_classes_perturbed = torch.argmax(prediction_proba_perturbed, axis=1)
predicted_classes_onlyprototype = torch.argmax(prediction_proba_onlyprototype, axis=1)
comp = (prediction_proba[torch.arange(prediction_proba.size(0)), predicted_classes] - prediction_proba_perturbed[torch.arange(prediction_proba_perturbed.size(0)), predicted_classes_perturbed]).mean()
suff = (prediction_proba[torch.arange(prediction_proba.size(0)), predicted_classes] - prediction_proba_onlyprototype[torch.arange(prediction_proba_onlyprototype.size(0)), predicted_classes_onlyprototype]).mean()
print(f"Accuracy Original: {(predicted_classes == outcomes).to(float).mean():.4f}")
print(f"Accuracy Perturbed (no rat): {(predicted_classes_perturbed == outcomes).to(float).mean():.4f}")
print(f"Accuracy Perturbed (only rat): {(predicted_classes_onlyprototype == outcomes).to(float).mean():.4f}")
print(f"Sufficiency: {suff:.4f}")
print(f"Comprehensiveness: {comp:.4f}")
return total_acc / total_count, comp, suff
def bootstrap(df) -> Tuple:
"""Bootstrap for calculating the confidence interval of a metric function
Args:
df (pd.DataFrame): dataframe containing 'predictions' and ' outcomes'
func (function): metric function that takes (y_true, y_pred) as parameters
Returns:
lower, upper 95% confidence interval
full bootstrap
"""
aucs = []
for i in range(1000):
sample = df.sample(
n=df.shape[0], random_state=i, replace=True
) # take 80% for the bootstrap
aucs.append((sample["outcomes"] == sample["predictions"]).sum() / len(df))
return np.percentile(np.array(aucs), 2.5), np.percentile(np.array(aucs), 97.5)
def bootstrap_faithfulness(df) -> Tuple:
"""Bootstrap for calculating the confidence interval of a metric function
Args:
df: dataframe containing 'predictions' and ' outcomes'
Returns:
lower, upper 95% confidence interval
full bootstrap
"""
aucs = []
for i in range(1000):
sample = pd.DataFrame(df).sample(
n=df.shape[0], random_state=i, replace=True
) # take 80% for the bootstrap
aucs.append(sample.mean())
return np.percentile(np.array(aucs), 2.5), np.percentile(np.array(aucs), 97.5)
def explain(
config,
model,
test_ds,
train_ds,
test_loader,
train_batches_unshuffled,
important_words,
device,
):
"""Create explanation CSV file of the model, using the first 50 testing samples
Args:
config: configuration dictionary
model: classification model
test_ds: test dataset (contains the texts)
train_ds: training dataset (contains the texts)
test_loader: test loader, which contains the embeddings and masks
train_batches_unshuffled: train loader, unshuffled, with embeddings and masks
important_words: list of lists with the most important words of the prototypes
device: current device
"""
model.eval()
text_train = []
labels_train = []
text_test = []
labels_test = []
embedding_test = torch.Tensor([])
mask_test = torch.Tensor([])
# Extract all the texts and embeddings to loop through them
for y, x in train_ds:
labels_train.append(y - 1)
text_train.append(x)
for y, x in test_ds:
labels_test.append(y - 1)
text_test.append(x)
for _, x, m in test_loader:
embedding_test = torch.cat([embedding_test, x])
mask_test = torch.cat([mask_test, m])
# Get the prototypes
_, proto_texts, _ = get_nearest(
model, train_batches_unshuffled, text_train, labels_train, device
)
import csv
# Write prototypes to CSV
save_path_prototypes = os.path.join("./explanations", config["name"] + "_prototypes.csv")
with open(save_path_prototypes, "w", newline="") as f:
proto_texts_for_csv = ["prototypes"] + proto_texts
proto_texts_for_csv = [[proto] for proto in proto_texts_for_csv]
writer = csv.writer(f)
writer.writerows(proto_texts_for_csv)
weights = model.get_proto_weights()
explained_test_samples = []
with torch.no_grad():
# Create the first values, which are a description how to read the CSV
values = [
f"test sample",
f"true label",
f"predicted label",
f"probability class 0",
f"probability class 1",
]
for j in range(config["explain"]["max_numbers"]):
values.append(f"explanation_{j + 1}")
values.append(f"keywords_prototype_{j+1}")
values.append(f"keywords_sentence_{j+1}")
values.append(f"score_{j + 1}")
values.append(f"id_{j + 1}")
values.append(f"similarity_{j + 1}")
values.append(f"weight_{j + 1} ")
explained_test_samples.append(values)
# Initialize for Test & Protovisualization
if (
config["model"]["embedding"] == "sentence"
and config["model"]["submodel"] == "bert"
):
tokenizer = AutoTokenizer.from_pretrained(
"sentence-transformers/bert-large-nli-mean-tokens"
)
model_emb = AutoModel.from_pretrained(
"sentence-transformers/bert-large-nli-mean-tokens"
)
elif (
config["model"]["embedding"] == "sentence"
and config["model"]["submodel"] == "roberta"
):
tokenizer = AutoTokenizer.from_pretrained(
"sentence-transformers/all-distilroberta-v1"
)
model_emb = AutoModel.from_pretrained(
"sentence-transformers/all-distilroberta-v1"
)
elif (
config["model"]["embedding"] == "sentence"
and config["model"]["submodel"] == "mpnet"
):
tokenizer = AutoTokenizer.from_pretrained(
"sentence-transformers/all-mpnet-base-v2"
)
model_emb = AutoModel.from_pretrained(
"sentence-transformers/all-mpnet-base-v2"
)
if config["explain"]["manual_input"] == True:
manual_sentences = [
"NLP is a really interesting course!",
"NLP is not an interesting course!",
"NLP is not not an interesting course!",
"The movie's plot was just mediocre, but the stunning performance by Joaquin Phoenix will make the flick a hit.",
]
tokenized_proto = tokenizer(
manual_sentences, padding=True, truncation=True, return_tensors="pt"
)
# Compute token embeddings
with torch.no_grad():
model_output = model_emb(**tokenized_proto)
# Perform pooling. In this case, mean pooling.
manual_sentence_embeddings = mean_pooling(
model_output, tokenized_proto["attention_mask"]
).to(device)
for z in range(len(manual_sentences)):
mask = (
tokenized_proto["attention_mask"][z]
.to(device)
.unsqueeze(0)
.unsqueeze(0)
)
emb_manual = (
manual_sentence_embeddings[z].to(device).unsqueeze(0).unsqueeze(0)
)
predicted_label, prototype_distances = model.forward(emb_manual, mask)
predicted = (
torch.argmax(predicted_label, dim=-1).squeeze().cpu().detach()
)
probability = (
torch.nn.functional.softmax(predicted_label, dim=-1)
.squeeze()
.tolist()
)
similarity_score = (
prototype_distances.cpu().detach().squeeze()
* weights[:, predicted].T
)
top_scores = similarity_score
# Sort the best scoring prototypes and add them to the explanation CSV
sorted = torch.argsort(top_scores, descending=True)
# Create Variations of all Sentence Embeddings by removing one word
keep_words = []
nearest_vals, _ = model.get_dist(emb_manual, _)
for nth_proto in range(config["explain"]["max_numbers"]):
text_strings = manual_sentences[z]
nearest_val_proto = (
nearest_vals[:, sorted[nth_proto]].cpu().detach().numpy()
)
top_words = np.min(
(5, len(re.findall(r"[\w']+|[.,\":\[\]!?;]", text_strings)))
)
text_words = []
text_distance = np.empty(top_words)
for nth_removed_word in range(
top_words
): # Iteratively remove most important words
text = re.findall(r"[\w']+|[.,\":\[\]!?;]", text_strings)
sentence_variants = [
text[:i] + text[i + 1 :] for i in range(len(text))
]
left_word = [text[i] for i in range(len(text))]
sentence_variants = [" ".join(i) for i in sentence_variants]
tokenized_text = tokenizer(
sentence_variants,
padding=True,
truncation=True,
return_tensors="pt",
)
# Compute token embeddings
with torch.no_grad():
model_output = model_emb(**tokenized_text)
# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(
model_output, tokenized_text["attention_mask"]
).to(device)
# Calculate distance to orginial embedding of sentence.
dist_per_word, _ = model.get_dist(
sentence_embeddings.unsqueeze(1), _
)
dist_per_word = dist_per_word[:, sorted[nth_proto]]
farthest_val, farthest_ids = torch.topk(
dist_per_word, 1, dim=0, largest=True
) # Store largest distance
text_words.append(left_word[farthest_ids])
text_distance[nth_removed_word] = farthest_val
text_strings = sentence_variants[farthest_ids]
# Choose words that give 75% of distance of all 5 words
proto_word_dist = text_distance - nearest_val_proto
# Check that removing words made words move away
if proto_word_dist[-1] < 0:
cutoff = proto_word_dist >= 0
else:
cutoff = proto_word_dist <= 0.75 * proto_word_dist[-1]
# Include the word responsible for the 75% drop
cutoff[sum(cutoff)] = True
keep_words.append([text_words[i] for i in np.where(cutoff)[0]])
# Calculate important words of prototypes wrt Sentence
protos_words = []
for nth_proto in range(config["explain"]["max_numbers"]):
proto_strings = proto_texts[sorted[nth_proto]]
nearest_val_proto = (
nearest_vals[:, sorted[nth_proto]].cpu().detach().numpy()
)
top_words = np.min(
(5, len(re.findall(r"[\w']+|[.,\":\[\]!?;]", proto_strings)))
)
proto_words = []
proto_distance = np.empty(top_words)
for nth_removed_word in range(
top_words
): # Iteratively remove most important words
prototype = re.findall(r"[\w']+|[.,\":\[\]!?;]", proto_strings)
sentence_variants = [
prototype[:i] + prototype[i + 1 :]
for i in range(len(prototype))
]
left_word = [prototype[i] for i in range(len(prototype))]
sentence_variants = [" ".join(i) for i in sentence_variants]
tokenized_proto = tokenizer(
sentence_variants,
padding=True,
truncation=True,
return_tensors="pt",
)
# Compute token embeddings
with torch.no_grad():
model_output = model_emb(**tokenized_proto)
# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(
model_output, tokenized_proto["attention_mask"]
).to(device)
# Calculate distance to of truncated prototype to sentence.
if config["model"]["similaritymeasure"] == "weighted_cosine":
dist_per_word = -torch.sum(
model.dim_weights * sentence_embeddings * emb_manual,
dim=-1,
) / torch.maximum(
(
torch.sqrt(
torch.sum(
model.dim_weights
* torch.square(sentence_embeddings),
dim=-1,
)
)
* torch.sqrt(
torch.sum(
model.dim_weights
* torch.square(emb_manual),
dim=-1,
)
)
),
torch.tensor(1e-8),
)
elif config["model"]["similaritymeasure"] == "cosine":
dist_per_word = -F.cosine_similarity(
emb_manual, sentence_embeddings, dim=-1
)
elif config["model"]["similaritymeasure"] == "L2":
# prototype_distances = -nes_torch(embedding, self.protolayer, dim=-1)
dist_per_word = (
torch.cdist(
sentence_embeddings.float(), emb_manual, p=2
).squeeze(1)
/ np.sqrt(model.dim)
).squeeze(-1)
elif config["model"]["similaritymeasure"] == "L1":
dist_per_word = (
torch.cdist(
sentence_embeddings.float(), emb_manual, p=1
).squeeze(1)
/ model.dim
).squeeze(-1)
elif config["model"]["similaritymeasure"] == "dot_product":
# exp(-x.T*y)
dist_per_word = torch.sum(
emb_manual * sentence_embeddings, dim=-1
)
elif config["model"]["similaritymeasure"] == "learned":
# x.T*W*y
hW = torch.matmul(
emb_manual, (model.W / torch.linalg.norm(model.W))
)
dist_per_word = torch.sum(hW * sentence_embeddings, dim=-1)
else:
raise NotImplemented
farthest_val, farthest_ids = torch.topk(
dist_per_word.squeeze(0), 1, dim=0, largest=True
) # Store largest distance
proto_words.append(left_word[farthest_ids])
proto_distance[nth_removed_word] = farthest_val
proto_strings = sentence_variants[farthest_ids]
# Choose words that give 75% of distance of all 5 words
proto_word_dist = proto_distance - nearest_val_proto
# Check that removing words made words move away
if proto_word_dist[-1] < 0:
cutoff = proto_word_dist >= 0
else:
cutoff = proto_word_dist <= 0.75 * proto_word_dist[-1]
# Include the word responsible for the 75% drop
cutoff[sum(cutoff)] = True
protos_words.append([proto_words[i] for i in np.where(cutoff)[0]])
values = [
"".join(manual_sentences[z]) + "",
f"{int(10)}",
f"{int(predicted)}",
f"{probability[0]:.3f}",
f"{probability[1]:.3f}",
]
for i, j in enumerate(sorted):
idx = j.item()
nearest_proto = proto_texts[idx]
values.append(f"{nearest_proto}")
values.append(", ".join(protos_words[i]) + "")
values.append(", ".join(keep_words[i]) + "")
values.append(f"{float(top_scores[j]):.3f}")
values.append(f"{idx + 1}")
values.append(f"{float(-prototype_distances.squeeze()[idx]):.3f}")
values.append(f"{float(-weights[idx, predicted]):.3f}")
if i == config["explain"]["max_numbers"] - 1:
break
explained_test_samples.append(values)
# Go through all the test samples and show their closest prototypes
for i in range(len(labels_test)):
emb = embedding_test[i].to(device).unsqueeze(0).unsqueeze(0)
mask = mask_test[i].to(device).unsqueeze(0).unsqueeze(0)
predicted_label, prototype_distances = model.forward(emb, mask)
predicted = torch.argmax(predicted_label, dim=-1).squeeze().cpu().detach()
probability = (
torch.nn.functional.softmax(predicted_label, dim=-1).squeeze().tolist()
)
similarity_score = (
prototype_distances.cpu().detach().squeeze() * weights[:, predicted].T
)
top_scores = similarity_score
# Sort the best scoring prototypes and add them to the explanation CSV
sorted = torch.argsort(top_scores, descending=True)
if i <= 50:
# Create Variations of all Sentence Embeddings by removing one word
keep_words = []
nearest_vals, _ = model.get_dist(emb, _)
for nth_proto in range(config["explain"]["max_numbers"]):
text_strings = text_test[i]
nearest_val_proto = (
nearest_vals[:, sorted[nth_proto]].cpu().detach().numpy()
)
top_words = np.min(
(5, len(re.findall(r"[\w']+|[.,\":\[\]!?;]", text_strings)))
)
text_words = []
text_distance = np.empty(top_words)
for nth_removed_word in range(
top_words
): # Iteratively remove most important words
text = re.findall(r"[\w']+|[.,\":\[\]!?;]", text_strings)
sentence_variants = [
text[:i] + text[i + 1 :] for i in range(len(text))
]
left_word = [text[i] for i in range(len(text))]
sentence_variants = [" ".join(i) for i in sentence_variants]
tokenized_text = tokenizer(
sentence_variants,
padding=True,
truncation=True,
return_tensors="pt",
)
# Compute token embeddings
with torch.no_grad():
model_output = model_emb(**tokenized_text)
# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(
model_output, tokenized_text["attention_mask"]
).to(device)
# Calculate distance to orginial embedding of sentence.
dist_per_word, _ = model.get_dist(
sentence_embeddings.unsqueeze(1), _
)
dist_per_word = dist_per_word[:, sorted[nth_proto]]
farthest_val, farthest_ids = torch.topk(
dist_per_word, 1, dim=0, largest=True
) # Store largest distance
text_words.append(left_word[farthest_ids])
text_distance[nth_removed_word] = farthest_val
text_strings = sentence_variants[farthest_ids]
# Choose words that give 75% of distance of all 5 words
proto_word_dist = text_distance - nearest_val_proto
# Check that removing words made words move away
if proto_word_dist[-1] < 0:
cutoff = proto_word_dist >= 0
else:
cutoff = proto_word_dist <= 0.75 * proto_word_dist[-1]
# Include the word responsible for the 75% drop
cutoff[sum(cutoff)] = True
keep_words.append([text_words[i] for i in np.where(cutoff)[0]])
# Calculate important words of prototypes wrt Sentence
protos_words = []
for nth_proto in range(config["explain"]["max_numbers"]):
proto_strings = proto_texts[sorted[nth_proto]]
nearest_val_proto = (
nearest_vals[:, sorted[nth_proto]].cpu().detach().numpy()
)
top_words = np.min(
(5, len(re.findall(r"[\w']+|[.,\":\[\]!?;]", proto_strings)))
)
proto_words = []
proto_distance = np.empty(top_words)
for nth_removed_word in range(
top_words
): # Iteratively remove most important words
prototype = re.findall(r"[\w']+|[.,\":\[\]!?;]", proto_strings)
sentence_variants = [
prototype[:i] + prototype[i + 1 :]
for i in range(len(prototype))
]
left_word = [prototype[i] for i in range(len(prototype))]
sentence_variants = [" ".join(i) for i in sentence_variants]
tokenized_proto = tokenizer(
sentence_variants,
padding=True,
truncation=True,
return_tensors="pt",
)
# Compute token embeddings
with torch.no_grad():
model_output = model_emb(**tokenized_proto)
# Perform pooling. In this case, mean pooling.
sentence_embeddings = mean_pooling(
model_output, tokenized_proto["attention_mask"]
).to(device)
# Calculate distance to of truncated prototype to sentence.
if config["model"]["similaritymeasure"] == "weighted_cosine":
dist_per_word = -torch.sum(
model.dim_weights * sentence_embeddings * emb, dim=-1
) / torch.maximum(
(
torch.sqrt(
torch.sum(
model.dim_weights
* torch.square(sentence_embeddings),
dim=-1,
)
)
* torch.sqrt(
torch.sum(
model.dim_weights * torch.square(emb),
dim=-1,
)
)
),
torch.tensor(1e-8),
)
elif config["model"]["similaritymeasure"] == "cosine":
dist_per_word = -F.cosine_similarity(
emb, sentence_embeddings, dim=-1
)
elif config["model"]["similaritymeasure"] == "L2":
# prototype_distances = -nes_torch(embedding, self.protolayer, dim=-1)
dist_per_word = (
torch.cdist(
sentence_embeddings.float(), emb, p=2
).squeeze(1)
/ np.sqrt(model.dim)
).squeeze(-1)
elif config["model"]["similaritymeasure"] == "L1":
dist_per_word = (
torch.cdist(
sentence_embeddings.float(), emb, p=1
).squeeze(1)
/ model.dim
).squeeze(-1)
elif config["model"]["similaritymeasure"] == "dot_product":
# exp(-x.T*y)
dist_per_word = torch.sum(emb * sentence_embeddings, dim=-1)
elif config["model"]["similaritymeasure"] == "learned":
# x.T*W*y
hW = torch.matmul(
emb, (model.W / torch.linalg.norm(model.W))
)
dist_per_word = torch.sum(hW * sentence_embeddings, dim=-1)
else:
raise NotImplemented
farthest_val, farthest_ids = torch.topk(
dist_per_word.squeeze(0), 1, dim=0, largest=True
) # Store largest distance
proto_words.append(left_word[farthest_ids])
proto_distance[nth_removed_word] = farthest_val
proto_strings = sentence_variants[farthest_ids]
# Choose words that give 75% of distance of all 5 words
proto_word_dist = proto_distance - nearest_val_proto
# Check that removing words made words move away
if proto_word_dist[-1] < 0:
cutoff = proto_word_dist >= 0
else:
cutoff = proto_word_dist <= 0.75 * proto_word_dist[-1]
# Include the word responsible for the 75% drop