-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata_processor.py
More file actions
1850 lines (1682 loc) · 91.2 KB
/
Copy pathdata_processor.py
File metadata and controls
1850 lines (1682 loc) · 91.2 KB
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 argparse
import datetime
import json
import math
import os
import random
import re
from collections import defaultdict, Counter
import dgl
import joblib
import numpy as np
import pandas as pd
import scipy as sp
import torch
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
from torch.utils.data import DataLoader
from torchtext.data.utils import get_tokenizer
from transformers import BertTokenizer, BertModel
from torchtext.vocab import build_vocab_from_iterator, Vectors, vocab
from our_models.TSGCN import get_paper_ego_subgraph
from utilis.scripts import get_configs, IndexDict, add_new_elements
# from utilis.bertwhitening_utils import input_to_vec, compute_kernel_bias, transform_and_normalize, inputs_to_vec
import networkx as nx
import pickle as pkl
# tokenizer = get_tokenizer('basic_english')
UNK, PAD, SEP = '[UNK]', '[PAD]', '[SEP]'
class DataProcessor:
def __init__(self, data_source, max_len=256, seed=123, norm=False, log=False, time=None, model_config=None):
print('Init...')
self.data_root = './data/'
self.data_source = data_source
self.seed = int(seed)
self.max_len = max_len
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.tokenizer = None
self.mean = 0
self.std = 1
self.norm = norm
self.log = log
self.time = time
self.config = model_config if model_config else dict()
self.batch_graph = self.config.get('batch_graph', False)
self.selected_ids = None
print(self.time)
# if self.data_source == 'pubmed':
# self.data_cat_path = self.data_root + self.data_source + '/'
# elif self.data_source == 's2orc':
# self.data_cat_path = self.data_root + self.data_source + '/'
# elif self.data_source == 'mag':
# self.data_cat_path = self.data_root + self.data_source + '/'
# elif self.data_source == 'dblp':
# self.data_cat_path = self.data_root + self.data_source + '/'
# elif self.data_source == 'sdblp':
# self.data_cat_path = self.data_root + self.data_source + '/'
if self.data_source.endswith('pubmed'):
self.data_cat_path = self.data_root + self.data_source + '/'
elif self.data_source == 's2orc':
self.data_cat_path = self.data_root + self.data_source + '/'
elif self.data_source == 'mag':
self.data_cat_path = self.data_root + self.data_source + '/'
elif self.data_source.endswith('dblp'):
self.data_cat_path = self.data_root + self.data_source + '/'
def split_data(self, rate=0.8, fixed_num=None, shuffle=True, by='normal', time=None, cut_time=2015):
if self.time:
time = self.time
all_values = json.load(open(self.data_cat_path + 'sample_citation_accum.json'))
print(len(all_values))
all_ids = list(all_values.keys())
if self.data_source.endswith('pubmed'):
info_dict = json.load(open(self.data_cat_path + 'sample_info_dict.json'))
time_dict = dict(map(lambda x: (x[0], x[1]['pub_date']['year']), info_dict.items()))
title_dict = dict(map(lambda x: (x[0], x[1]['title']), info_dict.items()))
abs_dict = dict(map(lambda x: (x[0], x[1]['abstract']), info_dict.items()))
elif self.data_source.endswith('dblp'):
info_dict = json.load(open(self.data_cat_path + 'sample_info_dict.json'))
time_dict = dict(map(lambda x: (x[0], x[1]['year']), info_dict.items()))
title_dict = dict(map(lambda x: (x[0], x[1]['title']), info_dict.items()))
del info_dict
abs_dict = json.load(open(self.data_cat_path + 'sample_abstract_dict.json'))
# elif self.data_source == 'sdblp':
# info_dict = json.load(open(self.data_cat_path + 'sample_info_dict.json'))
# time_dict = dict(map(lambda x: (x[0], x[1]['year']), info_dict.items()))
# title_dict = dict(map(lambda x: (x[0], x[1]['title']), info_dict.items()))
# del info_dict
# abs_dict = json.load(open(self.data_cat_path + 'sample_abstract_dict.json'))
if by == 'time':
# as by time, no rate and fixed_num, but use year
# here only input year < time, but should know the difference
train_time, val_time, test_time = time
print('time:', time)
print('cut time:', cut_time)
test_ids = [key for key in all_values if int(time_dict[key]) <= test_time]
print('test samples:', len(test_ids))
test_idx = test_time + 5 - cut_time - 1
print('test_idx', test_idx)
test_values = list(map(lambda x: all_values[x][1][test_idx] - all_values[x][0][test_idx], test_ids))
key_ids = set(map(lambda x: x[0],
filter(lambda x: x[1] >= self.config['cut_threshold'][-1], zip(test_ids, test_values))))
selected_ids = list(key_ids)
print('key_ids', len(key_ids))
# count = 0
random.seed(self.seed)
random.shuffle(test_ids)
for paper in test_ids:
if paper not in key_ids:
selected_ids.append(paper)
# count += 1
if len(selected_ids) >= fixed_num:
break
all_values = dict([(paper, all_values[paper]) for paper in selected_ids])
# train_ids = [key for key in all_values if int(info_dict[key]['pub_time']['year']) <= train_time]
# print(len(train_ids))
# val_ids = [key for key in all_values if int(info_dict[key]['pub_time']['year']) <= val_time]
# print(len(val_ids))
# test_ids = [key for key in all_values if int(info_dict[key]['pub_time']['year']) <= test_time]
# print(len(test_ids))
train_ids = [key for key in all_values if int(time_dict[key]) <= train_time]
print('train samples:', len(train_ids))
val_ids = [key for key in all_values if int(time_dict[key]) <= val_time]
print('val samples:', len(val_ids))
test_ids = [key for key in all_values if int(time_dict[key]) <= test_time]
print('test samples:', len(test_ids))
# here choose the cur + 5 as predict value 2015?
# will be changed in the future
# [2011, 2012, 2013, 2014, 2015], [2016, 2017, 2018, 2019, 2020]
train_idx = train_time + 5 - cut_time - 1
train_values = list(map(lambda x: all_values[x][1][train_idx] - all_values[x][0][train_idx], train_ids))
val_idx = val_time + 5 - cut_time - 1
val_values = list(map(lambda x: all_values[x][1][val_idx] - all_values[x][0][val_idx], val_ids))
test_idx = test_time + 5 - cut_time - 1
test_values = list(map(lambda x: all_values[x][1][test_idx] - all_values[x][0][test_idx], test_ids))
print('time:', train_time, val_time, test_time)
print('idx:', train_idx, val_idx, test_idx)
else:
if shuffle:
random.seed(self.seed)
print('data_processor seed', self.seed)
random.shuffle(all_ids)
total_count = len(all_ids)
train_ids = all_ids[:int(total_count * rate)]
val_ids = all_ids[int(total_count * rate): int(total_count * ((1 - rate) / 2 + rate))]
test_ids = all_ids[int(total_count * ((1 - rate) / 2 + rate)):]
train_values = list(map(lambda x: all_values[x], train_ids))
val_values = list(map(lambda x: all_values[x], val_ids))
test_values = list(map(lambda x: all_values[x], test_ids))
train_contents = list(
map(lambda x: re.sub('\s+', ' ', str(title_dict[x]) + '. ' + abs_dict[x]), train_ids))
val_contents = list(
map(lambda x: re.sub('\s+', ' ', str(title_dict[x]) + '. ' + abs_dict[x]), val_ids))
test_contents = list(
map(lambda x: re.sub('\s+', ' ', str(title_dict[x]) + '. ' + abs_dict[x]), test_ids))
train_times = list(map(lambda x: int(time_dict[x]), train_ids))
val_times = list(map(lambda x: int(time_dict[x]), val_ids))
test_times = list(map(lambda x: int(time_dict[x]), test_ids))
cut_data = {
'train': [train_ids, train_values, train_contents, train_times],
'val': [val_ids, val_values, val_contents, val_times],
'test': [test_ids, test_values, test_contents, test_times],
}
torch.save(cut_data, self.data_cat_path + 'split_data')
def show_graph_info(self, graph_name='graph_sample_feature_vector'):
all_values = json.load(open(self.data_cat_path + 'sample_citation_accum.json'))
print(len(all_values))
all_ids = list(all_values.keys())
trans_dict = json.load(open(self.data_cat_path + 'sample_node_trans.json'))
all_papers = [trans_dict['paper'][paper] for paper in all_ids]
graph = torch.load(self.data_cat_path + graph_name)
all_refs = graph.in_degrees(torch.tensor(all_papers), etype='is cited by').numpy().tolist()
all_cites = graph.in_degrees(torch.tensor(all_papers), etype='cites').numpy().tolist()
all_times = graph.nodes['paper'].data['time'][all_papers, :].squeeze(dim=-1).numpy().tolist()
df_count = pd.DataFrame(index=all_papers, data={'ref': all_refs, 'cite': all_cites, 'time': all_times})
print(df_count.describe(percentiles=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99]))
df_count = df_count[df_count['time'] <= 2011]
print(df_count.describe(percentiles=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.98, 0.99]))
def get_data(self, phases=None, selected_ids=None):
cur_data = torch.load(self.data_cat_path + 'split_data')
cur_phases = list(cur_data.keys())
if phases is not None:
for phase in cur_phases:
if phase not in phases:
del cur_data[phase]
# print(len(cur_data[phase]))
# print(len(list(zip(*zip(*cur_data[phase])))))
# print(len([*list(zip(cur_data[phase]))]))
if selected_ids is not None:
for phase in cur_data:
temp_data = list(zip(*filter(lambda x: x[0] in selected_ids, zip(*cur_data[phase]))))
cur_data[phase] = temp_data
print('{}:'.format(phase), len(cur_data[phase][0]))
return cur_data
def get_selected_ids(self):
df = pd.read_csv('./results/test/{}/hard_ones.csv'.format(self.data_source), index_col=0)
self.selected_ids = set(list(df.index.astype(str)))
return self.selected_ids
def add_attrs(self):
data = torch.load(self.data_cat_path + 'split_data')
info = json.load(open(self.data_cat_path + 'sample_info_dict.json', 'r'))
for phase in data:
if len(data[phase]) > 3:
continue
if self.data_source == 'pubmed':
pub_time = [int(info[paper]['pub_time']['year']) for paper in data[phase][0]]
elif self.data_source in ['dblp', 'sdblp']:
pub_time = [int(info[paper]['year']) for paper in data[phase][0]]
# print(pub_time)
data[phase].append(pub_time)
torch.save(data, self.data_cat_path + 'split_data')
def get_tokenizer(self, tokenizer_type='basic', tokenizer_path=None):
if tokenizer_type == 'bert':
self.tokenizer = CustomBertTokenizer(max_len=self.max_len, bert_path=tokenizer_path,
data_path=self.data_cat_path)
elif tokenizer_type == 'glove':
self.tokenizer = VectorTokenizer(max_len=self.max_len, vector_path=tokenizer_path,
data_path=self.data_cat_path, name='glove')
else:
self.tokenizer = BasicTokenizer(max_len=self.max_len, data_path=self.data_cat_path)
data = torch.load(self.data_cat_path + 'split_data')
self.tokenizer.load_vocab(data['train'][2], seed=self.seed)
return self.tokenizer
def get_dataloader(self, batch_size=32, num_workers=0, graph_dict=None):
print('workers', num_workers)
# data = torch.load(self.data_cat_path + 'split_data')
# self.data = data
phases = ['train', 'val', 'test']
if graph_dict:
phases = [phase for phase in phases if phase in graph_dict['data']]
data = self.get_data(phases, self.selected_ids)
# all_last_values = map(lambda x: x[1][-1], data['train'][1])
if self.norm:
# all_train_values = np.sum(list(map(lambda x: [num for num in (x[0] + x[1]) if num >= 0], data['train'][1])))
all_train_values = data['train'][1]
self.mean = np.mean(all_train_values)
self.std = np.std(all_train_values)
print(self.mean)
print(self.std)
self.graph_dict = graph_dict
collate_batch_method = self.collate_batch
if self.batch_graph == 'ego':
# collate_batch_method = {phase: self.graph_method_map(phase) for phase in phases}
collate_batch_method = {phase: ego_collate_batch(self, phase) for phase in phases}
elif self.batch_graph == 'emb':
collate_batch_method = self.emb_collate_batch
paper_idx_trans = dict(zip(self.graph_dict['node_trans']['paper'],
range(len(self.graph_dict['node_trans']['paper']))))
print(self.data_cat_path + self.config['emb_name'] + '_embs')
all_embs = joblib.load(self.data_cat_path + self.config['emb_name'] + '_embs')
print(len(all_embs))
for phase in phases:
paper_ids = data[phase][0]
embs = [all_embs[paper_idx_trans[paper]] for paper in paper_ids]
print(len(embs))
data[phase].append(embs)
# if phase == 'train':
# self.embs = torch.from_numpy(np.array(embs))
if type(collate_batch_method) != dict:
collate_batch_method = {phase: collate_batch_method for phase in phases}
self.dataloaders = []
for phase in phases:
self.dataloaders.append(CustomDataLoader(dataset=list(zip(*data[phase])), batch_size=batch_size,
shuffle=True, num_workers=num_workers,
collate_fn=collate_batch_method[phase],
mean=self.mean, std=self.std, log=self.log, phase=phase))
while len(self.dataloaders) < 3:
self.dataloaders.append(None)
return self.dataloaders
def collate_batch(self, batch):
values_list, content_list = [], []
# inputs_list, valid_lens = [], []
length_list = []
mask_list = []
ids_list = []
time_list = []
# print(batch)
for (_ids, _values, _contents, _time) in batch:
# processed_content, seq_len, mask = self.text_pipeline(_content)
# # print(_label)
processed_content, seq_len, mask = self.tokenizer.encode(_contents)
# values_list.append(_values)
# inputs, valid_len = self.values_pipeline(_values)
# values_list.append(self.label_pipeline(_values))
values_list.append(_values)
# inputs_list.append(inputs)
# valid_lens.append(valid_len)
content_list.append(processed_content)
length_list.append(seq_len)
mask_list.append(mask)
# ids_list.append(int(_ids.strip()))
ids_list.append(_ids.strip())
time_list.append(_time)
# content_list = torch.cat(content_list)
content_batch = torch.tensor(content_list, dtype=torch.int64)
values_list = torch.tensor(values_list, dtype=torch.int64)
# inputs_list = torch.tensor(inputs_list, dtype=torch.float32)
# valid_lens = torch.tensor(valid_lens, dtype=torch.int8)
length_list = torch.tensor(length_list, dtype=torch.int64)
mask_list = torch.tensor(mask_list, dtype=torch.int8)
# ids_list = torch.tensor(ids_list, dtype=torch.int64)
# print(len(label_list))
# content_list = [content_batch, inputs_list, valid_lens]
time_list = torch.tensor(time_list, dtype=torch.long)
content_list = content_batch
return content_list, values_list, length_list, \
mask_list, ids_list, time_list, None
def emb_collate_batch(self, batch):
values_list, emb_batch = [], []
# inputs_list, valid_lens = [], []
length_list = []
mask_list = []
ids_list = []
time_list = []
# print(batch)
for (_ids, _values, _contents, _time, _embs) in batch:
# processed_content, seq_len, mask = self.text_pipeline(_content)
# # print(_label)
# processed_content, seq_len, mask = self.tokenizer.encode(_contents)
# values_list.append(_values)
# inputs, valid_len = self.values_pipeline(_values)
# values_list.append(self.label_pipeline(_values))
values_list.append(_values)
# inputs_list.append(inputs)
# valid_lens.append(valid_len)
emb_batch.append(_embs)
length_list.append(0)
mask_list.append(0)
# ids_list.append(int(_ids.strip()))
ids_list.append(_ids.strip())
time_list.append(_time)
# content_list = torch.cat(content_list)
# content_batch = torch.tensor(content_list, dtype=torch.int64)
emb_batch = torch.from_numpy(np.array(emb_batch))
# print(emb_batch.shape)
values_list = torch.tensor(values_list, dtype=torch.int64)
# inputs_list = torch.tensor(inputs_list, dtype=torch.float32)
# valid_lens = torch.tensor(valid_lens, dtype=torch.int8)
length_list = torch.tensor(length_list, dtype=torch.int64)
mask_list = torch.tensor(mask_list, dtype=torch.int8)
# ids_list = torch.tensor(ids_list, dtype=torch.int64)
# print(len(label_list))
# content_list = [content_batch, inputs_list, valid_lens]
time_list = torch.tensor(time_list, dtype=torch.long)
return emb_batch, values_list, length_list, \
mask_list, ids_list, time_list, None
# def get_embs(self, tokenizer_type, tokenizer_path, name='graph_sample_feature', mode='vector',
# split_abstract=False):
# print(name)
# print(tokenizer_path)
# print('graph mode:', mode)
# # graph = torch.load(self.data_cat_path + 'graph_sample')
# node_trans = json.load(open(self.data_cat_path + 'sample_node_trans.json', 'r'))
# paper_trans = node_trans['paper']
# node_ids = list(paper_trans.values())
# node_ids.sort()
# print(len(node_ids))
# index_trans = dict(zip(paper_trans.values(), paper_trans.keys()))
#
# if not split_abstract:
# info_dict = json.load(open(self.data_cat_path + 'sample_info_dict.json', 'r'))
# abstracts = list(map(lambda x: info_dict[index_trans[x]]['abstract'].strip(), node_ids))
# del info_dict
# else:
# abs_dict = json.load(open(self.data_cat_path + 'sample_abstract_dict.json', 'r'))
# abstracts = list(map(lambda x: abs_dict[index_trans[x]].strip(), node_ids))
# del abs_dict
#
# feature_list = []
#
# self.tokenizer = self.get_tokenizer(tokenizer_type, tokenizer_path)
# self.tokenizer.load_vocab()
# print('bert-whitening embeddings')
# # self.tokenizer = CustomBertTokenizer(max_len=self.max_len, bert_path=tokenizer_path)
# # self.tokenizer.load_vocab()
# print(self.tokenizer.tokenizer)
#
# if mode == 'bw':
# bert_model = BertModel.from_pretrained(tokenizer_path, return_dict=True, output_hidden_states=True).to(
# self.device)
# elif mode in ['sbw', 'sbert']:
# bert_model = SentenceTransformer(tokenizer_path)
#
# # first get kernel and bias
# # params = {'kernel': 0, 'bias': 0}
# all_embs = []
#
# batch_size = 64
# if mode == 'bw':
# count = 0
# temp_tokens, temp_masks, temp_lens = [], [], []
# for abstract in tqdm(abstracts):
# processed_content, seq_len, mask = self.tokenizer.encode(abstract)
# temp_tokens.append(processed_content)
# temp_masks.append(mask)
# temp_lens.append(seq_len)
# count += 1
# if ((count > 0) and (count % batch_size == 0)) | (count == len(abstracts)):
# tokens = torch.tensor(temp_tokens, dtype=torch.long).to(self.device)
# masks = torch.tensor(temp_masks, dtype=torch.long).to(self.device)
# seq_lens = temp_lens
# output = inputs_to_vec([tokens, masks], bert_model, 'first_last_avg', seq_lens)
# # print(output.shape)
# all_embs.append(output)
# temp_tokens, temp_masks, temp_lens = [], [], []
# elif mode in ['sbw', 'sbert']:
# count = 0
# all_embs = []
# temp_list = []
# for abstract in tqdm(abstracts):
# # print(abstract)
# temp_list.append(abstract)
# count += 1
# if ((count > 0) and (count % batch_size == 0)) | (count == len(abstracts)):
# output = bert_model.encode(temp_list)
# # print(output.shape)
# all_embs.append(output)
# temp_list = []
#
# all_embs = np.array(all_embs)
# all_embs = np.concatenate(all_embs, axis=0)
#
# print(all_embs.shape)
# joblib.dump(all_embs, self.data_cat_path + name + '_' + mode + '_embs')
def get_feature_graph(self, tokenizer_type, tokenizer_path, name='graph_sample_feature', mode='vector',
split_abstract=False, time_range=(2001, 2015)):
print(name)
print(tokenizer_path)
print('graph mode:', mode)
graph = torch.load(self.data_cat_path + 'graph_sample')
node_trans = json.load(open(self.data_cat_path + 'sample_node_trans.json', 'r'))
paper_trans = node_trans['paper']
node_ids = list(paper_trans.values())
node_ids.sort()
print(len(node_ids))
index_trans = dict(zip(paper_trans.values(), paper_trans.keys()))
if not split_abstract:
info_dict = json.load(open(self.data_cat_path + 'sample_info_dict.json', 'r'))
abstracts = list(map(lambda x: info_dict[index_trans[x]]['abstract'].strip(), node_ids))
del info_dict
else:
abs_dict = json.load(open(self.data_cat_path + 'sample_abstract_dict.json', 'r'))
abstracts = list(map(lambda x: abs_dict[index_trans[x]].strip(), node_ids))
del abs_dict
feature_list = []
self.tokenizer = self.get_tokenizer(tokenizer_type, tokenizer_path)
self.tokenizer.load_vocab()
if mode == 'vector':
# self.tokenizer = VectorTokenizer(max_len=self.max_len, vector_path=tokenizer_path,
# data_path=self.data_cat_path, name='glove')
# self.tokenizer.load_vocab()
print(self.tokenizer.vectors.shape)
for abstract in tqdm(abstracts):
processed_content, seq_len, mask = self.tokenizer.encode(abstract)
node_embedding = self.tokenizer.vectors[processed_content][:seq_len].mean(dim=0, keepdim=True)
if torch.isnan(node_embedding).sum().item() > 0:
print(abstract)
node_embedding = torch.zeros_like(node_embedding)
feature_list.append(node_embedding)
# elif mode == 'bert':
# print('last 2nd avgpool')
# # self.tokenizer = CustomBertTokenizer(max_len=self.max_len, bert_path=tokenizer_path)
# # self.tokenizer.load_vocab()
# print(self.tokenizer.tokenizer)
# bert_model = BertModel.from_pretrained(tokenizer_path, return_dict=True, output_hidden_states=True).to(
# self.device)
#
# for abstract in tqdm(abstracts):
# processed_content, seq_len, mask = self.tokenizer.encode(abstract)
# tokens = torch.tensor(processed_content).unsqueeze(dim=0).to(self.device)
# mask = torch.tensor(mask).unsqueeze(dim=0).to(self.device)
# output = bert_model(tokens, attention_mask=mask)
# node_embedding = output['hidden_states'][-2][0, :seq_len].mean(dim=0, keepdim=True).detach().cpu()
# # print(node_embedding.shape)
# feature_list.append(node_embedding)
# elif mode == 'sbert':
# all_embs = joblib.load(self.data_cat_path + name + '_' + mode + '_embs')
# feature_list = torch.from_numpy(all_embs)
#
# elif mode.endswith('bw'):
# all_embs = joblib.load(self.data_cat_path + name + '_' + mode + '_embs')
elif mode == 'token':
# self.get_tokenizer(tokenizer_type, tokenizer_path)
# self.tokenizer.load_vocab()
seq_lens = []
masks = []
for abstract in tqdm(abstracts):
processed_content, seq_len, mask = self.tokenizer.encode(abstract)
processed_content = torch.tensor(processed_content).unsqueeze(dim=0)
seq_len = torch.tensor(seq_len).unsqueeze(dim=0)
mask = torch.tensor(mask).unsqueeze(dim=0)
feature_list.append(processed_content)
seq_lens.append(seq_len)
masks.append(mask)
# graph.ndata['seq_len'] = torch.cat(seq_lens, dim=0)
# graph.ndata['mask'] = torch.cat(masks, dim=0)
#
# graph.ndata['h'] = torch.cat(feature_list, dim=0)
# print(graph.ndata['h'].shape)
# torch.save(graph, self.data_cat_path + name + '_' + mode)
graph.nodes['paper'].data['seq_len'] = torch.cat(seq_lens, dim=0)
graph.nodes['paper'].data['mask'] = torch.cat(masks, dim=0)
# if mode.endswith('bw'):
# # graph.nodes['paper'].data['h'] = feature_list
# print('not here')
# elif mode == 'sbert':
# graph.nodes['paper'].data['h'] = feature_list
if mode == 'random':
paper_count = graph.nodes('paper').shape[0]
graph.nodes['paper'].data['h'] = torch.randn(paper_count, 300, dtype=torch.float32)
else:
graph.nodes['paper'].data['h'] = torch.cat(feature_list, dim=0)
print(graph.nodes['paper'].data['h'].shape)
# author_src, author_dst = graph.edges(form='uv', etype='writes', order='srcdst')
# journal_src, journal_dst = graph.edges(form='uv', etype='publishes', order='srcdst')
author_src, author_dst = graph.edges(form='uv', etype='writes', order='eid')
journal_src, journal_dst = graph.edges(form='uv', etype='publishes', order='eid')
# torch.save(graph, self.data_cat_path + name + '_' + mode)
joblib.dump(graph, self.data_cat_path + name + '_' + mode + '.job')
for time_point in range(time_range[0], time_range[1] + 1):
print('-' * 30 + str(time_point) + '-' * 30)
sub_papers = graph.nodes('paper')[graph.nodes['paper'].data['time'].squeeze(dim=-1) <= time_point]
print('paper', sub_papers.shape)
selected_journal = list(
set(journal_src[graph.edges['publishes'].data['time'].squeeze(dim=-1) <= time_point].numpy().tolist()))
print('journal', len(selected_journal))
selected_author = list(
set(author_src[graph.edges['writes'].data['time'].squeeze(dim=-1) <= time_point].numpy().tolist()))
print('author', len(selected_author))
sub_nodes_dict = {
'paper': sub_papers,
'author': selected_author,
'journal': selected_journal
}
sub_graph = dgl.node_subgraph(graph, sub_nodes_dict)
sub_graph = dgl.remove_self_loop(sub_graph, 'is cited by')
sub_graph = dgl.remove_self_loop(sub_graph, 'cites')
# if mode.endswith('bw'):
# cur_idx = sub_graph.nodes['paper'].data[dgl.NID]
# cur_embs = all_embs[cur_idx, :]
# print(cur_embs.shape)
# kernel, bias = compute_kernel_bias([cur_embs])
# kernel = kernel[:, :300] # 300 dim
#
# feature_list = torch.from_numpy(transform_and_normalize(cur_embs, kernel, bias).astype(np.float32))
# print(feature_list.shape)
# sub_graph.nodes['paper'].data['h'] = feature_list
if mode != 'token':
emb_dim = sub_graph.nodes['paper'].data['h'].shape[1]
author_features = []
# print(sub_papers)
# paper_oids = sub_graph.nodes['paper'].data[dgl.NID].numpy().tolist()
# oid_cid_trans = dict(zip(paper_oids, range(len(paper_oids))))
cur_author_src, cur_author_dst = sub_graph.edges(form='uv', etype='writes', order='eid')
cur_journal_src, cur_journal_dst = sub_graph.edges(form='uv', etype='publishes', order='eid')
# print(oid_cid_trans)
for author in tqdm(sub_graph.nodes('author')):
temp_papers = cur_author_dst[cur_author_src == author]
if len(temp_papers) == 0:
raise Exception
# print(temp_papers)
author_features.append(
torch.mean(sub_graph.nodes['paper'].data['h'][temp_papers, :], dim=0, keepdim=True))
if len(author_features) == 0:
sub_graph.nodes['author'].data['h'] = torch.zeros((0, emb_dim), dtype=torch.float32)
else:
sub_graph.nodes['author'].data['h'] = torch.cat(author_features, dim=0)
print(sub_graph.nodes['author'].data['h'].shape)
journal_features = []
for journal in tqdm(sub_graph.nodes('journal')):
# temp_papers = journal_dst[journal_src == journal]
# journal_features.append(
# torch.mean(graph.nodes['paper'].data['h'][temp_papers], dim=0, keepdim=True))
# temp_papers = sub_graph.out_edges(journal, etype='publishes')[1]
# temp_papers = [oid_cid_trans[paper] for paper in journal_dst[journal_src == journal].numpy().tolist()]
temp_papers = cur_journal_dst[cur_journal_src == journal]
if len(temp_papers) == 0:
raise Exception
# print(temp_papers)
journal_features.append(
torch.mean(sub_graph.nodes['paper'].data['h'][temp_papers, :], dim=0, keepdim=True))
if len(journal_features) == 0:
sub_graph.nodes['journal'].data['h'] = torch.zeros((0, emb_dim), dtype=torch.float32)
else:
sub_graph.nodes['journal'].data['h'] = torch.cat(journal_features, dim=0)
print(sub_graph.nodes['journal'].data['h'].shape)
time_features = []
cur_times = sorted(set(sub_graph.nodes['paper'].data['time'].squeeze(dim=-1).numpy().tolist()))
for pub_time in tqdm(cur_times):
cur_index = np.argwhere(
sub_graph.nodes['paper'].data['time'].squeeze(dim=-1).numpy() == pub_time).squeeze(
axis=-1)
time_features.append(sub_graph.nodes['paper'].data['h'][cur_index].mean(dim=0, keepdim=True))
time_features = torch.cat(time_features, dim=0)
print(time_features.shape)
sub_graph = add_new_elements(sub_graph, nodes={'time': len(cur_times)}, ndata={'time': {
'h': time_features,
'_ID': torch.tensor(cur_times, dtype=torch.long)
}})
print(sub_graph)
# print(sub_graph.ntypes)
# torch.save(sub_graph, self.data_cat_path + name + '_' + mode + '_' + str(time_point))
joblib.dump(sub_graph, self.data_cat_path + name + '_' + mode + '_' + str(time_point) + '.job')
def load_graphs(self, graph_name='graph_sample_feature', time_length=10, phases=('train', 'val', 'test')):
print(graph_name)
train_time, val_time, test_time = self.time
print(self.time, time_length)
phase_dict = {
'train': list(range(train_time - (time_length - 1), train_time + 1)),
'val': list(range(val_time - (time_length - 1), val_time + 1)),
'test': list(range(test_time - (time_length - 1), test_time + 1))
}
phase_dict = dict(filter(lambda x: x[0] in phases, phase_dict.items()))
print(phase_dict)
# train_list = list(range(train_time - 9, train_time + 1))
# val_list = list(range(val_time - 9, val_time + 1))
# test_list = list(range(test_time - 9, test_time + 1))
# all_time = set(phase_dict['train'] + phase_dict['val'] + phase_dict['test'])
all_time = []
for phase in phases:
all_time += phase_dict[phase]
all_time = set(all_time)
graphs = {}
for time in all_time:
# graphs[time] = torch.load(self.data_cat_path + graph_name + '_' + str(time))
graphs[time] = joblib.load(self.data_cat_path + graph_name + '_' + str(time) + '.job')
data_dict = {phase: [graphs[time] for time in phase_dict[phase]] for phase in phase_dict}
self.graph = {
'data': data_dict,
'node_trans': json.load(open(self.data_cat_path + 'sample_node_trans.json', 'r')),
'time': {'train': train_time, 'val': val_time, 'test': test_time},
'all_graphs': graphs,
'time_length': time_length
}
return self.graph
def get_time_dict(self):
train_time, val_time, test_time = self.time
return {'train': train_time, 'val': val_time, 'test': test_time}
def values_pipeline(self, values):
# inputs = values[0]
# outputs = np.array(values[1])
# inputs = list(filter(lambda x: x >= 0, inputs))
# valid_len = len(inputs)
# inputs = np.array(inputs + [0] * (len(outputs) - valid_len))
# inputs = np.stack([inputs, outputs], axis=0)
# if self.norm:
# inputs = (inputs - self.mean) / self.std
# return inputs, valid_len
return values
class CascadeDataProcessor(DataProcessor):
def __init__(self, data_source, structure='individual', max_time=10, max_len=256, seed=123, norm=False, log=False,
time=None, model_config=None):
super(CascadeDataProcessor, self).__init__(data_source, max_len, seed, norm, log, time, model_config)
self.structure = structure
self.max_time = max_time
def get_cascade_graph(self, name='graph_sample_feature', mode='vector',
all_times=None, structure='individual', time_length=10):
cur_start_time = datetime.datetime.now()
phases = ['train', 'val', 'test']
split_data = torch.load(self.data_cat_path + 'split_data')
paper_trans = json.load(open(self.data_cat_path + 'sample_node_trans.json', 'r'))['paper']
paper_reverse_trans = dict(zip(paper_trans.values(), paper_trans.keys()))
total_count = 0
times = {}
for i in range(len(phases)):
times[phases[i]] = all_times[i]
print(times)
if structure == 'individual':
global_fw = open(self.data_cat_path + 'global_graph.txt', 'w+')
global_graph = torch.load(self.data_cat_path + name + '_' + mode + '_' + str(times['train'] -
(time_length // 2)))
global_oids = global_graph.nodes['paper'].data[dgl.NID].numpy().tolist()
global_author_oids = global_graph.nodes['author'].data[dgl.NID].numpy().tolist()
paper_src, author_dst = global_graph.edges(form='uv', etype='is writen by', order='srcdst')
paper_src = [global_oids[x] for x in paper_src.numpy().tolist()]
author_dst = [global_author_oids[x] for x in author_dst.numpy().tolist()]
paper_author_dict = get_edge_dict(paper_src, author_dst)
srcs, dsts = global_graph.edges(form='uv', etype='is cited by', order='srcdst')
srcs = [global_oids[x] for x in srcs.numpy().tolist()]
dsts = [global_oids[x] for x in dsts.numpy().tolist()]
author_edges = defaultdict(int)
all_authors = set(srcs + dsts)
for src, dst in zip(srcs, dsts):
src_authors = paper_author_dict[src]
dst_authors = paper_author_dict[dst]
for src_author in src_authors:
for dst_author in dst_authors:
if src_author != dst_author:
author_edges[(src_author, dst_author)] += 1
# print(dict(filter(lambda x: x[1] > 1, author_edges.items())))
for node in all_authors:
edges = ['{}:{}'.format(key[1], author_edges[key]) for key in
list(filter(lambda x: x[0] == node, author_edges.keys()))]
if edges:
line = str(node) + '\t\t' + '\t'.join(edges) + '\n'
else:
line = str(node) + '\t\t' + 'null' + '\n'
global_fw.write(line)
phase_dict = defaultdict(int)
group_dict = dict()
for phase in phases:
cur_graph = dgl.remove_self_loop(
torch.load(self.data_cat_path + name + '_' + mode + '_' + str(times[phase])),
etype='is cited by')
cur_graph = dgl.node_type_subgraph(cur_graph, ntypes=['paper', 'author', 'journal'])
# order alignment
temp_papers = [paper_trans[paper] for paper in split_data[phase][0]]
original_ids = cur_graph.nodes['paper'].data[dgl.NID].numpy().tolist()
oid_cid_trans = dict(zip(original_ids, cur_graph.nodes('paper').numpy().tolist()))
author_oids = cur_graph.nodes['author'].data[dgl.NID].numpy().tolist()
# print(temp_starter)
fw = open(self.data_cat_path + 'cascade_{}_{}.txt'.format(structure, phase), 'w+')
paper_src, author_dst = cur_graph.edges(form='uv', etype='is writen by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
author_dst = [author_oids[x] for x in author_dst.numpy().tolist()]
paper_author_dict = get_edge_dict(paper_src, author_dst)
print('--paper_author_dict:', datetime.datetime.now() - cur_start_time, '--')
if structure == 'individual':
paper_src, paper_dst = cur_graph.edges(form='uv', etype='is cited by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
cite_edge_dict = get_edge_dict(paper_src, paper_dst)
for paper in temp_papers:
# author as node
paper_dict = defaultdict(int)
cur_authors = paper_author_dict[paper]
# print(cur_authors)
cur_edges = cite_edge_dict[paper]
all_nodes = cur_authors.copy()
for cite_paper in cur_edges:
dsts = paper_author_dict[cite_paper]
all_nodes.extend(dsts)
for dst in dsts:
# print(cur_authors)
for src in cur_authors:
if src != dst:
paper_dict[(src, dst)] += 1
cur_authors = [str(x) for x in cur_authors]
edges_list = ['{}:{}:{}'.format(key[0], key[1], paper_dict[key]) for key in paper_dict]
line = str('p' + paper_reverse_trans[paper]) + '\t' + ' '.join(cur_authors) + '\t' + str(
times[phase]) + '\t' + \
str(len(set(all_nodes))) + '\t' + ' '.join(edges_list) + '\n'
fw.write(line)
# total_count += 1
elif structure == 'group':
paper_src, paper_dst = cur_graph.edges(form='uv', etype='is cited by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
# cite_time = cur_graph.edges['is cited by'].data['time'][:, 0].numpy().tolist()
paper_time = cur_graph.nodes['paper'].data['time'][:, 0].numpy().tolist()
# cite_edge_dict = get_edge_dict(paper_src, paper_dst, cite_time)
cite_edge_dict = get_edge_dict(paper_src, paper_dst)
# group_dict = dict()
# paper_graph = dgl.edge_type_subgraph(cur_graph, ['is cited by'])
# nx_paper_graph = dgl.to_networkx(paper_graph, node_attrs=['time', '_ID'], edge_attrs=['time'])
group_count = 0
for paper in temp_papers:
# author group as node
paper_dict = defaultdict(int)
cur_authors = sorted(paper_author_dict[paper])
# cur_authors.sort()
cur_authors = str(cur_authors)
if cur_authors in group_dict:
cur_authors = group_dict[cur_authors]
else:
group_dict[cur_authors] = group_count
cur_authors = group_count
group_count += 1
# cur_edges = cite_edge_dict[paper]
all_nodes = []
# print('cur edges', cur_edges)
# shortest_paths = get_citation_cascade(cur_graph, original_ids.index(paper),
# [original_ids.index(paper)] +
# [original_ids.index(node) for node, _ in cite_edge_dict[paper]])
shortest_paths = get_citation_cascade(cur_graph, oid_cid_trans[paper],
[oid_cid_trans[node] for node in cite_edge_dict[paper] if
node != paper])
# shortest_paths = get_citation_cascade(cur_graph, oid_cid_trans[paper],
# [node for node in nx_paper_graph[oid_cid_trans[paper]]])
for path in shortest_paths:
# print('path', path)
cur_cite_time = paper_time[path[-1]]
path = [original_ids[node] for node in path]
groups = [str(sorted(paper_author_dict[paper])) for paper in path]
trans_groups = []
for group in groups:
if group in group_dict:
group = group_dict[group]
else:
group_dict[group] = group_count
group = group_count
group_count += 1
trans_groups.append(group)
all_nodes.append(trans_groups[-1])
paper_dict[tuple(trans_groups)] = cur_cite_time
path = sorted(paper_dict.items(), key=lambda x: x[1])
path = [','.join([str(node) for node in nodes]) + ':' + str(time) for nodes, time in path]
line = str('p' + paper_reverse_trans[paper]) + '\t' + str(cur_authors) + '\t' + str(
times[phase]) + '\t' + \
str(len(set(all_nodes))) + '\t' + ' '.join(path) + '\n'
fw.write(line)
json.dump(group_dict, open(self.data_cat_path + 'cascade_group_dict.json', 'w+'))
print('--phase:', datetime.datetime.now() - cur_start_time, '--')
elif structure == 'paper':
paper_src, paper_dst = cur_graph.edges(form='uv', etype='is cited by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
# cite_time = cur_graph.edges['is cited by'].data['time'][:, 0].numpy().tolist()
paper_time = cur_graph.nodes['paper'].data['time'][:, 0].numpy().tolist()
# cite_edge_dict = get_edge_dict(paper_src, paper_dst, cite_time)
cite_edge_dict = get_edge_dict(paper_src, paper_dst)
# group_dict = dict()
# paper_graph = dgl.edge_type_subgraph(cur_graph, ['is cited by'])
# nx_paper_graph = dgl.to_networkx(paper_graph, node_attrs=['time', '_ID'], edge_attrs=['time'])
group_count = 0
for paper in temp_papers:
# author group as node
paper_dict = defaultdict(int)
all_nodes = []
# print('cur edges', cur_edges)
# shortest_paths = get_citation_cascade(cur_graph, original_ids.index(paper),
# [original_ids.index(paper)] +
# [original_ids.index(node) for node, _ in cite_edge_dict[paper]])
shortest_paths = get_citation_cascade(cur_graph, oid_cid_trans[paper],
[oid_cid_trans[node] for node in cite_edge_dict[paper] if
node != paper])
# shortest_paths = get_citation_cascade(cur_graph, oid_cid_trans[paper],
# [node for node in nx_paper_graph[oid_cid_trans[paper]]])
for path in shortest_paths:
# print('path', path)
cur_cite_time = paper_time[path[-1]]
path = [original_ids[node] for node in path]
# groups = [str(sorted(paper_author_dict[paper])) for paper in path]
# trans_groups = []
# for group in groups:
# if group in group_dict:
# group = group_dict[group]
# else:
# group_dict[group] = group_count
# group = group_count
# group_count += 1
# trans_groups.append(group)
all_nodes.append(path[-1])
paper_dict[tuple(path)] = cur_cite_time
path = sorted(paper_dict.items(), key=lambda x: x[1])
path = [','.join([str(node) for node in nodes]) + ':' + str(time) for nodes, time in path]
line = str(paper_reverse_trans[paper]) + '\t' + str(paper) + '\t' + str(
times[phase]) + '\t' + \
str(len(set(all_nodes))) + '\t' + ' '.join(path) + '\n'
fw.write(line)
# json.dump(group_dict, open(self.data_cat_path + 'cascade_group_dict.json', 'w+'))
print('--phase:', datetime.datetime.now() - cur_start_time, '--')
elif structure == 'hdgnn':
# p_p, p_a, a_p, p_v, v_p
dir_path = self.data_cat_path + 'hdgnn/'
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
# paper citation
paper_src, paper_dst = cur_graph.edges(form='uv', etype='is cited by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
# paper_src = [x for x in paper_src.numpy().tolist()]
# paper_dst = [x for x in paper_dst.numpy().tolist()]
get_simple_graph(dir_path + 'p_p_citation_list_{}.txt'.format(phase), paper_src, paper_dst)
# paper, authors
paper_src, author_dst = cur_graph.edges(form='uv', etype='is writen by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
author_dst = [author_oids[x] for x in author_dst.numpy().tolist()]
# paper_src = [x for x in paper_src.numpy().tolist()]
# author_dst = [x for x in author_dst.numpy().tolist()]
get_simple_graph(dir_path + 'p_a_list_{}.txt'.format(phase), paper_src, author_dst)
author_src, paper_dst = cur_graph.edges(form='uv', etype='writes', order='srcdst')
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
author_src = [author_oids[x] for x in author_src.numpy().tolist()]
# paper_dst = [x for x in paper_dst.numpy().tolist()]
# author_src = [x for x in author_src.numpy().tolist()]
get_simple_graph(dir_path + 'a_p_list_{}.txt'.format(phase), author_src, paper_dst)
# paper, venues
venue_oids = cur_graph.nodes['journal'].data[dgl.NID].numpy().tolist()
paper_src, venue_dst = cur_graph.edges(form='uv', etype='is published by', order='srcdst')
paper_src = [original_ids[x] for x in paper_src.numpy().tolist()]
venue_dst = [venue_oids[x] for x in venue_dst.numpy().tolist()]
# paper_src = [x for x in paper_src.numpy().tolist()]
# venue_dst = [x for x in venue_dst.numpy().tolist()]
get_simple_graph(dir_path + 'p_v_{}.txt'.format(phase), paper_src, venue_dst)
venue_src, paper_dst = cur_graph.edges(form='uv', etype='publishes', order='srcdst')
# print(cur_graph)
paper_dst = [original_ids[x] for x in paper_dst.numpy().tolist()]
venue_src = [venue_oids[x] for x in venue_src.numpy().tolist()]
# paper_dst = [x for x in paper_dst.numpy().tolist()]
# venue_src = [x for x in venue_src.numpy().tolist()]
get_simple_graph(dir_path + 'v_p_list_{}.txt'.format(phase), venue_src, paper_dst)
final_graph = torch.load(self.data_cat_path + 'graph_sample_feature_vector_2015')
paper_embeds = final_graph.nodes['paper'].data['h'].numpy()
print(paper_embeds.shape)
pkl.dump(paper_embeds, open(dir_path + 'aps_title_emb.pkl', 'wb'))
def split_labeled_data(self, name='graph_sample_feature', all_times=None, time_length=10):
phases = ['train', 'val', 'test']
times = {}
for i in range(len(phases)):
times[phases[i]] = all_times[i]
print(times)
for phase in phases:
with open(self.data_cat_path + 'cascade_{}_{}.txt'.format(self.structure, phase), 'r') as fr:
cur_data = [line.strip().split('\t') for line in fr]
if phase == 'train':
labeled_data = []
unlabeled_data = []
for data in cur_data:
paper = data[0]