-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader.py
1731 lines (1306 loc) · 58.3 KB
/
dataloader.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
from operator import itemgetter
from config import parse_config
import argparse
from vocab import Vocab, STR, END, SEP, C2T, PAD
import json
import torch
from collections import Counter
import random
import tqdm,os
from transformers import AutoConfig,AutoTokenizer
from pytorch_pretrained_bert.modeling import BertPreTrainedModel,BertModel
import numpy as np
def get_align_mapping(alignments, token_lens):
# TODO: ???
align_mapping = []
for i, align in enumerate(alignments):
a = []
if i == 0:
for k in align:
if type(k) == type(["sean"]):
temp = []
for kk in k:
temp.append(int(kk))
a.append(temp)
else:
a.append(k)
else:
for k in align:
if type(k) == type(["sean"]):
add_index = sum(token_lens[:i])
temp = []
for kk in k:
temp.append(int(kk) + add_index)
a.append(temp)
else:
if k != -1:
add_index = sum(token_lens[:i])
a.append(k + add_index)
else:
a.append(k)
# align_mapping.append(a)
align_mapping.extend(a)
return align_mapping
def get_edge_mapping(edges, concept_lens):
# connect the root of each sentence
edges_mapping = []
root_index = [sum(concept_lens[:i]) for i in range(len(concept_lens))]
for i, es in enumerate(edges):
for j, e in enumerate(es):
edges_mapping.append([e[0], e[1]+root_index[i], e[2]+root_index[i]])
# add full connect root_node
root_edge_type = 'AMR_ROOT'
for i in root_index:
for j in root_index:
edges_mapping.append([root_edge_type, i, j])
return edges_mapping
def get_cluster_mapping(clusters, concept_lens):
cluster_mapping = []
cluster_mapping_labels = []
for i, cluster in enumerate(clusters):
cluster_mapping.append([])
cluster_mapping_labels.append([])
for j, c in enumerate(cluster):
cluster_mapping[-1].append((sum(concept_lens[:c[0]]) + c[1]))
cluster_mapping_labels[-1].append(c[2])
return cluster_mapping, cluster_mapping_labels
def get_concept_labels(cluster, cluster_labels, concepts):
# re-order the concept and its type, each concept has a type
concept_labels = []
cluster = [item for sublist in cluster for item in sublist] # flatten cluster
cluster_labels = [item for sublist in cluster_labels for item in sublist] #flatten
for i in range(len(concepts)):
if i in cluster:
concept_labels.append(cluster_labels[cluster.index(i)])
else:
concept_labels.append(-2)
a = [i + 2 for i in concept_labels]
return a
def get_bert_ids(tokens, args, tokenizer):
# TODO: get rid of the warnings
sentence_ids, sentence_toks, sentence_lens = [], [], []
for si, sentence in enumerate(tokens):
sent_len = 0
for word in sentence:
for char in tokenizer.tokenize(word):
sentence_ids.append(si)
sentence_toks.append(char)
break
sentence_lens.append(sent_len)
sentence_toks = [x if x in tokenizer.vocab else '[UNK]' for x in sentence_toks]
input_ids = tokenizer.convert_tokens_to_ids(sentence_toks)
return input_ids
def get_speaker(id_info):
speaker = None
if not ("::doc_type" in id_info):
return 'unk'
doc_type = id_info.split("::doc_type")[1].strip()
if doc_type == "dfa":
p = id_info.split("::post")[1]
if p[:2] == " ":
temp = 'unk'
elif p[:1] == " ":
temp = p.split()[0]
else:
assert False
speaker = temp
elif doc_type == "dfb":
p = id_info.split("::speaker")[1]
if p[:2] == " ":
temp = 'unk'
elif p[:1] == " ":
temp = p.split()[0]
else:
assert False
speaker = temp
else:
speaker = 'unk'
return speaker
def load_json(file_name, args, tokenizer):
'bert starts'
FLAG = False
if args.use_bert:
bert_dict = dict()
if os.path.exists(file_name+'.bert'):
with open(file_name+'.bert', 'r', encoding='utf-8') as bertf:
bert_dict = json.load(bertf)
else:
FLAG = True
bert = BertModel.from_pretrained(args.bert_tokenizer_path)
for param in bert.parameters(): param.requires_grad = False
tokenizer = AutoTokenizer.from_pretrained(args.bert_tokenizer_path) # 'bert-base-cased'
bert_pad = bert(torch.LongTensor([tokenizer.convert_tokens_to_ids(['PAD'])]))[0][-1][0] # shape [1,768]
'bert ends'
with open(file_name, 'r', encoding='utf-8') as f:
json_dict = json.load(f)
doc_data = []
# every doc is a json
# document level
for i , doc in enumerate(json_dict):
# print ('making data ',i, len(json_dict))
# sent level
# 在这个doc里, 先把句子合起来
toks, concepts, alignments, edges, clusters = [], [], [], [], []
tokens = []
speakers = []
concept_lens, token_lens, token_seps_index = [], [], []
concepts_for_align = []
bert_embeddings = []
for j, inst in enumerate(doc['data']):
# get snts, tokens, concepts
toks.extend(inst['token'].split())
tokens.append(inst['token'].split())
concept_lens.append(inst['concept_len'])
speaker = get_speaker(inst['id_info'])
speakers.extend([speaker] * inst['concept_len'])
concepts_for_align.append(inst['concept'])
token_lens.append(inst['token_len'])
alignments.append(inst['alignment'])
edges.append(inst['edge'])
'add bert emb'
if FLAG:
bert_tokens = tokenizer.convert_tokens_to_ids(inst['token'].split())
bert_emb = bert(torch.LongTensor([bert_tokens]))
bert_emb = bert_emb[0][-1][0] # shape: token_len, 768
bert_emb = torch.vstack([bert_pad,bert_emb])
tok2conept_align = []
for x in inst['alignment']:
y = x
if isinstance(x, list):
y = int(x[0])
tok2conept_align.append(y+1)
bert_fix_emb = bert_emb[tok2conept_align] # shape: concept_len, 768
bert_embeddings.append(bert_fix_emb)
'add bert emb ends'
concepts = [y for x in concepts_for_align for y in x] # flatten
a = sum(concept_lens)
token_bert_ids = get_bert_ids(tokens, args, tokenizer) # flattened: all sent in this document
# get alignments
align_mapping = get_align_mapping(alignments, token_lens)
# assert len(align_mapping) == len(concepts)
# get edge mapping
edge_mapping = get_edge_mapping(edges, concept_lens) # a list of lists: ['AMR_ROOT', 187, 328],...
# get cluster mapping: new concept IDs in lists, and their edge type
cluster_mapping, cluster_mapping_labels = get_cluster_mapping(doc['cluster'], concept_lens)
# -2, -1, 0, 1, 2
concept_labels = get_concept_labels(cluster_mapping, cluster_mapping_labels, concepts)
if args.use_bert:
if FLAG:
bert_concept = torch.vstack(bert_embeddings) # shape: concept_len, 768
bert_dict[str(i)] = bert_concept.numpy().tolist()
bert_concept = bert_concept.numpy()
else:
bert_concept = np.asarray(bert_dict[str(i)])
'append as the last item'
doc_data.append([speakers, toks, token_bert_ids, concepts, align_mapping,
edge_mapping, cluster_mapping, concept_labels, token_lens, concept_lens,bert_concept])
else:
doc_data.append([speakers, toks, token_bert_ids, concepts, align_mapping,
edge_mapping, cluster_mapping, concept_labels, token_lens,concept_lens,None])
if FLAG:
with open(file_name+'.bert', 'w') as fout:json.dump(bert_dict, fout)
print ('Finished writing bert features...',file_name+'.bert')
return doc_data
'sentence level loading from json'
def load_pretrain_json(file_name, args, tokenizer):
FLAG = False
if args.use_bert:
bert_dict = dict()
if os.path.exists(file_name + '.bert'):
with open(file_name + '.bert', 'r', encoding='utf-8') as bertf:
bert_dict = json.load(bertf)
else:
FLAG = True
bert = BertModel.from_pretrained(args.bert_tokenizer_path)
for param in bert.parameters(): param.requires_grad = False
tokenizer = AutoTokenizer.from_pretrained(args.bert_tokenizer_path) # 'bert-base-cased'
bert_pad = bert(torch.LongTensor([tokenizer.convert_tokens_to_ids(['PAD'])]))[0][-1][0] # shape [1,768]
'bert ends'
with open(file_name, 'r', encoding='utf-8') as f:
json_dict = json.load(f)
print (file_name)
all_sent_data = []
# every doc is a json
# document level
for i, doc in tqdm.tqdm(enumerate(json_dict)):
if i%1000 == 0:
print ('making pretrain data',i,len(json_dict))
# sent level
toks, concepts, alignments, edges, clusters = [], [], [], [], []
tokens = []
# speakers = []
concept_lens, token_lens, token_seps_index = [], [], []
concepts_for_align = []
'bert-related'
bert_embeddings = []
concept_ids = []
bert_tok_ids = []
max_len = 0
for j, inst in enumerate(doc['data']):
# get snts, tokens, concepts
toks.extend(inst['token'].split())
tokens.append(inst['token'].split())
concept_lens.append(inst['concept_len'])
# speaker = get_speaker(inst['id_info'])
# speakers.extend([speaker] * inst['concept_len'])
concepts_for_align.append(inst['concept'])
token_lens.append(inst['token_len'])
alignments.append(inst['alignment'])
edges.append(inst['edge'])
'add bert emb'
if FLAG:
bert_tokens = tokenizer.convert_tokens_to_ids(inst['token'].split())
if len(bert_tokens) >= max_len:
max_len = len(bert_tokens)
bert_tok_ids.append(bert_tokens)
# bert_emb = bert_emb[0][-1][0] # shape: token_len, 768
# bert_emb = torch.vstack([bert_pad, bert_emb])
tok2conept_align = []
for x in inst['alignment']:
y = x
if isinstance(x, list):
y = int(x[0])
tok2conept_align.append(y + 1)
concept_ids.append(tok2conept_align)
# bert_fix_emb = bert_emb[tok2conept_align] # shape: concept_len, 768
# bert_embeddings.append(bert_fix_emb)
'do bert encoding in a doc level'
#pad token ids
if max_len > 512:
max_len = 512
test = np.asarray([np.asarray(x + max_len * [100])[:max_len] for x in bert_tok_ids]) # shape: n_sent, max_len_tok
if test.shape[0] > 0:
bert_emb = bert(torch.LongTensor(test))[0][-1] # torch.Size([n_sent, max_len_tok, 768])
new = bert_pad.repeat(j+1, 1).unsqueeze(1)
bert_emb = torch.cat([new, bert_emb],1)
# pad concept_ids
for batch_id,sent_id in enumerate(concept_ids):
bert_embeddings.append(bert_emb[batch_id][sent_id])
'bert ends'
concepts = [y for x in concepts_for_align for y in x] # flatten
token_bert_ids = get_bert_ids(tokens, args, tokenizer) # flattened: all sent in this document
# get alignments
align_mapping = get_align_mapping(alignments, token_lens)
# assert len(align_mapping) == len(concepts)
# get edge mapping
edge_mapping = get_edge_mapping(edges, concept_lens) # a list of lists: ['AMR_ROOT', 187, 328],...
# cluster_mapping, cluster_mapping_labels = get_cluster_mapping(doc['cluster'], concept_lens)
# -2, -1, 0, 1, 2
# concept_labels = get_concept_labels(cluster_mapping, cluster_mapping_labels, concepts)
# all_sent_data.append([speakers, toks, token_bert_ids, concepts, align_mapping,
# edge_mapping, cluster_mapping, concept_labels, token_lens])
if args.use_bert:
if FLAG:
if test.shape[0] > 0:
bert_concept = torch.vstack(bert_embeddings) # shape: concept_len, 768
bert_dict[str(i)] = bert_concept.numpy().tolist()
bert_concept = bert_concept.numpy()
else:
bert_concept = []
else:
'load from bert_dict'
if str(i) in bert_dict.keys():
bert_concept = np.asarray(bert_dict[str(i)])
else:
bert_concept = []
'append as the last item'
all_sent_data.append([None, toks, token_bert_ids, concepts, align_mapping,
edge_mapping, None, None, token_lens,bert_concept])
else:
all_sent_data.append([None, toks, token_bert_ids, concepts, align_mapping,
edge_mapping, None, None, token_lens, None])
# all_sent_data.append([None, toks, token_bert_ids, concepts, align_mapping,
# edge_mapping, None, None, token_lens, None])
if FLAG:
with open(file_name+'.bert', 'w') as fout:json.dump(bert_dict, fout)
print ('Finished writing bert features...',file_name+'.bert')
return all_sent_data
def load_pretrain_json_with_coref(file_name, args, tokenizer):
with open(file_name, 'r', encoding='utf-8') as f:
json_dict = json.load(f)
print (file_name)
all_sent_data = []
# every doc is a json
# document level
for i, doc in enumerate(json_dict):
for j, inst in enumerate(doc['data']):
# sent level
toks, concepts, alignments, edges, clusters = [], [], [], [], []
tokens = []
# speakers = []
concept_lens, token_lens, token_seps_index = [], [], []
concepts_for_align = []
# get snts, tokens, concepts
toks.extend(inst['token'].split())
tokens.append(inst['token'].split())
concept_lens.append(inst['concept_len'])
# speaker = get_speaker(inst['id_info'])
# speakers.extend([speaker] * inst['concept_len'])
concepts_for_align.append(inst['concept'])
token_lens.append(inst['token_len'])
alignments.append(inst['alignment'])
edges.append(inst['edge'])
concepts = [y for x in concepts_for_align for y in x] # flatten
token_bert_ids = get_bert_ids(tokens, args, tokenizer) # flattened: all sent in this document
# get alignments
align_mapping = get_align_mapping(alignments, token_lens)
# assert len(align_mapping) == len(concepts)
# get edge mapping
edge_mapping = get_edge_mapping(edges, concept_lens) # a list of lists: ['AMR_ROOT', 187, 328],...
cluster_mapping, cluster_mapping_labels = get_cluster_mapping(doc['cluster'], concept_lens)
# -2, -1, 0, 1, 2
concept_labels = get_concept_labels(cluster_mapping, cluster_mapping_labels, concepts)
all_sent_data.append([None, toks, token_bert_ids, concepts, align_mapping,
edge_mapping, cluster_mapping, concept_labels, token_lens])
# all_sent_data.append([None, toks, token_bert_ids, concepts, align_mapping,
# edge_mapping, None, None, token_lens])
return all_sent_data
def make_vocab(batch_data, char_level=False):
count = Counter()
for seq in batch_data:
count.update(seq)
if not char_level:
return count
char_cnt = Counter()
for x, y in count.most_common():
for ch in list(x):
char_cnt[ch] += y
return count, char_cnt
def write_vocab(vocab, path):
with open(path, 'w', encoding='utf-8') as fo:
for x, y in vocab.most_common():
fo.write('%s\t%d\n' % (x, y))
def preprocess_vocab(train_data, args):
# batch data not make batch
tokens, concepts, relations = [], [], []
for i, doc in enumerate(train_data):
tokens.append(doc[1])
concepts.append(doc[3])
temp = []
for j, rel in enumerate(doc[5]):
temp.append(rel[0])
relations.append(temp)
a = 1
# make vocab
token_vocab, token_char_vocab = make_vocab(tokens, char_level=True)
concept_vocab, concept_char_vocab = make_vocab(concepts, char_level=True)
relation_vocab = make_vocab(relations, char_level=False)
write_vocab(token_vocab, args.token_vocab)
write_vocab(token_char_vocab, args.token_char_vocab)
write_vocab(concept_vocab, args.concept_vocab)
write_vocab(concept_char_vocab, args.concept_char_vocab)
write_vocab(relation_vocab, args.relation_vocab)
def list_to_tensor(xs, vocab=None, local_vocabs=None, unk_rate=0.):
pad = vocab.padding_idx if vocab else 0
def toIdx(w, i):
if vocab is None:
return w
if isinstance(w, list):
return [toIdx(_, i) for _ in w]
if random.random() < unk_rate:
return vocab.unk_idx
if local_vocabs is not None:
local_vocab = local_vocabs[i]
if (local_vocab is not None) and (w in local_vocab):
return local_vocab[w]
return vocab.token2idx(w)
max_len = max(len(x) for x in xs)
ys = []
for i, x in enumerate(xs):
y = toIdx(x, i) + [pad]*(max_len-len(x))
ys.append(y)
data = torch.LongTensor(ys).t_().contiguous()
return data
def list_string_to_tensor(xs, vocab, max_string_len=20):
max_len = max(len(x) for x in xs)
ys = []
for x in xs:
y = x + [PAD]*(max_len -len(x))
zs = []
for z in y:
z = list(z[:max_string_len])
zs.append(vocab.token2idx([STR]+z+[END]) + [vocab.padding_idx]*(max_string_len - len(z)))
ys.append(zs)
data = torch.LongTensor(ys).transpose(0, 1).contiguous()
return data
'add negative edges for vgae'
def negative_edges(nodes,edge_index):
n_node = len(nodes)
if len(nodes) == 1:
return [[0,0]]
sample_num = len(edge_index)
neg = []
for i in range(n_node):
for j in range(n_node):
if [i,j] not in edge_index:
neg.append([i,j])
if len(neg)>=sample_num:
false_edge = random.sample(neg,sample_num)
else:
# repeat
false_edge = neg
count = sample_num - len(neg)
false_edge += [random.sample(neg,1)] * count
return false_edge
def get_graph(nodes, edges):
# construct doc-level graphs
neighbor_num_in = []
edges_in = []
edges_out = []
neighbor_num_out = []
neighbors_in = []
neighbors_out = []
edge_index = []
for i, e in enumerate(edges):
edge_index.append(e[1:])
# if len(nodes) >= 1000:
for n in range(len(nodes)):
count, count_in, count_out = 0, 0, 0
neighbors_per_node_in = []
neighbors_per_node_out = []
edges_per_node_in = []
edges_per_node_out = []
for i, e in enumerate(edges):
if n in e:
count = count + 1
if e[1] == n:
count_out = count_out + 1
neighbors_per_node_out.append(e[2])
edges_per_node_out.append(e[0])
else:
count_in = count_in + 1
neighbors_per_node_in.append(e[1])
edges_per_node_in.append(e[0])
neighbor_num_in.append(count_in)
neighbor_num_out.append(count_out)
neighbors_in.append(neighbors_per_node_in)
neighbors_out.append(neighbors_per_node_out)
edges_in.append(edges_per_node_in)
edges_out.append(edges_per_node_out)
max_neighbor_num_in = max(neighbor_num_in)
max_neighbor_num_out = max(neighbor_num_out)
mask_in = [[1] * max_neighbor_num_in for x in range(len(edges_in))]
mask_out = [[1] * max_neighbor_num_out for x in range(len(edges_out))]
for i, e in enumerate(edges_in):
mask_in[i][len(e):max_neighbor_num_in] = [0] * (max_neighbor_num_in - len(e))
neighbors_in[i].extend([-1] * (max_neighbor_num_in - len(e)))
edges_in[i].extend([PAD] * (max_neighbor_num_in - len(e)))
for i, e in enumerate(edges_out):
mask_out[i][len(e):max_neighbor_num_out] = [0] * (max_neighbor_num_out - len(e))
neighbors_out[i].extend([-1] * (max_neighbor_num_out - len(e)))
edges_out[i].extend([PAD] * (max_neighbor_num_out - len(e)))
'add negative edeg index'
edge_index_negative = negative_edges(nodes,edge_index)
graph = {
"edge_index": edge_index,
"edge_index_negative": edge_index_negative,
"neighbor_index_in": neighbors_in,
"neighbor_index_out": neighbors_out,
"edges_in": edges_in,
"edges_out": edges_out,
"mask_in": mask_in,
"mask_out": mask_out
}
# 邻接表
return graph
def build_graph(data, vocabs, token2concept=False):
if token2concept:
new_nodes = data[3] + data[2]
new_edges = data[5]
for i, j in enumerate(data[3]):
if isinstance(j, int):
new_edges.append([C2T, i, j + len(data[2])])
else:
for k in j:
new_edges.append([C2T, i, k + len(data[2])])
graph_data = get_graph(new_nodes, new_edges)
return graph_data
else:
nodes = data[3] # concepts
edges = data[5] # a list of relations: ['AMR_ROOT', 373, 373] (edge_mapping from load_json)
graph_data = get_graph(nodes, edges)
'''
graph_data.keys()
dict_keys(['edge_index', 'neighbor_index_in', 'neighbor_index_out', 'edges_in',
'edges_out', 'mask_in', 'mask_out'])
"adjacency table"
'''
return graph_data
def get_cluster(clusters):
# remove same concept in one cluster and remove same concept in different clusters
clusters_filter1 = []
for i, c in enumerate(clusters):
if len(c) == len(set(c)):
clusters_filter1.append(c)
else:
if len(set(c)) > 1:
clusters_filter1.append(list(set(c)))
else:
continue
clusters_filter2, cs = [], []
for i, c in enumerate(clusters_filter1):
if i == 0:
clusters_filter2.append(c)
cs.extend(c)
else:
t = []
for cc in c:
if cc in cs:
continue
else:
t.append(cc)
if len(t) > 1:
cs.extend(t)
clusters_filter2.append(t)
cluster = []
for i, c in enumerate(clusters_filter2):
# for j in set(c):
# assert len(c) == len(set(c))
# if len(c) != len(set(c)):
# print('xx')
assert len(c) == len(set(c))
for j in c:
cluster.append([j, i + 1])
temp = sorted(cluster, key=itemgetter(0))
c = [i[0] for i in temp]
c_ids = [i[1] for i in temp]
return c, c_ids
def data_to_device_evl(args, train_data):
for j, data in enumerate(train_data):
features = []
for i, d in enumerate(data):
if d == 'concept_len' or d == 'token_segments' \
or d == 'alignment' or d == 'concept4filter':
continue
else:
train_data[j][d] = train_data[j][d].to(args.device)
return train_data
def data_to_device(args, evl_data):
features = []
for i, data in enumerate(evl_data):
if data == 'concept_len' or data == 'token_segments' \
or data == 'alignment' or data == 'concept4filter':
continue
else:
if evl_data[data] is not None:
evl_data[data] = evl_data[data].to(args.device)
return evl_data
def pre_speaker(speakers):
speaker_ids = []
speaker_dict = {'unk': 0, '[SPL]': 1}
for s in speakers:
speaker_dict[s] = len(speaker_dict)
for s in speakers:
speaker_ids.append(speaker_dict[s])
return speaker_ids
def get_filter_ids(args, concept, concept_class, mention_ids, mention_cluster_ids):
with open(args.dict_file, 'r', encoding='utf') as f:
dict_file = [line.strip('\n') for line in f]
dict_file = dict_file[:args.dict_size]
mention_filter_ids, cluster_filter_ids, concept_labels = [], [], []
for i, c in enumerate(concept):
if c not in dict_file:
mention_filter_ids.append(mention_ids[i])
cluster_filter_ids.append(mention_cluster_ids[i])
concept_labels.append(concept_class[i])
else:
continue
return mention_filter_ids, cluster_filter_ids, concept_labels
# def data_to_feature(args, train_data, vocabs,name):
# # train_data: contains rich info loaded from json
#
# features = []
#
#
#
# 'ordered data, save features as the list of json'
# f_path = os.path.dirname(args.train_data)
# f_name = f_path+"/2features_"+name+".json"
# Flag = False
#
# if os.path.exists(f_name):
# with open(f_name) as f:
# graph_features = json.load(f)
# print('Json graph feature loaded.',f_name)
# Flag = True
# else:
# graph_features = []
# print('Making Json graph features, this may take a few minutes..')
#
#
#
# for i, data in enumerate(train_data):
#
# item = dict()
# # concept
# # same shape
# item['concept_len'] = len(data[3])
# item['concept'] = list_to_tensor([data[3]], vocabs['concept'])
# item['concept_char'] = list_string_to_tensor([data[3]], vocabs['concept_char'])
#
# # speaker
# item['speaker'] = torch.LongTensor(pre_speaker(data[0])).unsqueeze(0)
#
# # graph
# if Flag:
# graph = graph_features[i]
#
# else:
# graph = build_graph(data, vocabs, False)
# graph_features.append(graph)
# print(i)
#
#
#
# item['edges_index_in'] = list_to_tensor(graph['edges_in'], vocabs['relation']).transpose(0, 1).unsqueeze(0)
# item['edges_index_out'] = list_to_tensor(graph['edges_out'], vocabs['relation']).transpose(0, 1).unsqueeze(0)
# item['neighbor_index_in'] = torch.LongTensor(graph['neighbor_index_in']).unsqueeze(0)
# item['neighbor_index_out'] = torch.LongTensor(graph['neighbor_index_out']).unsqueeze(0)
# item['mask_in'] = torch.LongTensor(graph['mask_in']).unsqueeze(0)
# item['mask_out'] = torch.LongTensor(graph['mask_out']).unsqueeze(0)
# item['edge_index'] = torch.LongTensor(graph['edge_index']).transpose(0, 1)
# item['edge_index_negative'] = torch.LongTensor(graph['edge_index_negative']).transpose(0, 1)
# # token
# token_len = len(data[1])
# item['token_len'] = torch.LongTensor([token_len])
# item['token'] = list_to_tensor([data[1]], vocabs['token'])
# item['token_bert_ids'] = torch.LongTensor(data[2]).unsqueeze(0)
# item['token_char'] = list_string_to_tensor([data[1]], vocabs['token_char'])
# item['token_segments'] = data[-1]
#
#
#
# # cluster
# cluster, cluster_ids = get_cluster(data[6]) # predict clusters for given concepts, same cluster has the same label number
# mention_cluster_ids = [0] * item['concept_len']
# mention_ids = list(range(item['concept_len']))
# for idx, (mention_id, cluster_id) in enumerate(zip(cluster, cluster_ids)):
# mention_cluster_ids[mention_id] = cluster_id
# '''mention_cluster_ids, a list of 390, each concept, 0 means nothing, otherwise it means cluster ID'''
#
#
# item['gold_mention_ids'] = torch.LongTensor(cluster).unsqueeze(0)
# item['gold_cluster_ids'] = torch.LongTensor(cluster_ids).unsqueeze(0)
#
#
# item['mention_ids'] = torch.LongTensor(mention_ids).unsqueeze(0)
# item['mention_cluster_ids'] = torch.LongTensor(mention_cluster_ids).unsqueeze(0)
# '''gold only includes clustered concepts, but mention has every single concepts (of all types)'''
#
# # alignment
# item['alignment'] = data[4]
# # dict to filter
# # item['concept4filter'] = data[3]
#
# mention_filter_ids, cluster_filter_ids, concept_labels = get_filter_ids(args, data[3], data[7], mention_ids, mention_cluster_ids)
# item['mention_filter_ids'] = torch.LongTensor(mention_filter_ids).unsqueeze(0)
# item['cluster_filter_ids'] = torch.LongTensor(cluster_filter_ids).unsqueeze(0)
#
#
#
# if args.use_dict:
# item['concept_class'] = torch.LongTensor(concept_labels)
# else:
# item['concept_class'] = torch.LongTensor(data[7])
#
# features.append(item)
#
# 'dump graph features'
# if not Flag:
# print ('Saving graph features as Json...')
# with open(f_name, 'w') as fout:
# json.dump(graph_features, fout)
#
#
# return features
def data_to_feature(args, train_data, vocabs,name):
# train_data: contains rich info loaded from json
features = []
# if name.endswith('test') or name.endswith('test_little'):
if name.endswith('dev') or name.endswith('dev_little'):
writing_token = []
writing_concepts = []
writing_alignment = []
'ordered data, save features as the list of json'
f_path = os.path.dirname(args.train_data)
# f_name = f_path+"/pretrain_vocab_new_features_alllevel_"+name+".json"
f_name = f_path + "/pretrain_vocab_new_features_" + name + ".json"
Flag = False
if os.path.exists(f_name):
with open(f_name) as f:
graph_features = json.load(f)
print('Json graph feature loaded.',f_name)
Flag = True
else:
graph_features = []
print('Making Json graph features, this may take a few minutes..')
for i, data in enumerate(train_data):
item = dict()
# if name.endswith('test') or name.endswith('test_little'):
if name.endswith('dev') or name.endswith('dev_little'):
writing_concepts.append(data[3])
writing_alignment.append(data[4]) # concept and alignment has the same shape
writing_token.append(data[1])
# import pdb;pdb.set_trace()
# concept
# same shape
item['concept_len'] = len(data[3])
item['concept'] = list_to_tensor([data[3]], vocabs['concept'])
item['concept_char'] = list_string_to_tensor([data[3]], vocabs['concept_char'])
# speaker
item['speaker'] = torch.LongTensor(pre_speaker(data[0])).unsqueeze(0)
# graph
if Flag:
graph = graph_features[i]
else:
# import pdb;pdb.set_trace()
if len(data[3]) <= 3000:
graph = build_graph(data, vocabs, False)
graph_features.append(graph)
print(i)
else:
print ('--- Skip')
item['edges_index_in'] = list_to_tensor(graph['edges_in'], vocabs['relation']).transpose(0, 1).unsqueeze(0)
item['edges_index_out'] = list_to_tensor(graph['edges_out'], vocabs['relation']).transpose(0, 1).unsqueeze(0)
item['neighbor_index_in'] = torch.LongTensor(graph['neighbor_index_in']).unsqueeze(0)
item['neighbor_index_out'] = torch.LongTensor(graph['neighbor_index_out']).unsqueeze(0)
item['mask_in'] = torch.LongTensor(graph['mask_in']).unsqueeze(0)
item['mask_out'] = torch.LongTensor(graph['mask_out']).unsqueeze(0)
item['edge_index'] = torch.LongTensor(graph['edge_index']).transpose(0, 1)
item['edge_index_negative'] = torch.LongTensor(graph['edge_index_negative']).transpose(0, 1)
# token
token_len = len(data[1])
item['token_len'] = torch.LongTensor([token_len])
item['token'] = list_to_tensor([data[1]], vocabs['token'])
item['token_bert_ids'] = torch.LongTensor(data[2]).unsqueeze(0)
item['token_char'] = list_string_to_tensor([data[1]], vocabs['token_char'])
# item['token_segments'] = data[-2]
item['token_segments'] = data[-3]
'add sentence length: this is a list (a shape of [1,num_of_sent]'
# item['sentence_len'] =torch.LongTensor(data[-1]).unsqueeze(0)
item['sentence_len'] = torch.LongTensor(data[-2]).unsqueeze(0)
# cluster
cluster, cluster_ids = get_cluster(data[6]) # predict clusters for given concepts, same cluster has the same label number
mention_cluster_ids = [0] * item['concept_len']
mention_ids = list(range(item['concept_len']))
for idx, (mention_id, cluster_id) in enumerate(zip(cluster, cluster_ids)):