-
Notifications
You must be signed in to change notification settings - Fork 2
/
PASTE.py
1634 lines (1376 loc) · 55.2 KB
/
PASTE.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 sys
import os
import numpy as np
import random
from collections import OrderedDict
import pickle
import datetime
import json
from tqdm import tqdm
from recordclass import recordclass
import math
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.backends.cudnn.deterministic = True
import regex as re
import spacy
from spacy.tokenizer import Tokenizer
nlp = spacy.load("en_core_web_sm")
nlp.tokenizer = Tokenizer(nlp.vocab, token_match=re.compile(r'\S+').match)
def custom_print(*msg):
for i in range(0, len(msg)):
if i == len(msg) - 1:
print(msg[i])
logger.write(str(msg[i]) + '\n')
else:
print(msg[i], ' ', end='')
logger.write(str(msg[i]))
def load_word_embedding(embed_file, vocab):
custom_print('vocab length:', len(vocab))
custom_print(embed_file)
embed_vocab = OrderedDict()
embed_matrix = list()
embed_vocab['<PAD>'] = 0
embed_matrix.append(np.zeros(word_embed_dim, dtype=np.float32))
embed_vocab['<UNK>'] = 1
embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim))
word_idx = 2
with open(embed_file, "r") as f:
for line in f:
parts = line.split()
if len(parts) < word_embed_dim + 1:
continue
word = parts[0]
if word in vocab:
vec = [np.float32(val) for val in parts[1:]]
embed_matrix.append(vec)
embed_vocab[word] = word_idx
word_idx += 1
for word in vocab:
if word not in embed_vocab and vocab[word] >= word_min_freq:
embed_matrix.append(np.random.uniform(-0.25, 0.25, word_embed_dim))
embed_vocab[word] = word_idx
word_idx += 1
custom_print('embed dictionary length:', len(embed_vocab))
return embed_vocab, np.array(embed_matrix, dtype=np.float32)
def build_vocab(tr_data, dv_data, ts_data, save_vocab, embedding_file):
vocab = OrderedDict()
char_v = OrderedDict()
char_v['<PAD>'] = 0
char_v['<UNK>'] = 1
char_idx = 2
for d in tr_data:
for word in d.SrcWords:
if lower_cased:
word = word.lower()
if word not in vocab:
vocab[word] = 1
else:
vocab[word] += 1
for c in word:
if c not in char_v:
char_v[c] = char_idx
char_idx += 1
for d in dv_data + ts_data:
for word in d.SrcWords:
if lower_cased:
word = word.lower()
if word not in vocab:
vocab[word] = 0
for c in word:
if c not in char_v:
char_v[c] = char_idx
char_idx += 1
word_v, embed_matrix = load_word_embedding(embedding_file, vocab)
output = open(save_vocab, 'wb')
pickle.dump([word_v, char_v, pos_vocab, dep_vocab], output)
output.close()
return word_v, char_v, embed_matrix
def build_pos_tags(file1, file2, file3):
f1 = open(file1, "r")
f2 = open(file2, "r")
f3 = open(file3, "r")
pos_vocab = OrderedDict()
pos_vocab['<PAD>'] = 0
pos_vocab['<UNK>'] = 1
k = 2
for line in f1:
line = line.strip()
doc = nlp(line)
tags = [tok.pos_ if tok.pos_ == 'PUNCT' else tok.pos_ + "-" + tok.tag_ for tok in doc]
for t in tags:
if t not in pos_vocab:
pos_vocab[t] = k
k += 1
for line in f2:
line = line.strip()
doc = nlp(line)
tags = [tok.pos_ if tok.pos_ == 'PUNCT' else tok.pos_ + "-" + tok.tag_ for tok in doc]
for t in tags:
if t not in pos_vocab:
pos_vocab[t] = k
k += 1
for line in f3:
line = line.strip()
doc = nlp(line)
tags = [tok.pos_ if tok.pos_ == 'PUNCT' else tok.pos_ + "-" + tok.tag_ for tok in doc]
for t in tags:
if t not in pos_vocab:
pos_vocab[t] = k
k += 1
return pos_vocab
def build_dep_tags(file1, file2, file3):
f1 = open(file1, "r")
f2 = open(file2, "r")
f3 = open(file3, "r")
dep_vocab = OrderedDict()
dep_vocab['<PAD>'] = 0
dep_vocab['<UNK>'] = 1
k = 2
for line in f1:
line = line.strip()
doc = nlp(line)
tags = [tok.dep_ for tok in doc]
for t in tags:
if t not in dep_vocab:
dep_vocab[t] = k
k += 1
for line in f2:
line = line.strip()
doc = nlp(line)
tags = [tok.dep_ for tok in doc]
for t in tags:
if t not in dep_vocab:
dep_vocab[t] = k
k += 1
for line in f3:
line = line.strip()
doc = nlp(line)
tags = [tok.dep_ for tok in doc]
for t in tags:
if t not in dep_vocab:
dep_vocab[t] = k
k += 1
return dep_vocab
def load_vocab(vocab_file):
with open(vocab_file, 'rb') as f:
embed_vocab, char_vocab, pos_vocab, dep_vocab = pickle.load(f)
return embed_vocab, char_vocab, pos_vocab, dep_vocab
def get_sample(uid, src_line, trg_line, datatype):
src_words = src_line.split(' ')
trg_rels = []
trg_pointers = []
parts = trg_line.split('|')
triples = []
for part in parts:
elements = part.strip().split(' ')
triples.append((int(elements[0]), int(elements[1]), int(elements[2]), int(elements[3]),
relnameToIdx[elements[4]]))
if datatype == 1:
if trip_order == triplet_orders[0]:
random.shuffle(triples)
elif trip_order == triplet_orders[1]:
triples = sorted(triples, key=lambda element: (element[0], element[2]))
else:
triples = sorted(triples, key=lambda element: (element[2], element[0]))
for triple in triples:
trg_rels.append(triple[4])
trg_pointers.append((triple[0], triple[1], triple[2], triple[3]))
if datatype == 1 and (len(src_words) > max_src_len or len(trg_rels) > max_trg_len):
return False, None
sample = Sample(Id=uid, SrcLen=len(src_words), SrcWords=src_words, TrgLen=len(trg_rels), TrgRels=trg_rels,
TrgPointers=trg_pointers)
return True, sample
def get_data(src_lines, trg_lines, datatype):
samples = []
uid = 1
for i in range(0, len(src_lines)):
src_line = src_lines[i].strip()
trg_line = trg_lines[i].strip()
status, sample = get_sample(uid, src_line, trg_line, datatype)
if status:
samples.append(sample)
uid += 1
if use_data_aug and datatype == 1:
parts = trg_line.split('|')
if len(parts) == 1:
continue
for j in range(1, 2):
status, aug_sample = get_sample(uid, src_line, trg_line, datatype)
if status:
samples.append(aug_sample)
uid += 1
return samples
def read_data(src_file, trg_file, datatype):
reader = open(src_file)
src_lines = reader.readlines()
custom_print('No. of sentences:', len(src_lines))
reader.close()
reader = open(trg_file)
trg_lines = reader.readlines()
reader.close()
data = get_data(src_lines, trg_lines, datatype)
return data
def get_relations(file_name):
nameToIdx = OrderedDict()
idxToName = OrderedDict()
reader = open(file_name)
lines = reader.readlines()
reader.close()
nameToIdx['<PAD>'] = 0
idxToName[0] = '<PAD>'
# nameToIdx['<SOS>'] = 1
# idxToName[1] = '<SOS>'
nameToIdx['None'] = 1
idxToName[1] = 'None'
idx = 2
if use_nr_triplets:
nameToIdx['NR'] = 2
idxToName[2] = 'NR'
idx = 3
for line in lines:
nameToIdx[line.strip()] = idx
idxToName[idx] = line.strip()
idx += 1
return nameToIdx, idxToName
def get_answer_pointers(arg1start_preds, arg1end_preds, arg2start_preds, arg2end_preds, sent_len):
arg1_prob = -1.0
arg1start = -1
arg1end = -1
max_ent_len = 5
window = 100
for i in range(0, sent_len):
for j in range(i, min(sent_len, i + max_ent_len)):
if arg1start_preds[i] * arg1end_preds[j] > arg1_prob:
arg1_prob = arg1start_preds[i] * arg1end_preds[j]
arg1start = i
arg1end = j
arg2_prob = -1.0
arg2start = -1
arg2end = -1
for i in range(max(0, arg1start - window), arg1start):
for j in range(i, min(arg1start, i + max_ent_len)):
if arg2start_preds[i] * arg2end_preds[j] > arg2_prob:
arg2_prob = arg2start_preds[i] * arg2end_preds[j]
arg2start = i
arg2end = j
for i in range(arg1end + 1, min(sent_len, arg1end + window)):
for j in range(i, min(sent_len, i + max_ent_len)):
if arg2start_preds[i] * arg2end_preds[j] > arg2_prob:
arg2_prob = arg2start_preds[i] * arg2end_preds[j]
arg2start = i
arg2end = j
# return arg1start, arg1end, arg2start, arg2end
arg2_prob1 = -1.0
arg2start1 = -1
arg2end1 = -1
for i in range(0, sent_len):
for j in range(i, min(sent_len, i + max_ent_len)):
if arg2start_preds[i] * arg2end_preds[j] > arg2_prob1:
arg2_prob1 = arg2start_preds[i] * arg2end_preds[j]
arg2start1 = i
arg2end1 = j
arg1_prob1 = -1.0
arg1start1 = -1
arg1end1 = -1
for i in range(max(0, arg2start1 - window), arg2start1):
for j in range(i, min(arg2start1, i + max_ent_len)):
if arg1start_preds[i] * arg1end_preds[j] > arg1_prob1:
arg1_prob1 = arg1start_preds[i] * arg1end_preds[j]
arg1start1 = i
arg1end1 = j
for i in range(arg2end1 + 1, min(sent_len, arg2end1 + window)):
for j in range(i, min(sent_len, i + max_ent_len)):
if arg1start_preds[i] * arg1end_preds[j] > arg1_prob1:
arg1_prob1 = arg1start_preds[i] * arg1end_preds[j]
arg1start1 = i
arg1end1 = j
if arg1_prob * arg2_prob > arg1_prob1 * arg2_prob1:
return arg1start, arg1end, arg2start, arg2end
else:
return arg1start1, arg1end1, arg2start1, arg2end1
def is_full_match(triplet, triplets):
for t in triplets:
if t[0] == triplet[0] and t[1] == triplet[1] and t[2] == triplet[2]:
return True
return False
def get_gt_triples(src_words, rels, pointers):
triples = []
i = 0
for r in rels:
arg1 = ' '.join(src_words[pointers[i][0]:pointers[i][1] + 1])
arg2 = ' '.join(src_words[pointers[i][2]:pointers[i][3] + 1])
triplet = (arg1.strip(), arg2.strip(), relIdxToName[r])
if not is_full_match(triplet, triples):
triples.append(triplet)
i += 1
return triples
def get_pred_triples(rel, arg1s, arg1e, arg2s, arg2e, src_words):
triples = []
all_triples = []
for i in range(0, len(rel)):
pred_idx = np.argmax(rel[i][1:]) + 1
pred_score = np.max(rel[i][1:])
if pred_idx == relnameToIdx['None']:
break
if use_nr_triplets and pred_idx == relnameToIdx['NR']:
continue
s1, e1, s2, e2 = get_answer_pointers(arg1s[i], arg1e[i], arg2s[i], arg2e[i], len(src_words))
arg1 = ' '.join(src_words[s1: e1 + 1])
arg2 = ' '.join(src_words[s2: e2 + 1])
arg1 = arg1.strip()
arg2 = arg2.strip()
if arg1 == arg2:
continue
triplet = (arg1, arg2, relIdxToName[pred_idx], pred_score)
all_triples.append(triplet)
if not is_full_match(triplet, triples):
triples.append(triplet)
return triples, all_triples
def get_F1(data, preds):
gt_pos = 0
pred_pos = 0
total_pred_pos = 0
correct_pos = 0
for i in range(0, len(data)):
gt_triples = get_gt_triples(data[i].SrcWords, data[i].TrgRels, data[i].TrgPointers)
pred_triples, all_pred_triples = get_pred_triples(preds[0][i], preds[1][i], preds[2][i], preds[3][i],
preds[4][i], data[i].SrcWords)
total_pred_pos += len(all_pred_triples)
gt_pos += len(gt_triples)
pred_pos += len(pred_triples)
for gt_triple in gt_triples:
if is_full_match(gt_triple, pred_triples):
correct_pos += 1
print(total_pred_pos)
return pred_pos, gt_pos, correct_pos
def print_scores(gt_pos, pred_pos, correct_pos):
custom_print('GT Triple Count:', gt_pos, '\tPRED Triple Count:', pred_pos, '\tCORRECT Triple Count:', correct_pos)
test_p = float(correct_pos) / (pred_pos + 1e-8)
test_r = float(correct_pos) / (gt_pos + 1e-8)
test_acc = (2 * test_p * test_r) / (test_p + test_r + 1e-8)
custom_print('Test P:', round(test_p, 3))
custom_print('Test R:', round(test_r, 3))
custom_print('Test F1:', round(test_acc, 3))
def get_splitted_F1(data, preds):
total_count = 0
gt_pos = 0
pred_pos = 0
correct_pos = 0
count_single = 0
gt_single = 0
pred_single = 0
correct_single = 0
count_multi = 0
gt_multi = 0
pred_multi = 0
correct_multi = 0
count_multiRel = 0
gt_multiRel = 0
pred_multiRel = 0
correct_multiRel = 0
count_overlappingEnt = 0
gt_overlappingEnt = 0
pred_overlappingEnt = 0
correct_overlappingEnt = 0
for i in range(0, len(data)):
total_count += 1
gt_triples = get_gt_triples(data[i].SrcWords, data[i].TrgRels, data[i].TrgPointers)
pred_triples, _ = get_pred_triples(preds[0][i], preds[1][i], preds[2][i], preds[3][i],
preds[4][i], data[i].SrcWords)
correct_count = 0
gt_pos += len(gt_triples)
pred_pos += len(pred_triples)
for gt_triple in gt_triples:
if is_full_match(gt_triple, pred_triples):
correct_count += 1
correct_pos += 1
if len(data[i].TrgRels) == 1:
count_single += 1
gt_single += len(gt_triples)
pred_single += len(pred_triples)
correct_single += correct_count
else:
count_multi += 1
gt_multi += len(gt_triples)
pred_multi += len(pred_triples)
correct_multi += correct_count
unique_rels = set(data[i].TrgRels)
if len(unique_rels) > 1:
count_multiRel += 1
gt_multiRel += len(gt_triples)
pred_multiRel += len(pred_triples)
correct_multiRel += correct_count
flag = 0
for j in range(len(data[i].TrgPointers)):
for k in range(len(data[i].TrgPointers)):
if j == k:
continue
if data[i].TrgPointers[j][0] == data[i].TrgPointers[k][0] and data[i].TrgPointers[j][1] == data[i].TrgPointers[k][1]:
flag = 1
break
if data[i].TrgPointers[j][2] == data[i].TrgPointers[k][2] and data[i].TrgPointers[j][3] == data[i].TrgPointers[k][3]:
flag = 1
break
if data[i].TrgPointers[j][0] == data[i].TrgPointers[k][2] and data[i].TrgPointers[j][1] == data[i].TrgPointers[k][3]:
flag = 1
break
if data[i].TrgPointers[j][2] == data[i].TrgPointers[k][0] and data[i].TrgPointers[j][3] == data[i].TrgPointers[k][1]:
flag = 1
break
if flag == 1:
break
if flag == 1:
count_overlappingEnt += 1
gt_overlappingEnt += len(gt_triples)
pred_overlappingEnt += len(pred_triples)
correct_overlappingEnt += correct_count
custom_print('Re-checking the scores of entire Test data with the best saved model:')
custom_print('Total sentences in the test set:', total_count)
print_scores(gt_pos, pred_pos, correct_pos)
custom_print('Now printing the scores for various subsets of Test Data with the best saved model:')
custom_print('Total sentences with single triples:', count_single)
print_scores(gt_single, pred_single, correct_single)
custom_print('Total sentences with multiple triples:', count_multi)
print_scores(gt_multi, pred_multi, correct_multi)
custom_print('Total sentences triples with varying sentiments:', count_multiRel)
print_scores(gt_multiRel, pred_multiRel, correct_multiRel)
custom_print('Total sentences with overlapping triples:', count_overlappingEnt)
print_scores(gt_overlappingEnt, pred_overlappingEnt, correct_overlappingEnt)
def write_test_res(src, trg, data, preds, outfile):
reader = open(src)
src_lines = reader.readlines()
writer = open(outfile, 'w')
for i in range(0, len(data)):
writer.write(src_lines[i])
writer.write('Expected: '+trg[i])
pred_triples, _ = get_pred_triples(preds[0][i], preds[1][i], preds[2][i], preds[3][i], preds[4][i],
data[i].SrcWords)
pred_triples_str = []
for pt in pred_triples:
str_tmp = pt[0] + ' ; ' + pt[1] + ' ; ' + pt[2] + ' ; ' + str(pt[3])
if str_tmp not in pred_triples_str:
pred_triples_str.append(str_tmp)
writer.write('Predicted: ' + ' | '.join(pred_triples_str) + '\n'+'\n')
writer.close()
reader.close()
def shuffle_data(data):
custom_print(len(data))
# data.sort(key=lambda x: x.SrcLen)
num_batch = int(len(data) / batch_size)
rand_idx = random.sample(range(num_batch), num_batch)
new_data = []
for idx in rand_idx:
new_data += data[batch_size * idx: batch_size * (idx + 1)]
if len(new_data) < len(data):
new_data += data[num_batch * batch_size:]
return new_data
def get_max_len(sample_batch):
src_max_len = len(sample_batch[0].SrcWords)
for idx in range(1, len(sample_batch)):
if len(sample_batch[idx].SrcWords) > src_max_len:
src_max_len = len(sample_batch[idx].SrcWords)
trg_max_len = len(sample_batch[0].TrgRels)
for idx in range(1, len(sample_batch)):
if len(sample_batch[idx].TrgRels) > trg_max_len:
trg_max_len = len(sample_batch[idx].TrgRels)
return src_max_len, trg_max_len
def get_words_index_seq(words, max_len):
seq = list()
for word in words:
if lower_cased:
word = word.lower()
if word in word_vocab:
seq.append(word_vocab[word])
else:
seq.append(word_vocab['<UNK>'])
pad_len = max_len - len(words)
for i in range(0, pad_len):
seq.append(word_vocab['<PAD>'])
return seq
def get_pos_index_seq(words, max_len):
seq = list()
sent = " ".join(words).strip()
doc = nlp(sent)
tags = [tok.pos_ if tok.pos_ == 'PUNCT' else tok.pos_ + "-" + tok.tag_ for tok in doc]
for t in tags:
if t in pos_vocab:
seq.append(pos_vocab[t])
else:
seq.append(pos_vocab['<UNK>'])
pad_len = max_len - len(seq)
for i in range(0, pad_len):
seq.append(pos_vocab['<PAD>'])
return seq
def get_dep_index_seq(words, max_len):
seq = list()
sent = " ".join(words).strip()
doc = nlp(sent)
tags = [tok.dep_ for tok in doc]
for t in tags:
if t in dep_vocab:
seq.append(dep_vocab[t])
else:
seq.append(dep_vocab['<UNK>'])
pad_len = max_len - len(seq)
for i in range(0, pad_len):
seq.append(dep_vocab['<PAD>'])
return seq
def get_char_seq(words, max_len):
char_seq = list()
for i in range(0, conv_filter_size - 1):
char_seq.append(char_vocab['<PAD>'])
for word in words:
if lower_cased:
word = word.lower()
for c in word[0:min(len(word), max_word_len)]:
if c in char_vocab:
char_seq.append(char_vocab[c])
else:
char_seq.append(char_vocab['<UNK>'])
pad_len = max_word_len - len(word)
for i in range(0, pad_len):
char_seq.append(char_vocab['<PAD>'])
for i in range(0, conv_filter_size - 1):
char_seq.append(char_vocab['<PAD>'])
pad_len = max_len - len(words)
for i in range(0, pad_len):
for i in range(0, max_word_len + conv_filter_size - 1):
char_seq.append(char_vocab['<PAD>'])
return char_seq
def get_relation_index_seq(rel_ids, max_len):
seq = list()
for r in rel_ids:
seq.append(r)
seq.append(relnameToIdx['None'])
pad_len = max_len + 1 - len(seq)
for i in range(0, pad_len):
seq.append(relnameToIdx['<PAD>'])
return seq
def get_padded_pointers(pointers, pidx, max_len):
idx_list = []
for p in pointers:
idx_list.append(p[pidx])
pad_len = max_len + 1 - len(pointers)
for i in range(0, pad_len):
idx_list.append(-1)
return idx_list
def get_pointer_location(pointers, pidx, src_max_len, trg_max_len):
loc_seq = []
for p in pointers:
cur_seq = [0 for i in range(src_max_len)]
cur_seq[p[pidx]] = 1
loc_seq.append(cur_seq)
pad_len = trg_max_len + 1 - len(pointers)
for i in range(pad_len):
cur_seq = [0 for i in range(src_max_len)]
loc_seq.append(cur_seq)
return loc_seq
def get_padded_mask(cur_len, max_len):
mask_seq = list()
for i in range(0, cur_len):
mask_seq.append(0)
pad_len = max_len - cur_len
for i in range(0, pad_len):
mask_seq.append(1)
return mask_seq
def get_target_vec(pointers, rels, src_max_len):
vec = [0 for i in range(src_max_len + len(relnameToIdx))]
for i in range(len(pointers)):
p = pointers[i]
vec[p[0]] += 1
vec[p[1]] += 1
vec[p[2]] += 1
vec[p[3]] += 1
vec[src_max_len + rels[i]] += 1
return vec
def get_batch_data(cur_samples, is_training=False):
"""
Returns the training samples and labels as numpy array
"""
batch_src_max_len, batch_trg_max_len = get_max_len(cur_samples)
batch_trg_max_len += 1
src_words_list = list()
src_words_mask_list = list()
src_char_seq = list()
decoder_input_list = list()
src_pos_seq = list()
src_dep_seq = list()
src_loc_seq = list()
arg1sweights = []
arg1eweights = []
arg2sweights = []
arg2eweights = []
rel_seq = list()
arg1_start_seq = list()
arg1_end_seq = list()
arg2_start_seq = list()
arg2_end_seq = list()
target_vec_seq = []
target_vec_mask_seq = []
for sample in cur_samples:
src_words_list.append(get_words_index_seq(sample.SrcWords, batch_src_max_len))
src_words_mask_list.append(get_padded_mask(sample.SrcLen, batch_src_max_len))
src_char_seq.append(get_char_seq(sample.SrcWords, batch_src_max_len))
src_pos_seq.append(get_pos_index_seq(sample.SrcWords, batch_src_max_len))
src_dep_seq.append(get_dep_index_seq(sample.SrcWords, batch_src_max_len))
src_loc_seq.append([i+1 for i in range(len(sample.SrcWords))] +
[0 for i in range(batch_src_max_len - len(sample.SrcWords))])
if is_training:
arg1_start_seq.append(get_padded_pointers(sample.TrgPointers, 0, batch_trg_max_len))
arg1_end_seq.append(get_padded_pointers(sample.TrgPointers, 1, batch_trg_max_len))
arg2_start_seq.append(get_padded_pointers(sample.TrgPointers, 2, batch_trg_max_len))
arg2_end_seq.append(get_padded_pointers(sample.TrgPointers, 3, batch_trg_max_len))
arg1sweights.append(get_pointer_location(sample.TrgPointers, 0, batch_src_max_len, batch_trg_max_len))
arg1eweights.append(get_pointer_location(sample.TrgPointers, 1, batch_src_max_len, batch_trg_max_len))
arg2sweights.append(get_pointer_location(sample.TrgPointers, 2, batch_src_max_len, batch_trg_max_len))
arg2eweights.append(get_pointer_location(sample.TrgPointers, 3, batch_src_max_len, batch_trg_max_len))
rel_seq.append(get_relation_index_seq(sample.TrgRels, batch_trg_max_len))
decoder_input_list.append(get_relation_index_seq(sample.TrgRels, batch_trg_max_len))
target_vec_seq.append(get_target_vec(sample.TrgPointers, sample.TrgRels, batch_src_max_len))
target_vec_mask_seq.append([0 for i in range(len(sample.TrgRels))] +
[1 for i in range(batch_trg_max_len + 1 - len(sample.TrgRels))])
else:
decoder_input_list.append(get_relation_index_seq([], 1))
return {'src_words': np.array(src_words_list, dtype=np.float32),
'src_words_mask': np.array(src_words_mask_list),
'src_chars': np.array(src_char_seq),
'src_pos_tags': np.array(src_pos_seq),
'src_dep_tags': np.array(src_dep_seq),
'src_loc': np.array(src_loc_seq),
'decoder_input': np.array(decoder_input_list),
'arg1sweights': np.array(arg1sweights),
'arg1eweights': np.array(arg1eweights),
'arg2sweights': np.array(arg2sweights),
'arg2eweights': np.array(arg2eweights),
'rel': np.array(rel_seq),
'arg1_start': np.array(arg1_start_seq),
'arg1_end': np.array(arg1_end_seq),
'arg2_start': np.array(arg2_start_seq),
'arg2_end': np.array(arg2_end_seq),
'target_vec': np.array(target_vec_seq),
'target_vec_mask': np.array(target_vec_mask_seq)}
class WordEmbeddings(nn.Module):
def __init__(self, vocab_size, embed_dim, drop_out_rate):
super(WordEmbeddings, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
if job_mode == 'train':
self.embeddings.weight.data.copy_(torch.from_numpy(word_embed_matrix))
self.embeddings.weight.requires_grad = False
self.dropout = nn.Dropout(drop_out_rate)
def forward(self, words_seq):
word_embeds = self.embeddings(words_seq)
word_embeds = self.dropout(word_embeds)
return word_embeds
def weight(self):
return self.embeddings.weight
class CharEmbeddings(nn.Module):
def __init__(self, vocab_size, embed_dim, drop_out_rate):
super(CharEmbeddings, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
self.conv1d = nn.Conv1d(char_embed_dim, char_feature_size, 3)
self.max_pool = nn.MaxPool1d(max_word_len + conv_filter_size - 1, max_word_len + conv_filter_size - 1)
self.dropout = nn.Dropout(drop_out_rate)
def forward(self, char_seq):
char_embeds = self.embeddings(char_seq)
char_embeds = self.dropout(char_embeds)
char_embeds = char_embeds.permute(0, 2, 1)
char_feature = torch.tanh(self.max_pool(self.conv1d(char_embeds)))
char_feature = char_feature.permute(0, 2, 1)
return char_feature
class POSEmbeddings(nn.Module):
def __init__(self, tag_len, tag_dim, drop_out_rate):
super(POSEmbeddings, self).__init__()
self.embeddings = nn.Embedding(tag_len, tag_dim, padding_idx=0)
self.dropout = nn.Dropout(drop_out_rate)
def forward(self, pos_seq):
pos_embeds = self.embeddings(pos_seq)
pos_embeds = self.dropout(pos_embeds)
return pos_embeds
class DEPEmbeddings(nn.Module):
def __init__(self, tag_len, tag_dim, drop_out_rate):
super(DEPEmbeddings, self).__init__()
self.embeddings = nn.Embedding(tag_len, tag_dim, padding_idx=0)
self.dropout = nn.Dropout(drop_out_rate)
def forward(self, dep_seq):
dep_embeds = self.embeddings(dep_seq)
dep_embeds = self.dropout(dep_embeds)
return dep_embeds
class LocEmbeddings(nn.Module):
def __init__(self, embed_size, embed_dim, drop_out_rate):
super(LocEmbeddings, self).__init__()
self.embeddings = nn.Embedding(embed_size, embed_dim, padding_idx=0)
self.dropout = nn.Dropout(drop_out_rate)
def forward(self, loc_seq):
loc_embeds = self.embeddings(loc_seq)
loc_embeds = self.dropout(loc_embeds)
return loc_embeds
class Attention(nn.Module):
def __init__(self, input_dim):
super(Attention, self).__init__()
self.input_dim = input_dim
self.linear_ctx = nn.Linear(self.input_dim, self.input_dim, bias=False)
self.linear_query = nn.Linear(self.input_dim, self.input_dim, bias=True)
self.v = nn.Linear(self.input_dim, 1)
def forward(self, s_prev, enc_hs, src_mask):
uh = self.linear_ctx(enc_hs)
wq = self.linear_query(s_prev)
wquh = torch.tanh(wq + uh)
attn_weights = self.v(wquh).squeeze()
attn_weights.data.masked_fill_(src_mask.data, -float('inf'))
attn_weights = F.softmax(attn_weights, dim=-1)
ctx = torch.bmm(attn_weights.unsqueeze(1), enc_hs).squeeze()
return ctx, attn_weights
class Sentiment_Attention_(nn.Module):
def __init__(self, enc_hid_dim, arg_dim):
super(Sentiment_Attention_, self).__init__()
self.w1 = nn.Linear(enc_hid_dim + arg_dim, 1)
self.w2 = nn.Linear(enc_hid_dim + arg_dim, 1)
def forward(self, arg1, arg2, enc_hs, src_mask):
ctx_arg1 = torch.cat((enc_hs, arg1.unsqueeze(1).repeat(1, enc_hs.size()[1], 1)), -1)
ctx_arg1_att = self.w1(ctx_arg1).squeeze()
ctx_arg1_att.data.masked_fill_(src_mask.data, -float('inf'))
ctx_arg1_att = F.softmax(ctx_arg1_att, dim=-1)
ctx1 = torch.bmm(ctx_arg1_att.unsqueeze(1), enc_hs).squeeze()
ctx_arg2 = torch.cat((enc_hs, arg2.unsqueeze(1).repeat(1, enc_hs.size()[1], 1)), -1)
ctx_arg2_att = self.w2(ctx_arg2).squeeze()
ctx_arg2_att.data.masked_fill_(src_mask.data, -float('inf'))
ctx_arg2_att = F.softmax(ctx_arg2_att, dim=-1)
ctx2 = torch.bmm(ctx_arg2_att.unsqueeze(1), enc_hs).squeeze()
return torch.cat((ctx1, ctx2), -1)
class Sentiment_Attention(nn.Module):
def __init__(self, enc_hid_dim, arg_dim):
super(Sentiment_Attention, self).__init__()
self.w1 = nn.Linear(enc_hid_dim, arg_dim)
self.w2 = nn.Linear(enc_hid_dim, arg_dim)
def forward(self, arg1, arg2, enc_hs, src_mask):
ctx_arg1_att = torch.bmm(torch.tanh(self.w1(enc_hs)), arg1.unsqueeze(2)).squeeze()
ctx_arg1_att.data.masked_fill_(src_mask.data, -float('inf'))
ctx_arg1_att = F.softmax(ctx_arg1_att, dim=-1)
ctx1 = torch.bmm(ctx_arg1_att.unsqueeze(1), enc_hs).squeeze()
ctx_arg2_att = torch.bmm(torch.tanh(self.w2(enc_hs)), arg2.unsqueeze(2)).squeeze()
ctx_arg2_att.data.masked_fill_(src_mask.data, -float('inf'))
ctx_arg2_att = F.softmax(ctx_arg2_att, dim=-1)
ctx2 = torch.bmm(ctx_arg2_att.unsqueeze(1), enc_hs).squeeze()
return torch.cat((ctx1, ctx2), -1)
def get_vec(arg1s, arg1e, arg2s, arg2e, rel):
arg1svec = F.softmax(arg1s, dim=-1)
arg1evec = F.softmax(arg1e, dim=-1)
arg2svec = F.softmax(arg2s, dim=-1)
arg2evec = F.softmax(arg2e, dim=-1)
relvec = F.softmax(rel, dim=-1)
argvec = arg1svec + arg1evec + arg2svec + arg2evec
argvec = torch.cat((argvec, relvec), -1)
return argvec
class Encoder(nn.Module):
def __init__(self, input_dim, hidden_dim, layers, is_bidirectional, drop_out_rate):
super(Encoder, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.layers = layers
self.is_bidirectional = is_bidirectional
self.drop_rate = drop_out_rate
self.word_embeddings = WordEmbeddings(len(word_vocab), word_embed_dim, drop_rate)
if use_char_embed:
self.char_embeddings = CharEmbeddings(len(char_vocab), char_embed_dim, drop_rate)
if use_pos_tags:
self.pos_embeddings = POSEmbeddings(len(pos_vocab), pos_tag_dim, drop_rate)
if use_dep_tags:
self.dep_embeddings = DEPEmbeddings(len(dep_vocab), dep_tag_dim, drop_rate)
if use_loc_embed:
self.loc_embeddings = LocEmbeddings(max_src_len + 1, loc_embed_dim, drop_rate)
if enc_type == 'LSTM':
self.lstm = nn.LSTM(self.input_dim, self.hidden_dim, self.layers, batch_first=True,
bidirectional=self.is_bidirectional, dropout=drop_out_rate)
self.dropout = nn.Dropout(self.drop_rate)
def forward(self, words, chars, pos_seq, dep_seq, loc_seq, adv=None, is_training=False):
src_word_embeds = self.word_embeddings(words)
if adv is not None:
batch_len = src_word_embeds.size()[0]
seq_len = src_word_embeds.size()[1]
adv = adv.unsqueeze(0).repeat(batch_len, 1, 1)
adv = torch.index_select(adv.view(-1, word_embed_dim), 0,
words.data.view(-1)).view(batch_len, seq_len, -1)
src_word_embeds.data = src_word_embeds.data + adv
words_input = src_word_embeds
if use_char_embed:
char_feature = self.char_embeddings(chars)
words_input = torch.cat((words_input, char_feature), -1)
if use_pos_tags:
src_pos_embeds = self.pos_embeddings(pos_seq)
words_input = torch.cat((words_input, src_pos_embeds), -1)
if use_dep_tags:
src_dep_embeds = self.dep_embeddings(dep_seq)
words_input = torch.cat((words_input, src_dep_embeds), -1)
if use_loc_embed:
src_loc_embeds = self.loc_embeddings(loc_seq)
words_input = torch.cat((words_input, src_loc_embeds), -1)
outputs, hc = self.lstm(words_input)
outputs = self.dropout(outputs)
return outputs
class Decoder(nn.Module):
def __init__(self, input_dim, hidden_dim, layers, drop_out_rate, max_length):
super(Decoder, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.layers = layers
self.drop_rate = drop_out_rate
self.max_length = max_length
if att_type == 0:
self.attention = Attention(input_dim)
self.lstm = nn.LSTMCell(rel_embed_dim + 4 * pointer_net_hidden_size + enc_hidden_size,
self.hidden_dim)
elif att_type == 1:
self.w = nn.Linear(9 * self.input_dim, self.input_dim)
self.attention = Attention(input_dim)
self.lstm = nn.LSTMCell(10 * self.input_dim, self.hidden_dim)
else:
self.w = nn.Linear(4 * pointer_net_hidden_size, self.input_dim)
self.attention1 = Attention(input_dim)
self.attention2 = Attention(input_dim)
self.lstm = nn.LSTMCell(4 * pointer_net_hidden_size + 2 * enc_hidden_size,
self.hidden_dim)
if gen_direct == gen_directions[0] or gen_direct == gen_directions[2]:
self.ap_first_pointer_lstm = nn.LSTM(enc_hidden_size + dec_hidden_size, int(pointer_net_hidden_size / 2),
1, batch_first=True, bidirectional=True)
self.op_second_pointer_lstm = nn.LSTM(enc_hidden_size + dec_hidden_size + pointer_net_hidden_size,
int(pointer_net_hidden_size / 2), 1, batch_first=True, bidirectional=True)
if gen_direct == gen_directions[1] or gen_direct == gen_directions[2]:
self.op_first_pointer_lstm = nn.LSTM(enc_hidden_size + dec_hidden_size, int(pointer_net_hidden_size / 2),
1, batch_first=True, bidirectional=True)
self.ap_second_pointer_lstm = nn.LSTM(enc_hidden_size + dec_hidden_size + pointer_net_hidden_size,
int(pointer_net_hidden_size / 2), 1, batch_first=True, bidirectional=True)
self.ap_start_lin = nn.Linear(pointer_net_hidden_size, 1)
self.ap_end_lin = nn.Linear(pointer_net_hidden_size, 1)
self.op_start_lin = nn.Linear(pointer_net_hidden_size, 1)
self.op_end_lin = nn.Linear(pointer_net_hidden_size, 1)
# self.sent_cnn = cnn()
if use_sentiment_attention:
self.sent_att = Sentiment_Attention(enc_hidden_size, 2 * pointer_net_hidden_size)
self.sent_lin = nn.Linear(dec_hidden_size + 4 * pointer_net_hidden_size + 2 * enc_hidden_size,
len(relnameToIdx))
else:
self.sent_lin = nn.Linear(dec_hidden_size + 4 * pointer_net_hidden_size, len(relnameToIdx))
self.dropout = nn.Dropout(self.drop_rate)