-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_DocNADE.py
2227 lines (1742 loc) · 95.5 KB
/
train_DocNADE.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
import os
import argparse
import json
import numpy as np
import tensorflow as tf
import model.data as data
import model.model_DocNADE as m
import model.evaluate as eval
import datetime
import json
import sys
import pickle
import codecs
import csv
from nltk.corpus import wordnet
from nltk.stem import WordNetLemmatizer
from gensim.models.keyedvectors import KeyedVectors
import sklearn.metrics.pairwise as pw
from sklearn.metrics import accuracy_score
import BM25
from sklearn.utils.extmath import softmax
os.environ['CUDA_VISIBLE_DEVICES'] = ''
#os.environ['KMP_DUPLICATE_LIB_OK']='True'
seed = 42
tf_op_seed = 1234
np.random.seed(seed)
tf.set_random_seed(seed)
home_dir = os.getenv("HOME")
dir(tf.contrib)
def loadGloveModel(gloveFile=None, params=None):
if gloveFile is None:
if params.hidden_size == 50:
gloveFile = os.path.join(home_dir, "resources/pretrained_embeddings/glove.6B.50d.txt")
elif params.hidden_size == 100:
gloveFile = os.path.join(home_dir, "resources/pretrained_embeddings/glove.6B.100d.txt")
elif params.hidden_size == 200:
gloveFile = os.path.join(home_dir, "resources/pretrained_embeddings/glove.6B.200d.txt")
elif params.hidden_size == 300:
gloveFile = os.path.join(home_dir, "resources/pretrained_embeddings/glove.6B.300d.txt")
else:
print('Invalid dimension [%d] for Glove pretrained embedding matrix!!' %params.hidden_size)
exit()
print("Loading Glove Model")
f = open(gloveFile, 'r')
model = {}
for line in f:
splitLine = line.split()
word = splitLine[0]
embedding = np.array([float(val) for val in splitLine[1:]])
model[word] = embedding
print("Done.", len(model), " words loaded!")
return model
def loadBioModel(BioFile=None, params=None):
print("Loading BioNLP Model")
#model = KeyedVectors.load_word2vec_format('./datasets/PubMed-w2v.bin', binary=True)
model = KeyedVectors.load_word2vec_format('./datasets/PubMed-and-PMC-w2v.bin', binary=True)
print("Binary model loaded!")
return model
def train(model, dataset, params):
log_dir = os.path.join(params.model, 'logs')
model_dir_ir = os.path.join(params.model, 'model_ir')
model_dir_ppl = os.path.join(params.model, 'model_ppl')
model_dir_sup = os.path.join(params.model, 'model_sup')
model_dir_mAP = os.path.join(params.model, 'model_mAP')
with tf.Session(config=tf.ConfigProto(
inter_op_parallelism_threads=params.num_cores,
intra_op_parallelism_threads=params.num_cores,
gpu_options=tf.GPUOptions(allow_growth=True)
)) as session:
avg_loss = tf.placeholder(tf.float32, [], 'loss_ph')
tf.summary.scalar('loss', avg_loss)
validation = tf.placeholder(tf.float32, [], 'validation_ph')
validation_accuracy = tf.placeholder(tf.float32, [], 'validation_acc')
tf.summary.scalar('validation', validation)
tf.summary.scalar('validation_accuracy', validation_accuracy)
summary_writer = tf.summary.FileWriter(log_dir, session.graph)
summaries = tf.summary.merge_all()
saver = tf.train.Saver(tf.global_variables())
tf.local_variables_initializer().run()
tf.global_variables_initializer().run()
losses = []
if params.input_type == "both":
training_filename = 'training_docnade'
validation_filename = 'validation_docnade'
test_filename = 'test_docnade'
elif params.input_type == "abstract":
training_filename = 'training_docnade_abstracts'
validation_filename = 'validation_docnade_abstracts'
test_filename = 'test_docnade_abstracts'
elif params.input_type == "title":
training_filename = 'training_docnade_titles'
validation_filename = 'validation_docnade_titles'
test_filename = 'test_docnade_titles'
else:
print("Wrong value for params.input_type: ", params.input_type)
sys.exit()
if params.use_title_separately:
training_title_filename = 'training_docnade_titles'
validation_title_filename = 'validation_docnade_titles'
test_title_filename = 'test_docnade_titles'
# This currently streams from disk. You set num_epochs=1 and
# wrap this call with something like itertools.cycle to keep
# this data in memory.
# shuffle: the order of words in the sentence for DocNADE
#training_data = dataset.batches('training_docnade', params.batch_size, shuffle=True, multilabel=params.multi_label)
training_data = dataset.batches(training_filename, params.batch_size, shuffle=True, multilabel=params.multi_label)
if params.use_title_separately:
training_title_data = dataset.batches(training_title_filename, params.batch_size, shuffle=True, multilabel=params.multi_label)
id2label = {0:"Acute_Threat_Fear", 1:"Arousal", 2:"Circadian_Rhythms", 3:"Frustrative_Nonreward",
4:"Loss", 5:"Potential_Threat_Anxiety", 6:"Sleep_Wakefulness", 7:"Sustained_Threat"}
with open(params.dataset + "/test_ids.txt", "r") as f:
ids = [line.strip() for line in f.readlines()]
best_val_IR = 0.0
best_val_acc = 0.0
best_val_mAP = 0.0
best_val_nll = np.inf
best_val_ppl = np.inf
best_val_disc_accuracy = 0.0
best_test_IR = 0.0
best_test_nll = np.inf
best_test_ppl = np.inf
best_test_disc_accuracy = 0.0
patience = params.patience
patience_count = 0
patience_count_ir = 0
best_train_nll = np.inf
training_labels = np.array(
#[[y] for y, _ in dataset.rows('training_docnade', num_epochs=1)]
[[y] for y, _ in dataset.rows(training_filename, num_epochs=1)]
)
validation_labels = np.array(
#[[y] for y, _ in dataset.rows('validation_docnade', num_epochs=1)]
[[y] for y, _ in dataset.rows(validation_filename, num_epochs=1)]
)
test_labels = np.array(
#[[y] for y, _ in dataset.rows('test_docnade', num_epochs=1)]
[[y] for y, _ in dataset.rows(test_filename, num_epochs=1)]
)
#initial_weights = session.run("embeddings_lambda_list_unclipped:0")
#np.save(os.path.join(log_dir, "initial_sup_weights.npy"), initial_weights)
for step in range(params.num_steps + 1):
this_loss = -1.
y, x, seq_lengths = next(training_data)
train_feed_dict = {}
train_feed_dict[model.x] = x
train_feed_dict[model.y] = y
train_feed_dict[model.seq_lengths] = seq_lengths
if params.use_title_separately:
y_title, x_title, seq_lengths_title = next(training_title_data)
train_feed_dict[model.x_title] = x_title
train_feed_dict[model.seq_lengths_title] = seq_lengths_title
_, loss, loss_unnormed = session.run([model.opt, model.loss_normed, model.loss_unnormed], feed_dict=train_feed_dict)
this_loss = loss
losses.append(this_loss)
if (step % params.log_every == 0):
print('{}: {:.6f}'.format(step, this_loss))
if step and (step % params.validation_ppl_freq) == 0:
this_val_nll = []
this_val_loss_normed = []
# val_loss_unnormed is NLL
this_val_nll_bw = []
this_val_loss_normed_bw = []
for val_y, val_x, val_seq_lengths in dataset.batches('validation_docnade', params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label):
val_loss_normed, val_loss_unnormed = session.run([model.loss_normed, model.loss_unnormed], feed_dict={
model.x: val_x,
model.y: val_y,
model.seq_lengths: val_seq_lengths
})
this_val_nll.append(val_loss_unnormed)
this_val_loss_normed.append(val_loss_normed)
total_val_nll = np.mean(this_val_nll)
total_val_ppl = np.exp(np.mean(this_val_loss_normed))
if total_val_ppl < best_val_ppl:
best_val_ppl = total_val_ppl
print('saving: {}'.format(model_dir_ppl))
saver.save(session, model_dir_ppl + '/model_ppl', global_step=1)
# Early stopping
if total_val_nll < best_val_nll:
best_val_nll = total_val_nll
patience_count = 0
else:
patience_count += 1
print('This val PPL: {:.3f} (best val PPL: {:.3f}, best val loss: {:.3f}'.format(
total_val_ppl,
best_val_ppl or 0.0,
best_val_nll
))
# logging information
with open(os.path.join(log_dir, "training_info.txt"), "a") as f:
f.write("Step: %i, val PPL: %s, best val PPL: %s, best val loss: %s\n" %
(step, total_val_ppl, best_val_ppl, best_val_nll))
if patience_count > patience:
print("Early stopping criterion satisfied.")
break
if step and (step % params.validation_ir_freq) == 0:
## Classification accuracy
if params.use_title_separately:
validation_title_data = dataset.batches(validation_title_filename, params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label)
validation_filename = 'validation_docnade_abstracts'
val_pred_labels = []
val_pred_logits = []
for val_y, val_x, val_seq_lengths in dataset.batches(validation_filename, params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label):
val_feed_dict = {}
val_feed_dict[model.x] = val_x
val_feed_dict[model.y] = val_y
val_feed_dict[model.seq_lengths] = val_seq_lengths
if params.use_title_separately:
val_y_title, val_x_title, val_seq_lengths_title = next(validation_title_data)
val_feed_dict[model.x_title] = val_x_title
val_feed_dict[model.seq_lengths_title] = val_seq_lengths_title
pred_labels, pred_logits = session.run([model.pred_labels, model.disc_output], feed_dict=val_feed_dict)
#val_pred_labels.append(pred_labels[0][0])
val_pred_labels.append(pred_labels[0])
val_pred_logits.append(pred_logits[0])
val_true_labels = [int(label[0]) for label in validation_labels]
val_acc = accuracy_score(val_true_labels, val_pred_labels)
if val_acc > best_val_acc:
best_val_acc = val_acc
print('saving: {}'.format(model_dir_sup))
saver.save(session, model_dir_sup + '/model_sup', global_step=1)
patience_count_ir = 0
test_pred_labels = []
test_pred_logits = []
for test_y, test_x, test_seq_lengths in dataset.batches(test_filename, params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label):
test_feed_dict = {}
test_feed_dict[model.x] = test_x
test_feed_dict[model.y] = test_y
test_feed_dict[model.seq_lengths] = test_seq_lengths
if params.use_title_separately:
test_y_title, test_x_title, test_seq_lengths_title = next(validation_title_data)
test_feed_dict[model.x_title] = test_x_title
test_feed_dict[model.seq_lengths_title] = test_seq_lengths_title
pred_labels, pred_logits = session.run([model.pred_labels, model.disc_output], feed_dict=test_feed_dict)
#test_pred_labels.append(pred_labels[0][0])
test_pred_labels.append(pred_labels[0])
test_pred_logits.append(pred_logits[0])
test_pred_logits = softmax(np.array(test_pred_logits))
test_true_labels = [int(label[0]) for label in test_labels]
test_acc = accuracy_score(test_true_labels, test_pred_labels)
np.save(os.path.join(log_dir, "test_pred_logits.npy"), np.array(test_pred_logits))
np.save(os.path.join(log_dir, "test_pred_labels.npy"), np.array(test_pred_labels))
np.save(os.path.join(log_dir, "test_true_labels.npy"), np.array(test_true_labels))
docnade_probs = []
for i, label in enumerate(test_true_labels):
docnade_probs.append(test_pred_logits[i, label])
docnade_probs = np.array(docnade_probs)
dict_label = {int(label):[] for label in np.unique(test_true_labels)}
for score, id, label in zip(docnade_probs, ids, test_true_labels):
dict_label[int(label)].append([id,score])
with open(os.path.join(log_dir, "task1_test_docnade_classify.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", "r") as f:
file_reader = csv.reader(f, delimiter=',')
docs = [line[1].strip() for line in file_reader]
bm25 = BM25.BM25("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", delimiter=' ')
def get_bm25_ids(tokens):
ids = []
for token in tokens:
try:
ids.append(bm25.dictionary.token2id[token])
except KeyError:
pass
return ids
bm25_extra_scores_list = []
#for query in queries:
for value in id2label.values():
query = " ".join(value.lower().split("_")).strip()
if query == "frustrative nonreward":
query = "reward aggression"
if query == "arousal":
query += " affective states heart rate"
query = query.split()
scores = bm25.BM25Score(query)
extra_features = []
for doc in docs:
doc = doc.split()
#doc_ids = [bm25.dictionary.token2id[token] for token in doc]
#query_ids = [bm25.dictionary.token2id[token] for token in query]
doc_ids = get_bm25_ids(doc)
query_ids = get_bm25_ids(query)
feats = bm25.query_doc_overlap(query_ids, doc_ids)
extra_features.append(np.sum(feats))
#scores = np.stack([np.array(scores), np.array(extra_features)], axis=1)
scores = np.add(np.array(scores), np.array(extra_features))
bm25_extra_scores_list.append(scores)
bm25_extra_scores_matrix = np.stack(bm25_extra_scores_list, axis=1)
#import pdb; pdb.set_trace()
relevance_score_bm25_extra = []
for i, label in enumerate(test_true_labels):
relevance_score_bm25_extra.append(bm25_extra_scores_matrix[i, int(label)])
relevance_score_bm25_extra = np.array(relevance_score_bm25_extra)
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(relevance_score_bm25_extra, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_bm25extra.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score = docnade_probs + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_with_bm25extra.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
#with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/vocab_docnade.vocab", "r") as f:
with open("./pretrained_embeddings/biggest_vocab.vocab", "r") as f:
total_vocab = [line.strip() for line in f.readlines()]
total_embedding_matrix = np.load('./pretrained_embeddings/fasttext_embeddings_biggest_vocab.npy')
similarity_scores_Attention_Based_EmbSum = np.zeros((len(test_true_labels), 8), dtype=np.float32)
with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", "r") as f:
file_reader = csv.reader(f, delimiter=",")
for j, row in enumerate(file_reader):
tokens = [total_vocab.index(word) for word in row[1].strip().split()]
Embs = total_embedding_matrix[np.array(tokens), :]
#for i, query in enumerate(queries):
for k, value in enumerate(id2label.values()):
query = " ".join(value.lower().split("_")).strip()
if query == "frustrative nonreward":
query = "reward aggression"
if query == "arousal":
query += " affective states heart rate"
query_tokens = query.split()
EmbSum_attns = []
query_vecs_attns = []
for qword in query_tokens:
query_vector = total_embedding_matrix[total_vocab.index(qword), :]
query_vector = np.expand_dims(query_vector, axis=0)
query_attentions = pw.cosine_similarity(query_vector, Embs)
#query_attentions[(query_attentions < 0.5)] = 0.0
query_attentions = softmax(query_attentions)
EmbSum_attentions = np.dot(query_attentions, Embs)
EmbSum_attns.append(EmbSum_attentions)
query_vecs_attns.append(query_vector)
EmbSum = np.sum(EmbSum_attns, axis=0)
#query_EmbSum_vector = np.expand_dims(query_vecs[i], axis=0)
query_EmbSum_vector = np.sum(query_vecs_attns, axis=0)
similarity_score = pw.cosine_similarity(query_EmbSum_vector, EmbSum)
similarity_scores_Attention_Based_EmbSum[j, k] = similarity_score[0][0]
relevance_score_att_embsum = []
for i, label in enumerate(test_true_labels):
relevance_score_att_embsum.append(similarity_scores_Attention_Based_EmbSum[i, int(label)])
relevance_score_att_embsum = np.array(relevance_score_att_embsum)
#combined_relevance_score = relevance_score_svm + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(relevance_score_att_embsum, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_att_based_embsum.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score_classify_embsum = relevance_score_att_embsum + docnade_probs
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score_classify_embsum, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_att_based_embsum.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score_classify_embsum_bm25extra = relevance_score_att_embsum + docnade_probs + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score_classify_embsum_bm25extra, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_att_based_embsum_bm25extra.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
else:
patience_count_ir += 1
print('This val accuracy: {:.3f} (best val accuracy: {:.3f})'.format(
val_acc,
best_val_acc or 0.0
))
# logging information
with open(os.path.join(log_dir, "training_info.txt"), "a") as f:
f.write("Step: %i, val accuracy: %s, best val accuracy: %s\n" %
(step, val_acc, best_val_acc))
if patience_count_ir > patience:
#if (patience_count_ir > patience) or (step > 50):
#final_weights = session.run("embeddings_lambda_list_unclipped:0")
#np.save(os.path.join(log_dir, "final_sup_weights.npy"), final_weights)
print("Early stopping criterion satisfied.")
test_pred_labels = []
test_pred_logits = []
for test_y, test_x, test_seq_lengths in dataset.batches(test_filename, params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label):
test_feed_dict = {}
test_feed_dict[model.x] = test_x
test_feed_dict[model.y] = test_y
test_feed_dict[model.seq_lengths] = test_seq_lengths
if params.use_title_separately:
test_y_title, test_x_title, test_seq_lengths_title = next(validation_title_data)
test_feed_dict[model.x_title] = test_x_title
test_feed_dict[model.seq_lengths_title] = test_seq_lengths_title
pred_labels, pred_logits = session.run([model.pred_labels, model.disc_output], feed_dict=test_feed_dict)
#test_pred_labels.append(pred_labels[0][0])
test_pred_labels.append(pred_labels[0])
test_pred_logits.append(pred_logits[0])
test_pred_logits = softmax(np.array(test_pred_logits))
test_true_labels = [int(label[0]) for label in test_labels]
test_acc = accuracy_score(test_true_labels, test_pred_labels)
np.save(os.path.join(log_dir, "test_pred_logits_last_epoch.npy"), np.array(test_pred_logits))
np.save(os.path.join(log_dir, "test_pred_labels_last_epoch.npy"), np.array(test_pred_labels))
np.save(os.path.join(log_dir, "test_true_labels_last_epoch.npy"), np.array(test_true_labels))
docnade_probs = []
for i, label in enumerate(test_true_labels):
docnade_probs.append(test_pred_logits[i, label])
docnade_probs = np.array(docnade_probs)
dict_label = {int(label):[] for label in np.unique(test_true_labels)}
for score, id, label in zip(docnade_probs, ids, test_true_labels):
dict_label[int(label)].append([id,score])
with open(os.path.join(log_dir, "task1_test_docnade_classify_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", "r") as f:
file_reader = csv.reader(f, delimiter=',')
docs = [line[1].strip() for line in file_reader]
bm25 = BM25.BM25("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", delimiter=' ')
def get_bm25_ids(tokens):
ids = []
for token in tokens:
try:
ids.append(bm25.dictionary.token2id[token])
except KeyError:
pass
return ids
bm25_extra_scores_list = []
#for query in queries:
for value in id2label.values():
query = " ".join(value.lower().split("_")).strip()
if query == "frustrative nonreward":
query = "reward aggression"
if query == "arousal":
query += " affective states heart rate"
query = query.split()
scores = bm25.BM25Score(query)
extra_features = []
for doc in docs:
doc = doc.split()
#doc_ids = [bm25.dictionary.token2id[token] for token in doc]
#query_ids = [bm25.dictionary.token2id[token] for token in query]
doc_ids = get_bm25_ids(doc)
query_ids = get_bm25_ids(query)
feats = bm25.query_doc_overlap(query_ids, doc_ids)
extra_features.append(np.sum(feats))
#scores = np.stack([np.array(scores), np.array(extra_features)], axis=1)
scores = np.add(np.array(scores), np.array(extra_features))
bm25_extra_scores_list.append(scores)
bm25_extra_scores_matrix = np.stack(bm25_extra_scores_list, axis=1)
#import pdb; pdb.set_trace()
relevance_score_bm25_extra = []
for i, label in enumerate(test_true_labels):
relevance_score_bm25_extra.append(bm25_extra_scores_matrix[i, int(label)])
relevance_score_bm25_extra = np.array(relevance_score_bm25_extra)
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(relevance_score_bm25_extra, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_bm25extra_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score = docnade_probs + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_with_bm25extra_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
#with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/vocab_docnade.vocab", "r") as f:
with open("./pretrained_embeddings/biggest_vocab.vocab", "r") as f:
total_vocab = [line.strip() for line in f.readlines()]
total_embedding_matrix = np.load('./pretrained_embeddings/fasttext_embeddings_biggest_vocab.npy')
similarity_scores_Attention_Based_EmbSum = np.zeros((len(test_true_labels), 8), dtype=np.float32)
with open("./datasets/Task1_and_Task2_without_acronym_with_Task1_testdata_OOV_words/test.csv", "r") as f:
file_reader = csv.reader(f, delimiter=",")
for j, row in enumerate(file_reader):
tokens = [total_vocab.index(word) for word in row[1].strip().split()]
Embs = total_embedding_matrix[np.array(tokens), :]
#for i, query in enumerate(queries):
for k, value in enumerate(id2label.values()):
query = " ".join(value.lower().split("_")).strip()
if query == "frustrative nonreward":
query = "reward aggression"
if query == "arousal":
query += " affective states heart rate"
query_tokens = query.split()
EmbSum_attns = []
query_vecs_attns = []
for qword in query_tokens:
query_vector = total_embedding_matrix[total_vocab.index(qword), :]
query_vector = np.expand_dims(query_vector, axis=0)
query_attentions = pw.cosine_similarity(query_vector, Embs)
#query_attentions[(query_attentions < 0.5)] = 0.0
query_attentions = softmax(query_attentions)
EmbSum_attentions = np.dot(query_attentions, Embs)
EmbSum_attns.append(EmbSum_attentions)
query_vecs_attns.append(query_vector)
EmbSum = np.sum(EmbSum_attns, axis=0)
#query_EmbSum_vector = np.expand_dims(query_vecs[i], axis=0)
query_EmbSum_vector = np.sum(query_vecs_attns, axis=0)
similarity_score = pw.cosine_similarity(query_EmbSum_vector, EmbSum)
similarity_scores_Attention_Based_EmbSum[j, k] = similarity_score[0][0]
relevance_score_att_embsum = []
for i, label in enumerate(test_true_labels):
relevance_score_att_embsum.append(similarity_scores_Attention_Based_EmbSum[i, int(label)])
relevance_score_att_embsum = np.array(relevance_score_att_embsum)
#combined_relevance_score = relevance_score_svm + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(relevance_score_att_embsum, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_att_based_embsum_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score_classify_embsum = relevance_score_att_embsum + docnade_probs
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score_classify_embsum, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_att_based_embsum_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
combined_relevance_score_classify_embsum_bm25extra = relevance_score_att_embsum + docnade_probs + relevance_score_bm25_extra
dict_label = {label:[] for label in np.unique(test_true_labels)}
for score, id, label in zip(combined_relevance_score_classify_embsum_bm25extra, ids, test_true_labels):
dict_label[label].append([id,score])
with open(os.path.join(log_dir, "task1_test_classify_att_based_embsum_bm25extra_last_epoch.txt"), "w") as f:
for key in dict_label.keys():
f.write(id2label[int(key)] + "\n")
for id, score in dict_label[key]:
f.write(id + "\t" + str(score) + "\n")
break
#import pdb; pdb.set_trace()
## mAP Calculation
val_pred_probs = eval.softmax(np.array(val_pred_logits), axis=1)
val_pred_probs = val_pred_probs[np.arange(len(val_pred_labels)), np.array(val_pred_labels)]
val_mAP, _, preds_dict, probs_dict, _ = eval.evaluate_mAP(val_true_labels, val_pred_labels, val_pred_probs)
if val_mAP > best_val_mAP:
best_val_mAP = val_mAP
print('saving: {}'.format(model_dir_mAP))
saver.save(session, model_dir_mAP + '/model_mAP', global_step=1)
patience_count_ir = 0
else:
patience_count_ir += 1
print('This val mAP: {:.3f} (best val mAP: {:.3f})'.format(
val_mAP,
best_val_mAP or 0.0
))
# logging information
with open(os.path.join(log_dir, "training_info.txt"), "a") as f:
f.write("Step: %i, val mAP: %s, best val mAP: %s\n" %
(step, val_mAP, best_val_mAP))
if patience_count_ir > patience:
print("Early stopping criterion satisfied.")
break
"""
validation_vectors = m.vectors(
model,
dataset.batches(
'validation_docnade',
params.validation_bs,
num_epochs=1,
shuffle=True,
multilabel=params.multi_label
),
session
)
training_vectors = m.vectors(
model,
dataset.batches(
'training_docnade',
params.validation_bs,
num_epochs=1,
shuffle=True,
multilabel=params.multi_label
),
session
)
val = eval.evaluate(
training_vectors,
validation_vectors,
training_labels,
validation_labels,
recall=[0.02],
num_classes=params.num_classes,
multi_label=params.multi_label
)[0]
if val > best_val_IR:
best_val_IR = val
print('saving: {}'.format(model_dir_ir))
saver.save(session, model_dir_ir + '/model_ir', global_step=1)
patience_count_ir = 0
else:
patience_count_ir += 1
print('This val IR: {:.3f} (best val IR: {:.3f})'.format(
val,
best_val_IR or 0.0
))
# logging information
with open(os.path.join(log_dir, "training_info.txt"), "a") as f:
f.write("Step: %i, val IR: %s, best val IR: %s\n" %
(step, val, best_val_IR))
if patience_count_ir > patience:
print("Early stopping criterion satisfied.")
break
"""
from gensim.models import CoherenceModel
from gensim.corpora.dictionary import Dictionary
def compute_coherence(texts, list_of_topics, top_n_word_in_each_topic_list, reload_model_dir):
dictionary = Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
print('corpus len:%s' %len(corpus))
print('dictionary:%s' %dictionary)
# https://github.com/earthquakesan/palmetto-py
# compute_topic_coherence: PMI and other coherence types
# from palmettopy.palmetto import Palmetto
# palmetto = Palmetto()
# coherence_types = ["ca", "cp", "cv", "npmi", "uci", "umass"] # for palmetto library
coherence_types = ["c_v"]#, 'u_mass', 'c_v', 'c_uci', 'c_npmi'] # ["c_v"] # 'u_mass', 'c_v', 'c_uci', 'c_npmi',
avg_coh_scores_dict = {}
best_coh_type_value_topci_indx = {}
for top_n in top_n_word_in_each_topic_list:
avg_coh_scores_dict[top_n]= []
best_coh_type_value_topci_indx[top_n] = [0, 0, []] # score, topic_indx, topics words
h_num = 0
with open(reload_model_dir, "w") as f:
for topic_words_all in list_of_topics:
h_num += 1
for top_n in top_n_word_in_each_topic_list:
topic_words = [topic_words_all[:top_n]]
for coh_type in coherence_types:
try:
print('top_n: %s Topic Num: %s \nTopic Words: %s' % (top_n, h_num, topic_words))
f.write('top_n: %s Topic Num: %s \nTopic Words: %s\n' % (top_n, h_num, topic_words))
# print('topic_words_top_10_abs[%s]:%s' % (h_num, topic_words_top_10_abs[h_num]))
# PMI = palmetto.get_coherence(topic_words_top_10[h_num], coherence_type=coh_type)
PMI = CoherenceModel(topics=topic_words, texts=texts, dictionary=dictionary, coherence=coh_type, processes=2).get_coherence()
avg_coh_scores_dict[top_n].append(PMI)
if PMI > best_coh_type_value_topci_indx[top_n][0]:
best_coh_type_value_topci_indx[top_n] = [PMI, top_n, topic_words]
print('Coh_type:%s Topic Num:%s COH score:%s' % (coh_type, h_num, PMI))
f.write('Coh_type:%s Topic Num:%s COH score:%s\n' % (coh_type, h_num, PMI))
print('--------------------------------------------------------------')
except:
continue
print('========================================================================================================')
for top_n in top_n_word_in_each_topic_list:
print('top scores for top_%s:%s' %(top_n, best_coh_type_value_topci_indx[top_n]))
print('-------------------------------------------------------------------')
f.write('top scores for top_%s:%s\n' %(top_n, best_coh_type_value_topci_indx[top_n]))
f.write('-------------------------------------------------------------------\n')
for top_n in top_n_word_in_each_topic_list:
print('Avg COH for top_%s topic words: %s' %(top_n, np.mean(avg_coh_scores_dict[top_n])))
print('-------------------------------------------------------------------')
f.write('Avg COH for top_%s topic words: %s\n' %(top_n, np.mean(avg_coh_scores_dict[top_n])))
f.write('-------------------------------------------------------------------\n')
def get_vectors_from_matrix(matrix, batches):
# matrix: embedding matrix of shape = [vocab_size X embedding_size]
vecs = []
for _, x, seq_length in batches:
temp_vec = np.zeros((matrix.shape[1]), dtype=np.float32)
indices = x[0, :seq_length[0]]
for index in indices:
temp_vec += matrix[index, :]
vecs.append(temp_vec)
return np.array(vecs)
from math import *
from nltk.corpus import wordnet
def square_rooted(x):
return round(sqrt(sum([a * a for a in x])), 3)
def cosine_similarity(x, y):
numerator = sum(a * b for a, b in zip(x, y))
denominator = square_rooted(x) * square_rooted(y)
return round(numerator / float(denominator), 3)
def reload_evaluation_acc_mAP(params):
with tf.Session(config=tf.ConfigProto(
inter_op_parallelism_threads=params['num_cores'],
intra_op_parallelism_threads=params['num_cores'],
gpu_options=tf.GPUOptions(allow_growth=True)
)) as session_acc:
dataset = data.Dataset(params['dataset'])
log_dir = os.path.join(params['model'], 'logs')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
saver_ppl = tf.train.import_meta_graph("model/" + params['reload_model_dir'] + "model_sup/model_sup-1.meta")
saver_ppl.restore(session_acc, tf.train.latest_checkpoint("model/" + params['reload_model_dir'] + "model_sup/"))
graph = tf.get_default_graph()
predicted_labels = graph.get_tensor_by_name("pred_labels:0")
disc_logits = graph.get_tensor_by_name("disc_logits:0")
x = graph.get_tensor_by_name("x:0")
y = graph.get_tensor_by_name("y:0")
seq_lengths = graph.get_tensor_by_name("seq_lengths:0")
if params['input_type'] == "both":
training_filename = 'training_docnade'
validation_filename = 'validation_docnade'
test_filename = 'test_docnade'
elif params['input_type'] == "abstract":
training_filename = 'training_docnade_abstracts'
validation_filename = 'validation_docnade_abstracts'
test_filename = 'test_docnade_abstracts'
elif params['input_type'] == "title":
training_filename = 'training_docnade_titles'
validation_filename = 'validation_docnade_titles'
test_filename = 'test_docnade_titles'
## Classification accuracy
#if params.use_title_separately:
# validation_title_data = dataset.batches(validation_title_filename, params.validation_bs, num_epochs=1, shuffle=True, multilabel=params.multi_label)
# validation_filename = 'validation_docnade_abstracts'
val_true_labels = []
val_pred_labels = []
val_pred_logits = []
for val_y, val_x, val_seq_lengths in dataset.batches(validation_filename, 1, num_epochs=1, shuffle=False, multilabel=params['multi_label']):
val_feed_dict = {}
val_feed_dict[x] = val_x
val_feed_dict[y] = val_y
val_feed_dict[seq_lengths] = val_seq_lengths
#if params.use_title_separately:
# val_y_title, val_x_title, val_seq_lengths_title = next(validation_title_data)
# val_feed_dict[model.x_title] = val_x_title
# val_feed_dict[model.seq_lengths_title] = val_seq_lengths_title
pred_labels, pred_logits = session_acc.run([predicted_labels, disc_logits], feed_dict=val_feed_dict)
#val_pred_labels.append(pred_labels[0][0])
val_pred_labels.append(pred_labels[0])
val_pred_logits.append(pred_logits[0])
val_true_labels.append(int(val_y))
#val_true_labels = [int(label[0]) for label in validation_labels]
val_acc = accuracy_score(val_true_labels, val_pred_labels)
print('This val accuracy: {:.3f}'.format(val_acc))
with open(os.path.join(log_dir, "reload_info_acc.txt"), "w") as f:
f.write("val accuracy: %s\n" % (val_acc))
## Using classification probability for relevance ranking and mAP calculation
val_pred_probs = eval.softmax(np.array(val_pred_logits), axis=1)
val_pred_probs_temp = val_pred_probs[np.arange(len(val_pred_labels)), np.array(val_pred_labels)]
val_mAP, val_AP_dict, preds_dict, probs_dict, indices_dict = eval.evaluate_mAP(val_true_labels, val_pred_labels, val_pred_probs_temp)
print('This val mAP: {:.3f}'.format(val_mAP))
# logging information
with open(os.path.join(log_dir, "reload_info_acc.txt"), "a") as f:
f.write("val mAP: %s\n" % (val_mAP))
with open(os.path.join(log_dir, "reload_info_clusters.txt"), "w") as f:
for label in preds_dict.keys():
preds = preds_dict[label]
probs = probs_dict[label]
preds_indices = indices_dict[label]
sorted_indices = np.argsort(probs)[::-1]
sorted_preds = np.array(preds)[sorted_indices]
sorted_probs = np.array(probs)[sorted_indices]
sorted_preds_indices = np.array(preds_indices)[sorted_indices]
f.write("Cluster " + str(label) + "\n\n")
f.write("Average precision: " + str(val_AP_dict[label]) + "\n")
f.write("Predicted_labels: " + " ".join([str(l) for l in sorted_preds]) + "\n")
f.write("Predicted_probs: " + " ".join([str(l) for l in sorted_probs]) + "\n")
f.write("Predicted_indices: " + " ".join([str(l) for l in sorted_preds_indices]) + "\n")
f.write("\n\n")
f.write("\n\n=================================================================================\n\n")
#import pdb; pdb.set_trace()
# misclassified
temp = (np.array(val_pred_labels) == np.array(val_true_labels))
#val_pred_probs_full = eval.softmax(np.array(val_pred_logits), axis=1)
indices = [index for index, val in enumerate(temp) if not val]
with open(os.path.join(log_dir, "misclassified.txt"), "a") as f:
for index in indices:
#f.write("Val doc #" + str(index+1) + "\n")
f.write("Val doc #" + str(index+1) + "\n")
f.write("True label: " + str(val_true_labels[index]) + "\n")
f.write("Pred label: " + str(val_pred_labels[index]) + "\n")
#f.write("Prediction probs: " + " ".join([str(prob) for prob in val_pred_probs_full[index, :]]) + "\n")
f.write("Prediction probs: " + " ".join([str(prob) for prob in val_pred_probs[index, :]]) + "\n")
f.write("\n\n")
## Using BM25 score for relevance ranking and mAP calculation