-
Notifications
You must be signed in to change notification settings - Fork 147
/
LinkPredictionDataset.py
2611 lines (2098 loc) · 107 KB
/
LinkPredictionDataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os.path
import dgl
import math
import re
from copy import deepcopy
import numpy as np
import torch as th
import itertools
import random
from random import shuffle, choice
from collections import Counter
from os.path import join as joinpath
from os.path import isfile
from dgl.data.knowledge_graph import load_data
from . import BaseDataset, register_dataset
from . import AcademicDataset, HGBDataset, OHGBDataset, NBF_Dataset
from ..utils import add_reverse_edges
from collections import defaultdict
import os
from scipy.sparse import csr_matrix
__all__ = ['LinkPredictionDataset', 'HGB_LinkPrediction']
@register_dataset('link_prediction')
class LinkPredictionDataset(BaseDataset):
"""
metric: Accuracy, multi-label f1 or multi-class f1. Default: `accuracy`
"""
def __init__(self, *args, **kwargs):
super(LinkPredictionDataset, self).__init__(*args, **kwargs)
self.target_link = None
self.target_link_r = None
def get_split(self, val_ratio=0.1, test_ratio=0.2):
"""
Get subgraphs for train, valid and test.
Generally, the original will have train_mask and test_mask in edata, or we will split it automatically.
If the original graph do not has the train_mask in edata, we default that there is no valid_mask and test_mask.
So we will split the edges of the original graph into train/valid/test 0.7/0.1/0.2.
The dataset has not validation_mask, so we split train edges randomly.
Parameters
----------
val_ratio : int
The ratio of validation. Default: 0.1
test_ratio : int
The ratio of test. Default: 0.2
Returns
-------
train_hg
"""
val_edge_dict = {}
test_edge_dict = {}
out_ntypes = []
train_graph = self.g
for i, etype in enumerate(self.target_link):
num_edges = self.g.num_edges(etype)
if 'train_mask' not in self.g.edges[etype].data:
"""
split edges into train/valid/test.
"""
random_int = th.randperm(num_edges)
val_index = random_int[:int(num_edges * val_ratio)]
val_edge = self.g.find_edges(val_index, etype)
test_index = random_int[int(num_edges * val_ratio):int(num_edges * (test_ratio + val_ratio))]
test_edge = self.g.find_edges(test_index, etype)
val_edge_dict[etype] = val_edge
test_edge_dict[etype] = test_edge
out_ntypes.append(etype[0])
out_ntypes.append(etype[2])
train_graph = dgl.remove_edges(train_graph, th.cat((val_index, test_index)), etype)
# train_graph = dgl.remove_edges(train_graph, val_index, etype)
if self.target_link_r is None:
pass
else:
reverse_edge = self.target_link_r[i]
train_graph = dgl.remove_edges(train_graph, th.arange(train_graph.num_edges(reverse_edge)),
reverse_edge)
edges = train_graph.edges(etype=etype)
train_graph = dgl.add_edges(train_graph, edges[1], edges[0], etype=reverse_edge)
else:
if 'valid_mask' not in self.g.edges[etype].data:
train_idx = self.g.edges[etype].data['train_mask']
random_int = th.randperm(int(train_idx.sum( )))
val_index = random_int[:int(train_idx.sum( ) * val_ratio)]
val_edge = self.g.find_edges(val_index, etype)
else:
val_mask = self.g.edges[etype].data['valid_mask'].squeeze( )
val_index = th.nonzero(val_mask).squeeze( )
val_edge = self.g.find_edges(val_index, etype)
test_mask = self.g.edges[etype].data['test_mask'].squeeze( )
test_index = th.nonzero(test_mask).squeeze( )
test_edge = self.g.find_edges(test_index, etype)
val_edge_dict[etype] = val_edge
test_edge_dict[etype] = test_edge
out_ntypes.append(etype[0])
out_ntypes.append(etype[2])
# self.val_label = train_graph.edges[etype[1]].data['label'][val_index]
self.test_label = train_graph.edges[etype[1]].data['label'][test_index]
train_graph = dgl.remove_edges(train_graph, th.cat((val_index, test_index)), etype)
# train_graph = dgl.remove_edges(train_graph, th.cat((val_index, test_index)), 'item-user')
self.out_ntypes = set(out_ntypes)
val_graph = dgl.heterograph(val_edge_dict,
{ntype: self.g.number_of_nodes(ntype) for ntype in set(out_ntypes)})
test_graph = dgl.heterograph(test_edge_dict,
{ntype: self.g.number_of_nodes(ntype) for ntype in set(out_ntypes)})
# todo: val/test negative graphs should be created before training rather than
# create them dynamically in every evaluation.
return train_graph, val_graph, test_graph, None, None
@register_dataset('demo_link_prediction')
class Test_LinkPrediction(LinkPredictionDataset):
def __init__(self, dataset_name):
super(Test_LinkPrediction, self).__init__( )
self.g = self.load_HIN('./openhgnn/debug/data.bin')
self.target_link = 'user-item'
self.has_feature = False
self.meta_paths_dict = None
self.preprocess( )
# self.generate_negative()
def preprocess(self):
test_mask = self.g.edges[self.target_link].data['test_mask']
index = th.nonzero(test_mask).squeeze( )
self.test_edge = self.g.find_edges(index, self.target_link)
self.pos_test_graph = dgl.heterograph({('user', 'user-item', 'item'): self.test_edge},
{ntype: self.g.number_of_nodes(ntype) for ntype in ['user', 'item']})
self.g.remove_edges(index, self.target_link)
self.g.remove_edges(index, 'item-user')
self.neg_test_graph, _ = dgl.load_graphs('./openhgnn/debug/neg.bin')
self.neg_test_graph = self.neg_test_graph[0]
return
def generate_negative(self):
k = 99
e = self.pos_test_graph.edges( )
neg_src = []
neg_dst = []
for i in range(self.pos_test_graph.number_of_edges( )):
src = e[0][i]
exp = self.pos_test_graph.successors(src)
dst = th.randint(high=self.g.number_of_nodes('item'), size=(k,))
for d in range(len(dst)):
while dst[d] in exp:
dst[d] = th.randint(high=self.g.number_of_nodes('item'), size=(1,))
src = src.repeat_interleave(k)
neg_src.append(src)
neg_dst.append(dst)
neg_edge = (th.cat(neg_src), th.cat(neg_dst))
neg_graph = dgl.heterograph({('user', 'user-item', 'item'): neg_edge},
{ntype: self.g.number_of_nodes(ntype) for ntype in ['user', 'item']})
dgl.save_graphs('./openhgnn/debug/neg.bin', neg_graph)
@register_dataset('hin_link_prediction')
class HIN_LinkPrediction(LinkPredictionDataset):
def __init__(self, dataset_name, *args, **kwargs):
super(HIN_LinkPrediction, self).__init__(*args, **kwargs)
self.g = self.load_HIN(dataset_name)
def load_link_pred(self, path):
u_list = []
v_list = []
label_list = []
with open(path) as f:
for i in f.readlines( ):
u, v, label = i.strip( ).split(', ')
u_list.append(int(u))
v_list.append(int(v))
label_list.append(int(label))
return u_list, v_list, label_list
def load_HIN(self, dataset_name):
self.dataset_name = dataset_name
if dataset_name == 'academic4HetGNN':
# which is used in HetGNN
dataset = AcademicDataset(name='academic4HetGNN', raw_dir='')
g = dataset[0].long( )
self.train_batch = self.load_link_pred('./openhgnn/dataset/' + dataset_name + '/a_a_list_train.txt')
self.test_batch = self.load_link_pred('./openhgnn/dataset/' + dataset_name + '/a_a_list_test.txt')
self.category = 'author'
elif dataset_name == 'Book-Crossing':
g, _ = dgl.load_graphs('./openhgnn/dataset/book_graph.bin')
g = g[0]
self.target_link = [('user', 'user-item', 'item')]
self.node_type = ['user', 'item']
elif dataset_name == 'amazon4SLICE':
dataset = AcademicDataset(name='amazon4SLICE', raw_dir='')
g = dataset[0].long( )
# self.target_link = [('product', 'product-1-product', 'product'),
# ('product', 'product-2-product', 'product')]
self.target_link = [('product', 'product-1-product', 'product')]
elif dataset_name == 'MTWM':
dataset = AcademicDataset(name='MTWM', raw_dir='')
g = dataset[0].long( )
g = add_reverse_edges(g)
self.target_link = [('user', 'user-buy-spu', 'spu')]
self.target_link_r = [('spu', 'user-buy-spu-rev', 'user')]
self.meta_paths_dict = {
'UPU1': [('user', 'user-buy-poi', 'poi'), ('poi', 'user-buy-poi-rev', 'user')],
'UPU2': [('user', 'user-click-poi', 'poi'), ('poi', 'user-click-poi-rev', 'user')],
'USU': [('user', 'user-buy-spu', 'spu'), ('spu', 'user-buy-spu-rev', 'user')],
'UPSPU1': [('user', 'user-buy-poi', 'poi'), ('poi', 'poi-contain-spu', 'spu'),
('spu', 'poi-contain-spu-rev', 'poi'), ('poi', 'user-buy-poi-rev', 'user')
],
'UPSPU2': [
('user', 'user-click-poi', 'poi'), ('poi', 'poi-contain-spu', 'spu'),
('spu', 'poi-contain-spu-rev', 'poi'), ('poi', 'user-click-poi-rev', 'user')
]
}
self.node_type = ['user', 'spu']
elif dataset_name == 'HGBl-ACM':
dataset = HGBDataset(name='HGBn-ACM', raw_dir='')
g = dataset[0].long( )
self.has_feature = True
self.target_link = [('paper', 'paper-ref-paper', 'paper')]
self.node_type = ['author', 'paper', 'subject', 'term']
self.target_link_r = [('paper', 'paper-cite-paper', 'paper')]
self.meta_paths_dict = {'PAP': [('paper', 'paper-author', 'author'), ('author', 'author-paper', 'paper')],
'PSP': [('paper', 'paper-subject', 'subject'),
('subject', 'subject-paper', 'paper')],
'PcPAP': [('paper', 'paper-cite-paper', 'paper'),
('paper', 'paper-author', 'author'),
('author', 'author-paper', 'paper')],
'PcPSP': [('paper', 'paper-cite-paper', 'paper'),
('paper', 'paper-subject', 'subject'),
('subject', 'subject-paper', 'paper')],
'PrPAP': [('paper', 'paper-ref-paper', 'paper'),
('paper', 'paper-author', 'author'),
('author', 'author-paper', 'paper')],
'PrPSP': [('paper', 'paper-ref-paper', 'paper'),
('paper', 'paper-subject', 'subject'),
('subject', 'subject-paper', 'paper')]
}
elif dataset_name == 'HGBl-DBLP':
dataset = HGBDataset(name='HGBn-DBLP', raw_dir='')
g = dataset[0].long( )
self.has_feature = True
self.target_link = [('author', 'author-paper', 'paper')]
self.node_type = ['author', 'paper', 'venue', 'term']
self.target_link_r = [('paper', 'paper-author', 'author')]
self.meta_paths_dict = {'APA': [('author', 'author-paper', 'paper'), ('paper', 'paper-author', 'author')],
'APTPA': [('author', 'author-paper', 'paper'), ('paper', 'paper-term', 'term'),
('term', 'term-paper', 'paper'), ('paper', 'paper-author', 'author')],
'APVPA': [('author', 'author-paper', 'paper'), ('paper', 'paper-venue', 'venue'),
('venue', 'venue-paper', 'paper'), ('paper', 'paper-author', 'author')],
'PAP': [('paper', 'paper-author', 'author'), ('author', 'author-paper', 'paper')],
'PTP': [('paper', 'paper-term', 'term'), ('term', 'term-paper', 'paper')],
'PVP': [('paper', 'paper-venue', 'venue'), ('venue', 'venue-paper', 'paper')],
}
elif dataset_name == 'HGBl-IMDB':
dataset = HGBDataset(name='HGBn-IMDB', raw_dir='')
g = dataset[0].long( )
self.has_feature = True
# self.target_link = [('author', 'author-paper', 'paper')]
# self.node_type = ['author', 'paper', 'subject', 'term']
# self.target_link_r = [('paper', 'paper-author', 'author')]
self.target_link = [('actor', 'actor->movie', 'movie')]
self.node_type = ['actor', 'director', 'keyword', 'movie']
self.target_link_r = [('movie', 'movie->actor', 'actor')]
self.meta_paths_dict = {
'MAM': [('movie', 'movie->actor', 'actor'), ('actor', 'actor->movie', 'movie')],
'MDM': [('movie', 'movie->director', 'director'), ('director', 'director->movie', 'movie')],
'MKM': [('movie', 'movie->keyword', 'keyword'), ('keyword', 'keyword->movie', 'movie')],
# 'DMD': [('director', 'director->movie', 'movie'), ('movie', 'movie->director', 'director')],
# 'DMAMD': [('director', 'director->movie', 'movie'), ('movie', 'movie->actor', 'actor'),
# ('actor', 'actor->movie', 'movie'), ('movie', 'movie->director', 'director')],
'AMA': [('actor', 'actor->movie', 'movie'), ('movie', 'movie->actor', 'actor')],
'AMDMA': [('actor', 'actor->movie', 'movie'), ('movie', 'movie->director', 'director'),
('director', 'director->movie', 'movie'), ('movie', 'movie->actor', 'actor')]
}
return g
def get_split(self, val_ratio=0.1, test_ratio=0.2):
if self.dataset_name == 'academic4HetGNN':
return None, None, None, None, None
else:
return super(HIN_LinkPrediction, self).get_split(val_ratio, test_ratio)
@register_dataset('HGBl_link_prediction')
class HGB_LinkPrediction(LinkPredictionDataset):
r"""
The HGB dataset will be used in task *link prediction*.
Dataset Name :
HGBn-amazon/HGBn-LastFM/HGBn-PubMed
So if you want to get more information, refer to
`HGB datasets <https://github.com/THUDM/HGB>`_
Attributes
-----------
has_feature : bool
Whether the dataset has feature. Except HGBl-LastFM, others have features.
target_link : list of tuple[canonical_etypes]
The etypes of test link. HGBl-amazon has two etypes of test link. other has only one.
"""
def __init__(self, dataset_name, *args, **kwargs):
super(HGB_LinkPrediction, self).__init__(*args, **kwargs)
self.dataset_name = dataset_name
self.target_link_r = None
if dataset_name == 'HGBl-amazon':
dataset = HGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.has_feature = False
self.target_link = [('product', 'product-product-0', 'product'),
('product', 'product-product-1', 'product')]
self.target_link_r = None
self.link = [0, 1]
self.node_type = ["product"]
self.test_edge_type = {'product-product-0': 0, 'product-product-1': 1}
self.meta_paths_dict = {
'P0P': [('product', 'product-product-0', 'product'), ('product', 'product-product-1', 'product')],
'P1P': [('product', 'product-product-1', 'product'), ('product', 'product-product-0', 'product')]
}
elif dataset_name == 'HGBl-LastFM':
dataset = HGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.has_feature = False
self.target_link = [('user', 'user-artist', 'artist')]
self.node_type = ['user', 'artist', 'tag']
self.test_edge_type = {'user-artist': 0}
g = add_reverse_edges(g)
self.target_link_r = [('artist', 'user-artist-rev', 'user')]
self.meta_paths_dict = {'UU': [('user', 'user-user', 'user')],
'UAU': [('user', 'user-artist', 'artist'), ('artist', 'user-artist-rev', 'user')],
'UATAU': [('user', 'user-artist', 'artist'), ('artist', 'artist-tag', 'tag'),
('tag', 'artist-tag-rev', 'artist'),
('artist', 'user-artist-rev', 'user')],
'AUA': [('artist', 'user-artist-rev', 'user'), ('user', 'user-artist', 'artist')],
'ATA': [('artist', 'artist-tag', 'tag'), ('tag', 'artist-tag-rev', 'artist')]
}
elif dataset_name == 'HGBl-PubMed':
dataset = HGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.has_feature = True
self.target_link = [('1', '1_to_1', '1')]
self.node_type = ['0', '1', '2', '3']
self.test_edge_type = {'1_to_1': 2}
g = add_reverse_edges(g)
self.target_link_r = [('1', '1_to_1-rev', '1')]
self.meta_paths_dict = {'101': [('1', '0_to_1-rev', '0'), ('0', '0_to_1', '1')],
'111': [('1', '1_to_1', '1'), ('1', '1_to_1-rev', '1')],
'121': [('1', '2_to_1-rev', '2'), ('2', '2_to_1', '1')],
'131': [('1', '3_to_1-rev', '3'), ('3', '3_to_1', '1')]
}
self.g = g
self.shift_dict = self.calculate_node_shift( )
def load_link_pred(self, path):
return
def calculate_node_shift(self):
node_shift_dict = {}
count = 0
for type in self.node_type:
node_shift_dict[type] = count
count += self.g.num_nodes(type)
return node_shift_dict
def get_split(self):
r"""
Get graphs for train, valid or test.
The dataset has not validation_mask, so we split train edges randomly.
"""
val_edge_dict = {}
test_edge_dict = {}
out_ntypes = []
train_graph = self.g
val_ratio = 0.1
for i, etype in enumerate(self.target_link):
train_mask = self.g.edges[etype].data['train_mask'].squeeze( )
train_index = th.nonzero(train_mask).squeeze( )
random_int = th.randperm(len(train_index))[:int(len(train_index) * val_ratio)]
val_index = train_index[random_int]
val_edge = self.g.find_edges(val_index, etype)
test_mask = self.g.edges[etype].data['test_mask'].squeeze( )
test_index = th.nonzero(test_mask).squeeze( )
test_edge = self.g.find_edges(test_index, etype)
val_edge_dict[etype] = val_edge
test_edge_dict[etype] = test_edge
out_ntypes.append(etype[0])
out_ntypes.append(etype[2])
train_graph = dgl.remove_edges(train_graph, th.cat((val_index, test_index)), etype)
if self.target_link_r is None:
pass
else:
train_graph = dgl.remove_edges(train_graph, th.cat((val_index, test_index)), self.target_link_r[i])
self.out_ntypes = set(out_ntypes)
val_graph = dgl.heterograph(val_edge_dict,
{ntype: self.g.number_of_nodes(ntype) for ntype in set(out_ntypes)})
test_graph = dgl.heterograph(test_edge_dict,
{ntype: self.g.number_of_nodes(ntype) for ntype in set(out_ntypes)})
return train_graph, val_graph, test_graph, None, None
def save_results(self, hg, score, file_path):
with hg.local_scope( ):
src_list = []
dst_list = []
edge_type_list = []
for etype in hg.canonical_etypes:
edges = hg.edges(etype=etype)
src_id = edges[0] + self.shift_dict[etype[0]]
dst_id = edges[1] + self.shift_dict[etype[2]]
src_list.append(src_id)
dst_list.append(dst_id)
edge_type_list.append(th.full((src_id.shape[0],), self.test_edge_type[etype[1]]))
src_list = th.cat(src_list)
dst_list = th.cat(dst_list)
edge_type_list = th.cat(edge_type_list)
with open(file_path, "w") as f:
for l, r, edge_type, c in zip(src_list, dst_list, edge_type_list, score):
f.write(f"{l}\t{r}\t{edge_type}\t{round(float(c), 4)}\n")
@register_dataset('ohgb_link_prediction')
class OHGB_LinkPrediction(LinkPredictionDataset):
def __init__(self, dataset_name, *args, **kwargs):
super(OHGB_LinkPrediction, self).__init__(*args, **kwargs)
self.dataset_name = dataset_name
self.has_feature = True
if dataset_name == 'ohgbl-MTWM':
dataset = OHGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.target_link = [('user', 'user-buy-spu', 'spu')]
self.target_link_r = [('spu', 'user-buy-spu-rev', 'user')]
self.node_type = ['user', 'spu']
elif dataset_name == 'ohgbl-yelp1':
dataset = OHGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.target_link = [('user', 'user-buy-business', 'business')]
self.target_link_r = [('business', 'user-buy-business-rev', 'user')]
elif dataset_name == 'ohgbl-yelp2':
dataset = OHGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.target_link = [('business', 'described-with', 'phrase')]
self.target_link_r = [('business', 'described-with-rev', 'phrase')]
elif dataset_name == 'ohgbl-Freebase':
dataset = OHGBDataset(name=dataset_name, raw_dir='')
g = dataset[0].long( )
self.target_link = [('BOOK', 'BOOK-and-BOOK', 'BOOK')]
self.target_link_r = [('BOOK', 'BOOK-and-BOOK-rev', 'BOOK')]
self.g = g
def build_graph_from_triplets(num_nodes, num_rels, triplets):
""" Create a DGL graph. The graph is bidirectional because RGCN authors
use reversed relations.
This function also generates edge type and normalization factor
(reciprocal of node incoming degree)
"""
g = dgl.graph(([], []))
g.add_nodes(num_nodes)
src, rel, dst = triplets
src, dst = np.concatenate((src, dst)), np.concatenate((dst, src))
rel = np.concatenate((rel, rel + num_rels))
edges = sorted(zip(dst, src, rel))
dst, src, rel = np.array(edges).transpose( )
g.add_edges(src, dst)
norm = comp_deg_norm(g)
print("# nodes: {}, # edges: {}".format(num_nodes, len(src)))
return g, rel.astype('int64'), norm.astype('int64')
def comp_deg_norm(g):
g = g.local_var( )
in_deg = g.in_degrees(range(g.number_of_nodes( ))).float( ).numpy( )
norm = 1.0 / in_deg
norm[np.isinf(norm)] = 0
return norm
@register_dataset('kg_sub_link_prediction')
class KG_RedDataset(LinkPredictionDataset):
def __init__(self, dataset_name, *args, **kwargs):
super(KG_RedDataset, self).__init__(*args, **kwargs)
self.trans_dir = os.path.join('openhgnn/dataset/data', dataset_name)
self.ind_dir = self.trans_dir + '_ind'
folder = os.path.exists(self.trans_dir)
if not folder:
os.makedirs(self.trans_dir)
url = "https://s3.cn-north-1.amazonaws.com.cn/dgl-data/dataset/openhgnn/fb237_v1.zip"
response = requests.get(url)
with zipfile.ZipFile(io.BytesIO(response.content)) as myzip:
myzip.extractall(self.trans_dir)
print("--- download data ---")
else:
print("--- There is data! ---")
folder = os.path.exists(self.ind_dir)
if not folder:
os.makedirs(self.ind_dir)
# 下载数据
url = "https://s3.cn-north-1.amazonaws.com.cn/dgl-data/dataset/openhgnn/fb237_v1_ind.zip"
response = requests.get(url)
with zipfile.ZipFile(io.BytesIO(response.content)) as myzip:
myzip.extractall(self.ind_dir)
print("--- download data ---")
else:
print("--- There is data! ---")
with open(os.path.join(self.trans_dir, 'entities.txt')) as f:
self.entity2id = dict()
for line in f:
entity, eid = line.strip().split()
self.entity2id[entity] = int(eid)
with open(os.path.join(self.trans_dir, 'relations.txt')) as f:
self.relation2id = dict()
id2relation = []
for line in f:
relation, rid = line.strip().split()
self.relation2id[relation] = int(rid)
id2relation.append(relation)
with open(os.path.join(self.ind_dir, 'entities.txt')) as f:
self.entity2id_ind = dict()
for line in f:
entity, eid = line.strip().split()
self.entity2id_ind[entity] = int(eid)
for i in range(len(self.relation2id)):
id2relation.append(id2relation[i] + '_inv')
id2relation.append('idd')
self.id2relation = id2relation
self.n_ent = len(self.entity2id)
self.n_rel = len(self.relation2id)
self.n_ent_ind = len(self.entity2id_ind)
self.tra_train = self.read_triples(self.trans_dir, 'train.txt')
self.tra_valid = self.read_triples(self.trans_dir, 'valid.txt')
self.tra_test = self.read_triples(self.trans_dir, 'test.txt')
self.ind_train = self.read_triples(self.ind_dir, 'train.txt', 'inductive')
self.ind_valid = self.read_triples(self.ind_dir, 'valid.txt', 'inductive')
self.ind_test = self.read_triples(self.ind_dir, 'test.txt', 'inductive')
self.val_filters = self.get_filter('valid')
self.tst_filters = self.get_filter('test')
for filt in self.val_filters:
self.val_filters[filt] = list(self.val_filters[filt])
for filt in self.tst_filters:
self.tst_filters[filt] = list(self.tst_filters[filt])
self.tra_KG, self.tra_sub = self.load_graph(self.tra_train)
self.ind_KG, self.ind_sub = self.load_graph(self.ind_train, 'inductive')
self.tra_train = np.array(self.tra_valid)
self.tra_val_qry, self.tra_val_ans = self.load_query(self.tra_test)
self.ind_val_qry, self.ind_val_ans = self.load_query(self.ind_valid)
self.ind_tst_qry, self.ind_tst_ans = self.load_query(self.ind_test)
self.valid_q, self.valid_a = self.tra_val_qry, self.tra_val_ans
self.test_q, self.test_a = self.ind_val_qry + self.ind_tst_qry, self.ind_val_ans + self.ind_tst_ans
self.n_train = len(self.tra_train)
self.n_valid = len(self.valid_q)
self.n_test = len(self.test_q)
def read_triples(self, directory, filename, mode='transductive'):
triples = []
with open(os.path.join(directory, filename)) as f:
for line in f:
h, r, t = line.strip().split()
if mode == 'transductive':
h, r, t = self.entity2id[h], self.relation2id[r], self.entity2id[t]
else:
h, r, t = self.entity2id_ind[h], self.relation2id[r], self.entity2id_ind[t]
triples.append([h, r, t])
triples.append([t, r + self.n_rel, h])
return triples
def load_graph(self, triples, mode='transductive'):
n_ent = self.n_ent if mode == 'transductive' else self.n_ent_ind
KG = np.array(triples)
idd = np.concatenate([np.expand_dims(np.arange(n_ent), 1), 2 * self.n_rel * np.ones((n_ent, 1)),
np.expand_dims(np.arange(n_ent), 1)], 1)
KG = np.concatenate([KG, idd], 0)
n_fact = KG.shape[0]
M_sub = csr_matrix((np.ones((n_fact,)), (np.arange(n_fact), KG[:, 0])), shape=(n_fact, n_ent))
return KG, M_sub
def load_query(self, triples):
triples.sort(key=lambda x: (x[0], x[1]))
trip_hr = defaultdict(lambda: list())
for trip in triples:
h, r, t = trip
trip_hr[(h, r)].append(t)
queries = []
answers = []
for key in trip_hr:
queries.append(key)
answers.append(np.array(trip_hr[key]))
return queries, answers
def get_neighbors(self, nodes, mode='transductive'):
# nodes: n_node x 2 with (batch_idx, node_idx)
if mode == 'transductive':
KG = self.tra_KG
M_sub = self.tra_sub
n_ent = self.n_ent
else:
KG = self.ind_KG
M_sub = self.ind_sub
n_ent = self.n_ent_ind
node_1hot = csr_matrix((np.ones(len(nodes)), (nodes[:, 1], nodes[:, 0])), shape=(n_ent, nodes.shape[0]))
edge_1hot = M_sub.dot(node_1hot)
edges = np.nonzero(edge_1hot)
sampled_edges = np.concatenate([np.expand_dims(edges[1], 1), KG[edges[0]]],
axis=1) # (batch_idx, head, rela, tail)
sampled_edges = th.LongTensor(sampled_edges)
# index to nodes
head_nodes, head_index = th.unique(sampled_edges[:, [0, 1]], dim=0, sorted=True, return_inverse=True)
tail_nodes, tail_index = th.unique(sampled_edges[:, [0, 3]], dim=0, sorted=True, return_inverse=True)
mask = sampled_edges[:, 2] == (self.n_rel * 2)
_, old_idx = head_index[mask].sort()
old_nodes_new_idx = tail_index[mask][old_idx]
sampled_edges = th.cat([sampled_edges, head_index.unsqueeze(1), tail_index.unsqueeze(1)], 1)
return tail_nodes, sampled_edges, old_nodes_new_idx
def get_batch(self, batch_idx, steps=2, data='train'):
if data == 'train':
return self.tra_train[batch_idx]
if data == 'valid':
# print(self.)
query, answer = np.array(self.valid_q), self.valid_a # np.array(self.valid_a)
n_ent = self.n_ent
if data == 'test':
query, answer = np.array(self.test_q), self.test_a # np.array(self.test_a)
n_ent = self.n_ent_ind
subs = []
rels = []
objs = []
subs = query[batch_idx, 0]
rels = query[batch_idx, 1]
objs = np.zeros((len(batch_idx), n_ent))
for i in range(len(batch_idx)):
objs[i][answer[batch_idx[i]]] = 1
return subs, rels, objs
def shuffle_train(self, ):
rand_idx = np.random.permutation(self.n_train)
self.tra_train = self.tra_train[rand_idx]
def get_filter(self, data='valid'):
filters = defaultdict(lambda: set())
if data == 'valid':
for triple in self.tra_train:
h, r, t = triple
filters[(h, r)].add(t)
for triple in self.tra_valid:
h, r, t = triple
filters[(h, r)].add(t)
for triple in self.tra_test:
h, r, t = triple
filters[(h, r)].add(t)
else:
for triple in self.ind_train:
h, r, t = triple
filters[(h, r)].add(t)
for triple in self.ind_valid:
h, r, t = triple
filters[(h, r)].add(t)
for triple in self.ind_test:
h, r, t = triple
filters[(h, r)].add(t)
return filters
@register_dataset('kg_subT_link_prediction')
class KG_RedTDataset(LinkPredictionDataset):
def __init__(self, dataset_name, *args, **kwargs):
super(KG_RedTDataset, self).__init__(*args, **kwargs)
self.task_dir = os.path.join('openhgnn/dataset/data', dataset_name)
task_dir = self.task_dir
folder = os.path.exists(self.task_dir)
if not folder:
os.makedirs(self.task_dir)
url = "https://s3.cn-north-1.amazonaws.com.cn/dgl-data/dataset/openhgnn/family.zip"
response = requests.get(url)
with zipfile.ZipFile(io.BytesIO(response.content)) as myzip:
myzip.extractall(self.task_dir)
print("--- download data ---")
else:
print("--- There is data! ---")
with open(os.path.join(task_dir, 'entities.txt')) as f:
self.entity2id = dict()
n_ent = 0
for line in f:
entity = line.strip()
self.entity2id[entity] = n_ent
n_ent += 1
with open(os.path.join(task_dir, 'relations.txt')) as f:
self.relation2id = dict()
n_rel = 0
for line in f:
relation = line.strip()
self.relation2id[relation] = n_rel
n_rel += 1
self.n_ent = n_ent
self.n_rel = n_rel
self.filters = defaultdict(lambda: set())
self.fact_triple = self.read_triples('facts.txt')
self.train_triple = self.read_triples('train.txt')
self.valid_triple = self.read_triples('valid.txt')
self.test_triple = self.read_triples('test.txt')
self.fact_data = self.double_triple(self.fact_triple)
self.train_data = np.array(self.double_triple(self.train_triple))
self.valid_data = self.double_triple(self.valid_triple)
self.test_data = self.double_triple(self.test_triple)
self.load_graph(self.fact_data)
self.load_test_graph(self.double_triple(self.fact_triple) + self.double_triple(self.train_triple))
self.valid_q, self.valid_a = self.load_query(self.valid_data)
self.test_q, self.test_a = self.load_query(self.test_data)
self.n_train = len(self.train_data)
self.n_valid = len(self.valid_q)
self.n_test = len(self.test_q)
for filt in self.filters:
self.filters[filt] = list(self.filters[filt])
print('n_train:', self.n_train, 'n_valid:', self.n_valid, 'n_test:', self.n_test)
def read_triples(self, filename):
triples = []
with open(os.path.join(self.task_dir, filename)) as f:
for line in f:
h, r, t = line.strip().split()
h, r, t = self.entity2id[h], self.relation2id[r], self.entity2id[t]
triples.append([h, r, t])
self.filters[(h, r)].add(t)
self.filters[(t, r + self.n_rel)].add(h)
return triples
def double_triple(self, triples):
new_triples = []
for triple in triples:
h, r, t = triple
new_triples.append([t, r + self.n_rel, h])
return triples + new_triples
def load_graph(self, triples):
idd = np.concatenate([np.expand_dims(np.arange(self.n_ent), 1), 2 * self.n_rel * np.ones((self.n_ent, 1)),
np.expand_dims(np.arange(self.n_ent), 1)], 1)
self.KG = np.concatenate([np.array(triples), idd], 0)
self.n_fact = len(self.KG)
self.M_sub = csr_matrix((np.ones((self.n_fact,)), (np.arange(self.n_fact), self.KG[:, 0])),
shape=(self.n_fact, self.n_ent))
def load_test_graph(self, triples):
idd = np.concatenate([np.expand_dims(np.arange(self.n_ent), 1), 2 * self.n_rel * np.ones((self.n_ent, 1)),
np.expand_dims(np.arange(self.n_ent), 1)], 1)
self.tKG = np.concatenate([np.array(triples), idd], 0)
self.tn_fact = len(self.tKG)
self.tM_sub = csr_matrix((np.ones((self.tn_fact,)), (np.arange(self.tn_fact), self.tKG[:, 0])),
shape=(self.tn_fact, self.n_ent))
def load_query(self, triples):
triples.sort(key=lambda x: (x[0], x[1]))
trip_hr = defaultdict(lambda: list())
for trip in triples:
h, r, t = trip
trip_hr[(h, r)].append(t)
queries = []
answers = []
for key in trip_hr:
queries.append(key)
answers.append(np.array(trip_hr[key]))
return queries, answers
def get_neighbors(self, nodes, mode='train'):
if mode == 'train':
KG = self.KG
M_sub = self.M_sub
else:
KG = self.tKG
M_sub = self.tM_sub
# nodes: n_node x 2 with (batch_idx, node_idx)
node_1hot = csr_matrix((np.ones(len(nodes)), (nodes[:, 1], nodes[:, 0])), shape=(self.n_ent, nodes.shape[0]))
edge_1hot = M_sub.dot(node_1hot)
edges = np.nonzero(edge_1hot)
sampled_edges = np.concatenate([np.expand_dims(edges[1], 1), KG[edges[0]]],
axis=1) # (batch_idx, head, rela, tail)
sampled_edges = torch.LongTensor(sampled_edges).cuda()
# index to nodes
head_nodes, head_index = torch.unique(sampled_edges[:, [0, 1]], dim=0, sorted=True, return_inverse=True)
tail_nodes, tail_index = torch.unique(sampled_edges[:, [0, 3]], dim=0, sorted=True, return_inverse=True)
sampled_edges = torch.cat([sampled_edges, head_index.unsqueeze(1), tail_index.unsqueeze(1)], 1)
mask = sampled_edges[:, 2] == (self.n_rel * 2)
_, old_idx = head_index[mask].sort()
old_nodes_new_idx = tail_index[mask][old_idx]
return tail_nodes, sampled_edges, old_nodes_new_idx
def get_batch(self, batch_idx, steps=2, data='train'):
if data == 'train':
return np.array(self.train_data)[batch_idx]
if data == 'valid':
query, answer = np.array(self.valid_q), self.valid_a
if data == 'test':
query, answer = np.array(self.test_q), self.test_a
subs = []
rels = []
objs = []
subs = query[batch_idx, 0]
rels = query[batch_idx, 1]
objs = np.zeros((len(batch_idx), self.n_ent))
for i in range(len(batch_idx)):
objs[i][answer[batch_idx[i]]] = 1
return subs, rels, objs
def shuffle_train(self, ):
fact_triple = np.array(self.fact_triple)
train_triple = np.array(self.train_triple)
all_triple = np.concatenate([fact_triple, train_triple], axis=0)
n_all = len(all_triple)
rand_idx = np.random.permutation(n_all)
all_triple = all_triple[rand_idx]
# increase the ratio of fact_data, e.g., 3/4->4/5, can increase the performance
self.fact_data = self.double_triple(all_triple[:n_all * 3 // 4].tolist())
self.train_data = np.array(self.double_triple(all_triple[n_all * 3 // 4:].tolist()))
self.n_train = len(self.train_data)
self.load_graph(self.fact_data)
@register_dataset('kg_link_prediction')
class KG_LinkPrediction(LinkPredictionDataset):
"""
From `RGCN <https://arxiv.org/abs/1703.06103>`_, WN18 & FB15k face a data leakage.
"""
def __init__(self, dataset_name, *args, **kwargs):
super(KG_LinkPrediction, self).__init__(*args, **kwargs)
if dataset_name in ['wn18', 'FB15k', 'FB15k-237']:
dataset = load_data(dataset_name)
g = dataset[0]
self.num_rels = dataset.num_rels
self.num_nodes = dataset.num_nodes
self.train_hg, self.train_triplets = self._build_hg(g, 'train')
self.valid_hg, self.valid_triplets = self._build_hg(g, 'valid')
self.test_hg, self.test_triplets = self._build_hg(g, 'test')
self.g = self.train_hg
self.category = '_N'
self.target_link = self.test_hg.canonical_etypes
def _build_hg(self, g, mode):
sub_g = dgl.edge_subgraph(g, g.edata[mode + '_edge_mask'], relabel_nodes=False)
src, dst = sub_g.edges( )
etype = sub_g.edata['etype']
edge_dict = {}
for i in range(self.num_rels):
mask = (etype == i)
edge_name = ('_N', str(i), '_N')
edge_dict[edge_name] = (src[mask], dst[mask])
hg = dgl.heterograph(edge_dict, {'_N': self.num_nodes})
return hg, th.stack((src, etype, dst)).T
def modify_size(self, eval_percent, dataset_type):
if dataset_type == 'valid':
self.valid_triplets = th.tensor(
random.sample(self.valid_triplets.tolist( ), math.ceil(self.valid_triplets.shape[0] * eval_percent)))
elif dataset_type == 'test':
self.test_triplets = th.tensor(
random.sample(self.test_triplets.tolist( ), math.ceil(self.test_triplets.shape[0] * eval_percent)))
def get_graph_directed_from_triples(self, triples, format='graph'):
s = th.LongTensor(triples[:, 0])
r = th.LongTensor(triples[:, 1])
o = th.LongTensor(triples[:, 2])
if format == 'graph':
edge_dict = {}
for i in range(self.num_rels):
mask = (r == i)
edge_name = (self.category, str(i), self.category)
edge_dict[edge_name] = (s[mask], o[mask])
return dgl.heterograph(edge_dict, {self.category: self.num_nodes})
def get_triples(self, g, mask_mode):
'''
:param g:
:param mask_mode: should be one of 'train_mask', 'val_mask', 'test_mask
:return:
'''
edges = g.edges( )
etype = g.edata['etype']
mask = g.edata.pop(mask_mode)
return th.stack((edges[0][mask], etype[mask], edges[1][mask]))
def get_all_triplets(self, dataset):
train_data = th.LongTensor(dataset.train)
valid_data = th.LongTensor(dataset.valid)
test_data = th.LongTensor(dataset.test)
return train_data, valid_data, test_data
def get_split(self):
return self.train_hg, self.valid_hg, self.test_hg, None, None
def split_graph(self, g, mode='train'):
"""
Parameters
----------
g: DGLGraph
a homogeneous graph fomat
mode: str
split the subgraph according to the mode
Returns
-------
hg: DGLHeterograph
"""
edges = g.edges( )
etype = g.edata['etype']
if mode == 'train':
mask = g.edata['train_mask']
elif mode == 'valid':
mask = g.edata['valid_edge_mask']
elif mode == 'test':
mask = g.edata['test_edge_mask']
hg = self.build_graph((edges[0][mask], edges[1][mask]), etype[mask])
return hg
def build_graph(self, edges, etype):
edge_dict = {}
for i in range(self.num_rels):
mask = (etype == i)
edge_name = (self.category, str(i), self.category)
edge_dict[edge_name] = (edges[0][mask], edges[1][mask])
hg = dgl.heterograph(edge_dict, {self.category: self.num_nodes})
return hg
def build_g(self, train):
s = train[:, 0]