-
Notifications
You must be signed in to change notification settings - Fork 0
/
CFAG.py
1333 lines (1163 loc) · 68 KB
/
CFAG.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
'''
Created on Oct 10, 2018
Tensorflow Implementation of Neural Graph Collaborative Filtering (NGCF) model in:
Wang Xiang et al. Neural Graph Collaborative Filtering. In SIGIR 2019.
@author: Xiang Wang (xiangwang@u.nus.edu)
version:
Parallelized sampling on CPU
C++ evaluation for top-k recommendation
'''
import os
import sys
import threading
import tensorflow as tf
from tensorflow.python.client import device_lib
from utility.helper import *
from utility.attention import *
from utility.batch_test import *
from tensorflow.keras.regularizers import l2
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
cpus = [x.name for x in device_lib.list_local_devices() if x.device_type == 'CPU']
class LightGCN(object):
def __init__(self, data_config, pretrain_data):
# argument settings
self.model_type = 'LightGCN'
self.adj_type = args.adj_type
self.alg_type = args.alg_type
self.pretrain_data = pretrain_data
self.n_groups = data_config['n_groups']
self.n_users = data_config['n_users']
self.aug_type = args.aug_type
self.item_side = args.item_side
self.ssl_mode = args.ssl_mode
self.ssl_temp = args.ssl_temp
self.n_items = data_config['n_items']
self.ssl_reg = args.ssl_reg
self.ssl_ratio = args.ssl_ratio
self.n_fold = 1
self.norm_adj = data_config['norm_adj']
self.n_nonzero_elems = self.norm_adj.count_nonzero()
self.att_ver = args.att_ver
self.att_coef = args.att_coef
self.gat_type = args.gat_type
self.R = data_config['R']
self.R_gi = data_config['R_gi']
self.norm_adj_gi = data_config['norm_adj_gi']
self.n_nonzero_elems_gi = self.norm_adj.count_nonzero()
self.norm_adj_ui = data_config['norm_adj_ui']
self.n_nonzero_elems_ui = self.norm_adj_ui.count_nonzero()
if self.aug_type != -1:
self.sgl_norm_adj = self.create_adj_mat(False)
# print(self.norm_adj.toarray().shape)
# print(self.norm_adj_gi.toarray().shape)
# print(self.norm_adj_ui.toarray().shape)
self.lr = args.lr
self.emb_dim = args.embed_size
self.intra_emb_dim = args.intra_emb_dim
self.batch_size = args.batch_size
self.weight_size = eval(args.layer_size)
self.n_layers = len(self.weight_size)
self.regs = eval(args.regs)
self.decay = self.regs[0]
self.log_dir = self.create_model_str()
self.verbose = args.verbose
self.Ks = eval(args.Ks)
self.gi_side = args.gi_side
self.att_concat = args.att_concat
self.ebd_save = args.ebd_save
'''
*********************************************************
Create Placeholder for Input Data & Dropout.
'''
# placeholder definition
self.train = tf.placeholder(tf.bool)
if self.train == tf.constant(True):
self.groups = tf.placeholder(tf.int32, shape=(self.batch_size,))
self.pos_users = tf.placeholder(tf.int32, shape=(self.batch_size,))
self.neg_users = tf.placeholder(tf.int32, shape=(self.batch_size,))
else:
self.groups = tf.placeholder(tf.int32, shape=(None,))
self.pos_users = tf.placeholder(tf.int32, shape=(None,))
self.neg_users = tf.placeholder(tf.int32, shape=(None,))
att_initializer = tf.random_normal_initializer(stddev=0.01)
if self.att_ver in [1]:
self.gu_attention = tf.Variable(
tf.constant_initializer(1.)(shape=[self.n_users, self.n_users], dtype=tf.float32))
self.gi_attention = tf.Variable(
tf.constant_initializer(1.)(shape=[self.n_items, self.n_items], dtype=tf.float32))
elif self.att_ver == 2:
(gu_indices_row, gu_indices_col) = self.R.nonzero()
(gi_indices_row, gi_indices_col) = self.R_gi.nonzero()
gu_atten_w = tf.Variable(tf.constant_initializer(1.)(shape=[gu_indices_row.shape[0], ], dtype=tf.float32))
gi_atten_w = tf.Variable(tf.constant_initializer(1.)(shape=[gi_indices_row.shape[0], ], dtype=tf.float32))
self.gu_attention_v2 = tf.sparse_softmax(
tf.SparseTensor(indices=np.stack((gu_indices_row, gu_indices_col), axis=1),
values=gu_atten_w, dense_shape=self.R.shape))
self.gi_attention_v2 = tf.sparse_softmax(
tf.SparseTensor(indices=np.stack((gi_indices_row, gi_indices_col), axis=1),
values=gi_atten_w, dense_shape=self.R_gi.shape))
elif self.att_ver == 3:
self.gu_attention = tf.Variable(
att_initializer(shape=[self.n_groups, self.n_users], dtype=tf.float32))
self.gi_attention = tf.Variable(
att_initializer(shape=[self.n_groups, self.n_items], dtype=tf.float32))
elif self.att_ver == 4:
self.gu_attention_vert = tf.Variable(
att_initializer(shape=[self.n_users, self.intra_emb_dim], dtype=tf.float32))
self.gu_attention_hori = tf.Variable(
att_initializer(shape=[self.intra_emb_dim, self.n_users], dtype=tf.float32))
self.gi_attention_vert = tf.Variable(
att_initializer(shape=[self.n_items, self.intra_emb_dim], dtype=tf.float32))
self.gi_attention_hori = tf.Variable(
att_initializer(shape=[self.intra_emb_dim, self.n_items], dtype=tf.float32))
elif self.att_ver in [5, 6]:
self.gu_attention_vert = tf.Variable(
att_initializer(shape=[self.n_users, self.intra_emb_dim], dtype=tf.float32), name='gu_attention')
self.gi_attention_vert = tf.Variable(
att_initializer(shape=[self.n_items, self.intra_emb_dim], dtype=tf.float32), name='gi_attention')
self.items = tf.placeholder(tf.int32, shape=(None,))
self.node_dropout_flag = args.node_dropout_flag
self.node_dropout = tf.placeholder(tf.float32, shape=[None])
self.mess_dropout = tf.placeholder(tf.float32, shape=[None])
with tf.name_scope('TRAIN_LOSS'):
self.train_loss = tf.placeholder(tf.float32)
tf.summary.scalar('train_loss', self.train_loss)
self.train_mf_loss = tf.placeholder(tf.float32)
tf.summary.scalar('train_mf_loss', self.train_mf_loss)
self.train_emb_loss = tf.placeholder(tf.float32)
tf.summary.scalar('train_emb_loss', self.train_emb_loss)
self.train_reg_loss = tf.placeholder(tf.float32)
tf.summary.scalar('train_reg_loss', self.train_reg_loss)
self.train_ssl_loss = tf.placeholder(tf.float32)
tf.summary.scalar('train_ssl_loss', self.train_ssl_loss)
self.merged_train_loss = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES, 'TRAIN_LOSS'))
with tf.name_scope('TRAIN_ACC'):
self.train_rec_first = tf.placeholder(tf.float32)
# record for top(Ks[0])
tf.summary.scalar('train_rec_first', self.train_rec_first)
self.train_rec_last = tf.placeholder(tf.float32)
# record for top(Ks[-1])
tf.summary.scalar('train_rec_last', self.train_rec_last)
self.train_ndcg_first = tf.placeholder(tf.float32)
tf.summary.scalar('train_ndcg_first', self.train_ndcg_first)
self.train_ndcg_last = tf.placeholder(tf.float32)
tf.summary.scalar('train_ndcg_last', self.train_ndcg_last)
self.merged_train_acc = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES, 'TRAIN_ACC'))
with tf.name_scope('TEST_LOSS'):
self.test_loss = tf.placeholder(tf.float32)
tf.summary.scalar('test_loss', self.test_loss)
self.test_mf_loss = tf.placeholder(tf.float32)
tf.summary.scalar('test_mf_loss', self.test_mf_loss)
self.test_emb_loss = tf.placeholder(tf.float32)
tf.summary.scalar('test_emb_loss', self.test_emb_loss)
self.test_reg_loss = tf.placeholder(tf.float32)
tf.summary.scalar('test_reg_loss', self.test_reg_loss)
self.test_ssl_loss = tf.placeholder(tf.float32)
tf.summary.scalar('test_ssl_loss', self.test_ssl_loss)
self.merged_test_loss = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES, 'TEST_LOSS'))
with tf.name_scope('TEST_ACC'):
self.test_rec_first = tf.placeholder(tf.float32)
tf.summary.scalar('test_rec_first', self.test_rec_first)
self.test_rec_last = tf.placeholder(tf.float32)
tf.summary.scalar('test_rec_last', self.test_rec_last)
self.test_ndcg_first = tf.placeholder(tf.float32)
tf.summary.scalar('test_ndcg_first', self.test_ndcg_first)
self.test_ndcg_last = tf.placeholder(tf.float32)
tf.summary.scalar('test_ndcg_last', self.test_ndcg_last)
self.merged_test_acc = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES, 'TEST_ACC'))
"""
*********************************************************
Create Model Parameters (i.e., Initialize Weights).
"""
# initialization of model parameters
self.weights = self._init_weights()
"""
*********************************************************
Compute Graph-based Representations of all groups & users via Message-Passing Mechanism of Graph Neural Networks.
Different Convolutional Layers:
1. ngcf: defined in 'Neural Graph Collaborative Filtering', SIGIR2019;
2. gcn: defined in 'Semi-Supervised Classification with Graph Convolutional Networks', ICLR2018;
3. gcmc: defined in 'Graph Convolutional Matrix Completion', KDD2018;
"""
if self.alg_type in ['lightgcn']:
if self.item_side == 0:
self.ga_embeddings, self.ua_embeddings = self._create_lightgcn_embed()
elif self.item_side == 1:
self.ga_embeddings, self.ua_embeddings, self.ia_embeddings = self._create_lightgcn_embed_general()
print('embedding created')
if self.aug_type != -1:
self.ga_embeddings_sub1, self.ga_embeddings_sub2, self.ua_embeddings_sub1, self.ua_embeddings_sub2 = self._create_lightgcn_embed_sgl()
elif self.alg_type in ['ngcf']:
self.ga_embeddings, self.ua_embeddings = self._create_ngcf_embed()
elif self.alg_type in ['gcn']:
self.ga_embeddings, self.ua_embeddings = self._create_gcn_embed()
elif self.alg_type in ['gcmc']:
self.ga_embeddings, self.ua_embeddings = self._create_gcmc_embed()
"""
*********************************************************
Establish the final representations for group-user pairs in batch.
"""
self.g_g_embeddings = tf.nn.embedding_lookup(self.ga_embeddings, self.groups)
self.pos_u_g_embeddings = tf.nn.embedding_lookup(self.ua_embeddings, self.pos_users)
self.neg_u_g_embeddings = tf.nn.embedding_lookup(self.ua_embeddings, self.neg_users)
self.g_g_embeddings_pre = tf.nn.embedding_lookup(self.weights['group_embedding'], self.groups)
self.pos_u_g_embeddings_pre = tf.nn.embedding_lookup(self.weights['user_embedding'], self.pos_users)
self.neg_u_g_embeddings_pre = tf.nn.embedding_lookup(self.weights['user_embedding'], self.neg_users)
"""
*********************************************************
Inference for the testing phase.
"""
if self.att_ver == 5 and self.ebd_save == 1:
# self.gu_atten_embeddings = tf.nn.embedding_lookup(self.gu_attention_vert, self.pos_users)
# self.saved_embedding = [self.g_g_embeddings, self.pos_u_g_embeddings, self.gu_atten_embeddings]
self.gi_atten_embeddings = self.gi_attention_vert
self.saved_embedding = [self.g_g_embeddings, self.ia_embeddings, self.gi_atten_embeddings]
self.batch_ratings = tf.matmul(self.g_g_embeddings, self.pos_u_g_embeddings, transpose_a=False,
transpose_b=True)
"""
*********************************************************
Generate Predictions & Optimize via BPR loss.
"""
self.mf_loss, self.emb_loss, self.reg_loss = self.create_bpr_loss(self.g_g_embeddings,
self.pos_u_g_embeddings,
self.neg_u_g_embeddings)
self.ssl_loss = self.calc_ssl_loss_v2(self.ga_embeddings_sub1, self.ga_embeddings_sub2, self.ua_embeddings_sub1,
self.ua_embeddings_sub2) if self.aug_type != -1 else tf.constant(0.0,
tf.float32)
self.loss = self.mf_loss + self.emb_loss + self.ssl_loss
# self.loss = self.mf_loss + self.emb_loss
self.opt = tf.train.AdamOptimizer(learning_rate=self.lr).minimize(self.loss)
def create_model_str(self):
log_dir = '/' + self.alg_type + '/layers_' + str(self.n_layers) + '/dim_' + str(self.emb_dim)
log_dir += '/' + args.dataset + '/lr_' + str(self.lr) + '/reg_' + str(self.decay)
return log_dir
def create_adj_mat(self, is_subgraph=False, aug_type=0):
n_nodes = self.n_groups + self.n_users
self.training_group = data_generator.groups_list
self.training_user = data_generator.users_list
if is_subgraph and aug_type in [0, 1, 2] and self.ssl_ratio > 0:
# data augmentation type --- 0: Node Dropout; 1: Edge Dropout; 2: Random Walk
if aug_type == 0:
drop_user_idx = randint_choice(self.n_groups, size=int(self.n_groups * self.ssl_ratio), replace=False)
drop_item_idx = randint_choice(self.n_users, size=int(self.n_users * self.ssl_ratio), replace=False)
indicator_user = np.ones(self.n_groups, dtype=np.float32)
indicator_item = np.ones(self.n_users, dtype=np.float32)
indicator_user[drop_user_idx] = 0.
indicator_item[drop_item_idx] = 0.
diag_indicator_user = sp.diags(indicator_user)
diag_indicator_item = sp.diags(indicator_item)
R = data_generator.R
R_prime = diag_indicator_user.dot(R).dot(diag_indicator_item)
(user_np_keep, item_np_keep) = R_prime.nonzero()
ratings_keep = R_prime.data
tmp_adj = sp.csr_matrix((ratings_keep, (user_np_keep, item_np_keep + self.n_groups)),
shape=(n_nodes, n_nodes))
if aug_type in [1, 2]:
keep_idx = randint_choice(len(self.training_group),
size=int(len(self.training_group) * (1 - self.ssl_ratio)), replace=False)
user_np = np.array(self.training_group)[keep_idx]
item_np = np.array(self.training_user)[keep_idx]
ratings = np.ones_like(user_np, dtype=np.float32)
tmp_adj = sp.csr_matrix((ratings, (user_np, item_np + self.n_groups)), shape=(n_nodes, n_nodes))
else:
user_np = np.array(self.training_group)
item_np = np.array(self.training_user)
ratings = np.ones_like(user_np, dtype=np.float32)
tmp_adj = sp.csr_matrix((ratings, (user_np, item_np + self.n_groups)), shape=(n_nodes, n_nodes))
adj_mat = tmp_adj + tmp_adj.T
# pre adjcency matrix
rowsum = np.array(adj_mat.sum(1))
d_inv = np.power(rowsum, -0.5).flatten()
d_inv[np.isinf(d_inv)] = 0.
d_mat_inv = sp.diags(d_inv)
norm_adj_tmp = d_mat_inv.dot(adj_mat)
adj_matrix = norm_adj_tmp.dot(d_mat_inv)
# print('use the pre adjcency matrix')
return adj_matrix
def _init_weights(self):
if self.aug_type != -1:
self.sub_mat = {}
if self.aug_type in [0, 1]:
self.sub_mat['adj_values_sub1'] = tf.placeholder(tf.float32)
self.sub_mat['adj_indices_sub1'] = tf.placeholder(tf.int64)
self.sub_mat['adj_shape_sub1'] = tf.placeholder(tf.int64)
self.sub_mat['adj_values_sub2'] = tf.placeholder(tf.float32)
self.sub_mat['adj_indices_sub2'] = tf.placeholder(tf.int64)
self.sub_mat['adj_shape_sub2'] = tf.placeholder(tf.int64)
else:
for k in range(1, self.n_layers + 1):
self.sub_mat['adj_values_sub1%d' % k] = tf.placeholder(tf.float32, name='adj_values_sub1%d' % k)
self.sub_mat['adj_indices_sub1%d' % k] = tf.placeholder(tf.int64, name='adj_indices_sub1%d' % k)
self.sub_mat['adj_shape_sub1%d' % k] = tf.placeholder(tf.int64, name='adj_shape_sub1%d' % k)
self.sub_mat['adj_values_sub2%d' % k] = tf.placeholder(tf.float32, name='adj_values_sub2%d' % k)
self.sub_mat['adj_indices_sub2%d' % k] = tf.placeholder(tf.int64, name='adj_indices_sub2%d' % k)
self.sub_mat['adj_shape_sub2%d' % k] = tf.placeholder(tf.int64, name='adj_shape_sub2%d' % k)
all_weights = dict()
initializer = tf.random_normal_initializer(stddev=0.01) # tf.contrib.layers.xavier_initializer()
if self.pretrain_data is None:
all_weights['group_embedding'] = tf.Variable(initializer([self.n_groups, self.emb_dim]),
name='group_embedding')
all_weights['user_embedding'] = tf.Variable(initializer([self.n_users, self.emb_dim]),
name='user_embedding')
all_weights['item_embedding'] = tf.Variable(initializer([self.n_items, self.emb_dim]),
name='item_embedding')
# all_weights['gu_atten_embedding'] = tf.Variable(initializer([self.n_users, self.intra_emb_dim]),
# name='gu_atten_embedding')
print('using random initialization') # print('using xavier initialization')
else:
all_weights['group_embedding'] = tf.Variable(initial_value=self.pretrain_data['group_embed'],
trainable=True,
name='group_embedding', dtype=tf.float32)
all_weights['user_embedding'] = tf.Variable(initial_value=self.pretrain_data['user_embed'], trainable=True,
name='user_embedding', dtype=tf.float32)
all_weights['item_embedding'] = tf.Variable(initial_value=self.pretrain_data['item_embed'], trainable=True,
name='item_embedding', dtype=tf.float32)
print('using pretrained initialization')
self.weight_size_list = [self.emb_dim] + self.weight_size
for k in range(self.n_layers):
all_weights['W_gc_%d' % k] = tf.Variable(
initializer([self.weight_size_list[k], self.weight_size_list[k + 1]]), name='W_gc_%d' % k)
all_weights['b_gc_%d' % k] = tf.Variable(
initializer([1, self.weight_size_list[k + 1]]), name='b_gc_%d' % k)
all_weights['W_bi_%d' % k] = tf.Variable(
initializer([self.weight_size_list[k], self.weight_size_list[k + 1]]), name='W_bi_%d' % k)
all_weights['b_bi_%d' % k] = tf.Variable(
initializer([1, self.weight_size_list[k + 1]]), name='b_bi_%d' % k)
all_weights['W_mlp_%d' % k] = tf.Variable(
initializer([self.weight_size_list[k], self.weight_size_list[k + 1]]), name='W_mlp_%d' % k)
all_weights['b_mlp_%d' % k] = tf.Variable(
initializer([1, self.weight_size_list[k + 1]]), name='b_mlp_%d' % k)
return all_weights
def _split_A_hat(self, X):
A_fold_hat = []
fold_len = (self.n_groups + self.n_users) // self.n_fold
for i_fold in range(self.n_fold):
start = i_fold * fold_len
if i_fold == self.n_fold - 1:
end = self.n_groups + self.n_users
else:
end = (i_fold + 1) * fold_len
A_fold_hat.append(self._convert_sp_mat_to_sp_tensor(X[start:end]))
return A_fold_hat
def _split_A_hat_general(self, n_groups, n_users, norm_adj):
# print(norm_adj.toarray().shape)
A_fold_hat = []
fold_len = (n_groups + n_users) // self.n_fold
for i_fold in range(self.n_fold):
start = i_fold * fold_len
if i_fold == self.n_fold - 1:
end = n_groups + n_users
else:
end = (i_fold + 1) * fold_len
# print(start, end)
A_fold_hat.append(self._convert_sp_mat_to_sp_tensor(norm_adj[start:end]))
return A_fold_hat
def _split_A_hat_node_dropout_general(self, n_groups, n_users, norm_adj):
A_fold_hat = []
fold_len = (n_groups + n_users) // self.n_fold
for i_fold in range(self.n_fold):
start = i_fold * fold_len
if i_fold == self.n_fold - 1:
end = n_groups + n_users
else:
end = (i_fold + 1) * fold_len
temp = self._convert_sp_mat_to_sp_tensor(norm_adj[start:end])
n_nonzero_temp = norm_adj[start:end].count_nonzero()
A_fold_hat.append(self._dropout_sparse(temp, 1 - self.node_dropout[0], n_nonzero_temp))
return A_fold_hat
def _split_A_hat_node_dropout(self, X):
A_fold_hat = []
fold_len = (self.n_groups + self.n_users) // self.n_fold
for i_fold in range(self.n_fold):
start = i_fold * fold_len
if i_fold == self.n_fold - 1:
end = self.n_groups + self.n_users
else:
end = (i_fold + 1) * fold_len
temp = self._convert_sp_mat_to_sp_tensor(X[start:end])
n_nonzero_temp = X[start:end].count_nonzero()
A_fold_hat.append(self._dropout_sparse(temp, 1 - self.node_dropout[0], n_nonzero_temp))
return A_fold_hat
def _create_lightgcn_embed_sgl(self):
for k in range(1, self.n_layers + 1):
if self.aug_type in [0, 1]:
self.sub_mat['sub_mat_1%d' % k] = tf.SparseTensor(
self.sub_mat['adj_indices_sub1'],
self.sub_mat['adj_values_sub1'],
self.sub_mat['adj_shape_sub1'])
self.sub_mat['sub_mat_2%d' % k] = tf.SparseTensor(
self.sub_mat['adj_indices_sub2'],
self.sub_mat['adj_values_sub2'],
self.sub_mat['adj_shape_sub2'])
else:
self.sub_mat['sub_mat_1%d' % k] = tf.SparseTensor(
self.sub_mat['adj_indices_sub1%d' % k],
self.sub_mat['adj_values_sub1%d' % k],
self.sub_mat['adj_shape_sub1%d' % k])
self.sub_mat['sub_mat_2%d' % k] = tf.SparseTensor(
self.sub_mat['adj_indices_sub2%d' % k],
self.sub_mat['adj_values_sub2%d' % k],
self.sub_mat['adj_shape_sub2%d' % k])
# adj_mat = self._convert_sp_mat_to_sp_tensor(self.norm_adj_sgl)
ego_embeddings = tf.concat([self.weights['group_embedding'], self.weights['user_embedding']], axis=0)
ego_embeddings_sub1 = ego_embeddings
ego_embeddings_sub2 = ego_embeddings
all_embeddings = [ego_embeddings]
all_embeddings_sub1 = [ego_embeddings_sub1]
all_embeddings_sub2 = [ego_embeddings_sub2]
for k in range(1, self.n_layers + 1):
# ego_embeddings = tf.sparse_tensor_dense_matmul(adj_mat, ego_embeddings, name="sparse_dense")
# all_embeddings += [ego_embeddings]
ego_embeddings_sub1 = tf.sparse_tensor_dense_matmul(
self.sub_mat['sub_mat_1%d' % k],
ego_embeddings_sub1, name="sparse_dense_sub1%d" % k)
all_embeddings_sub1 += [ego_embeddings_sub1]
ego_embeddings_sub2 = tf.sparse_tensor_dense_matmul(
self.sub_mat['sub_mat_2%d' % k],
ego_embeddings_sub2, name="sparse_dense_sub2%d" % k)
all_embeddings_sub2 += [ego_embeddings_sub2]
# all_embeddings = tf.stack(all_embeddings, 1)
# all_embeddings = tf.reduce_mean(all_embeddings, axis=1, keepdims=False)
# u_g_embeddings, i_g_embeddings = tf.split(all_embeddings, [self.n_users, self.n_items], 0)
all_embeddings_sub1 = tf.stack(all_embeddings_sub1, 1)
all_embeddings_sub1 = tf.reduce_mean(all_embeddings_sub1, axis=1, keepdims=False)
g_g_embeddings_sub1, u_g_embeddings_sub1 = tf.split(all_embeddings_sub1, [self.n_groups, self.n_users], 0)
all_embeddings_sub2 = tf.stack(all_embeddings_sub2, 1)
all_embeddings_sub2 = tf.reduce_mean(all_embeddings_sub2, axis=1, keepdims=False)
g_g_embeddings_sub2, u_g_embeddings_sub2 = tf.split(all_embeddings_sub2, [self.n_groups, self.n_users], 0)
return g_g_embeddings_sub1, u_g_embeddings_sub1, g_g_embeddings_sub2, u_g_embeddings_sub2
def calc_ssl_loss_v2(self, ga_embeddings_sub1, ga_embeddings_sub2, ua_embeddings_sub1, ua_embeddings_sub2):
'''
The denominator is summing over all the group or user nodes in the whole grpah
'''
if self.ssl_mode in ['group_side', 'both_side']:
group_emb1 = tf.nn.embedding_lookup(ga_embeddings_sub1, self.groups)
group_emb2 = tf.nn.embedding_lookup(ga_embeddings_sub2, self.groups)
normalize_group_emb1 = tf.nn.l2_normalize(group_emb1, 1)
normalize_group_emb2 = tf.nn.l2_normalize(group_emb2, 1)
normalize_all_group_emb2 = tf.nn.l2_normalize(ga_embeddings_sub2, 1)
pos_score_group = tf.reduce_sum(tf.multiply(normalize_group_emb1, normalize_group_emb2), axis=1)
ttl_score_group = tf.matmul(normalize_group_emb1, normalize_all_group_emb2, transpose_a=False,
transpose_b=True)
pos_score_group = tf.exp(pos_score_group / self.ssl_temp)
ttl_score_group = tf.reduce_sum(tf.exp(ttl_score_group / self.ssl_temp), axis=1)
ssl_loss_group = -tf.reduce_sum(tf.log(pos_score_group / ttl_score_group))
if self.ssl_mode in ['user_side', 'both_side']:
user_emb1 = tf.nn.embedding_lookup(ua_embeddings_sub1, self.pos_users)
user_emb2 = tf.nn.embedding_lookup(ua_embeddings_sub2, self.pos_users)
normalize_user_emb1 = tf.nn.l2_normalize(user_emb1, 1)
normalize_user_emb2 = tf.nn.l2_normalize(user_emb2, 1)
normalize_all_user_emb2 = tf.nn.l2_normalize(ua_embeddings_sub2, 1)
pos_score_user = tf.reduce_sum(tf.multiply(normalize_user_emb1, normalize_user_emb2), axis=1)
ttl_score_user = tf.matmul(normalize_user_emb1, normalize_all_user_emb2, transpose_a=False,
transpose_b=True)
pos_score_user = tf.exp(pos_score_user / self.ssl_temp)
ttl_score_user = tf.reduce_sum(tf.exp(ttl_score_user / self.ssl_temp), axis=1)
ssl_loss_user = -tf.reduce_sum(tf.log(pos_score_user / ttl_score_user))
if self.ssl_mode == 'group_side':
ssl_loss = self.ssl_reg * ssl_loss_group
elif self.ssl_mode == 'user_side':
ssl_loss = self.ssl_reg * ssl_loss_user
else:
ssl_loss = self.ssl_reg * (ssl_loss_group + ssl_loss_user)
return ssl_loss
def graph_atten(self, user_embeddings, R, gu_attention):
R = self._convert_sp_mat_to_sp_tensor(R)
atten_mat = tf.nn.softmax(tf.sparse_tensor_dense_matmul(R, gu_attention), axis=1)
# atten_mat = tf.nn.softmax(tf.nn.leaky_relu(tf.sparse_tensor_dense_matmul(R, gu_attention)), axis=1)
# print(self.R.shape)
print(atten_mat)
g_atten_embeddings = tf.matmul(atten_mat, user_embeddings)
return g_atten_embeddings
def graph_atten_v4(self, user_embeddings, R, gu_attention_vert, gu_attention_hori):
print('v4 used.')
R = self._convert_sp_mat_to_sp_tensor(R)
# gu_attention = tf.matmul(gu_attention_vert, gu_attention_hori)
# gu_attention = tf.nn.sigmoid(tf.matmul(gu_attention_vert, gu_attention_hori))
# gu_attention = tf.nn.softmax(tf.matmul(tf.nn.softmax(gu_attention_vert,axis = 1), tf.nn.softmax(gu_attention_hori,axis = 0)),axis=0)
if args.att_norm == 0:
gu_attention = tf.nn.softmax(tf.matmul(gu_attention_vert, gu_attention_hori), axis=0)
else:
gu_attention = tf.matmul(gu_attention_vert, gu_attention_hori)
# gu_attention = tf.nn.tanh(tf.matmul(gu_attention_vert, gu_attention_hori))
# atten_mat = tf.nn.softmax(tf.nn.relu(tf.sparse_tensor_dense_matmul(R, gu_attention)), axis=1)
# atten_mat = tf.nn.softmax(tf.sparse_tensor_dense_matmul(R, gu_attention), axis=1)
atten_mat = tf.nn.softmax(tf.nn.leaky_relu(tf.sparse_tensor_dense_matmul(R, gu_attention), alpha=0.2), axis=1)
# print(self.R.shape)
print(atten_mat)
g_atten_embeddings = tf.matmul(atten_mat, user_embeddings)
return g_atten_embeddings
def graph_atten_v2(self, user_embeddings, gu_attention):
'''
:param user_embeddings: UxD
:param R: GxU
:param gu_attention:UxU
:return: GxD
'''
return tf.sparse_tensor_dense_matmul(gu_attention, user_embeddings)
def graph_atten_v3(self, user_embeddings, gu_attention):
print('v3 used')
g_atten_embeddings = tf.matmul(gu_attention, user_embeddings)
return g_atten_embeddings
def graph_conv(self, A_fold_hat, n_layers, ego_embeddings):
all_embeddings = [ego_embeddings]
for k in range(0, n_layers):
temp_embed = []
for f in range(self.n_fold):
# print(A_fold_hat[f].shape, ego_embeddings.shape)
temp_embed.append(tf.sparse_tensor_dense_matmul(A_fold_hat[f], ego_embeddings))
side_embeddings = tf.concat(temp_embed, 0)
ego_embeddings = side_embeddings
all_embeddings += [ego_embeddings]
all_embeddings = tf.stack(all_embeddings, 1)
# print(all_embeddings.shape)
all_embeddings = tf.reduce_mean(all_embeddings, axis=1, keepdims=False)
# print(all_embeddings.shape)
# sys.exit(0)
return all_embeddings
def _create_lightgcn_embed_general(self):
if self.node_dropout_flag:
A_fold_hat = self._split_A_hat_node_dropout_general(self.n_groups, self.n_users, self.norm_adj)
A_fold_hat_gi = self._split_A_hat_node_dropout_general(self.n_groups, self.n_items, self.norm_adj_gi)
if self.gi_side == 1:
A_fold_hat_ui = self._split_A_hat_node_dropout_general(self.n_users, self.n_items, self.norm_adj_ui)
else:
A_fold_hat = self._split_A_hat_general(self.n_groups, self.n_users, self.norm_adj)
A_fold_hat_gi = self._split_A_hat_general(self.n_groups, self.n_items, self.norm_adj_gi)
if self.gi_side == 1:
A_fold_hat_ui = self._split_A_hat_general(self.n_users, self.n_items, self.norm_adj_ui)
if self.gat_type in ['user_side', 'both_side']:
if self.att_ver == 1: # one matrix
atten_embedding = self.graph_atten(self.weights['user_embedding'], self.R, self.gu_attention)
elif self.att_ver == 2: # GAT_mode
atten_embedding = self.graph_atten_v2(self.weights['user_embedding'], self.gu_attention_v2)
elif self.att_ver == 3:
atten_embedding = self.graph_atten_v3(self.weights['user_embedding'], self.gu_attention)
elif self.att_ver == 4:
atten_embedding = self.graph_atten_v4(self.weights['user_embedding'], self.R, self.gu_attention_vert,
self.gu_attention_hori)
elif self.att_ver == 5: # two embedding. M2 is transpose of M1
atten_embedding = self.graph_atten_v4(self.weights['user_embedding'], self.R, self.gu_attention_vert,
tf.transpose(self.gu_attention_vert))
elif self.att_ver == 6:
# print(self.gu_attention_vert.shape)
# print(self.weights['user_embedding'].shape)
# sys.exit(0)
atten_embedding = self.graph_atten_v4(self.weights['user_embedding'], self.R,
self.weights['user_embedding'],
tf.transpose(self.weights['user_embedding']))
if self.att_concat:
group_embedding = tf.concat([self.weights['group_embedding'], atten_embedding], axis=1)
all_embeddings = self.graph_conv(A_fold_hat, self.n_layers,
tf.concat([group_embedding, tf.concat(
[self.weights['user_embedding'], self.weights['user_embedding']],
axis=1)], axis=0))
else:
if args.att_norm == 0:
group_embedding = self.weights['group_embedding'] + self.att_coef * atten_embedding
else:
group_embedding = tf.nn.l2_normalize(self.weights['group_embedding'] + self.att_coef * atten_embedding,axis=1)
all_embeddings = self.graph_conv(A_fold_hat, self.n_layers,
tf.concat([group_embedding, self.weights['user_embedding']], axis=0))
else:
all_embeddings = self.graph_conv(A_fold_hat, self.n_layers,
tf.concat(
[self.weights['group_embedding'], self.weights['user_embedding']],
axis=0))
g_u_embeddings, u_g_embeddings = tf.split(all_embeddings, [self.n_groups, self.n_users], 0)
# print(g_u_embeddings.shape, u_g_embeddings.shape)
if self.gat_type in ['item_side', 'both_side']:
if self.att_ver == 1:
atten_embedding_gi = self.graph_atten(self.weights['item_embedding'], self.R_gi, self.gi_attention)
elif self.att_ver == 2:
atten_embedding_gi = self.graph_atten_v2(self.weights['item_embedding'], self.gi_attention_v2)
elif self.att_ver == 3:
atten_embedding_gi = self.graph_atten_v3(self.weights['item_embedding'], self.gi_attention)
elif self.att_ver == 4:
atten_embedding_gi = self.graph_atten_v4(self.weights['item_embedding'], self.R_gi,
self.gi_attention_vert, self.gi_attention_hori)
elif self.att_ver == 5:
atten_embedding_gi = self.graph_atten_v4(self.weights['item_embedding'], self.R_gi,
self.gi_attention_vert, tf.transpose(self.gi_attention_vert))
elif self.att_ver == 6:
atten_embedding_gi = self.graph_atten_v4(self.weights['item_embedding'], self.R_gi,
self.weights['item_embedding'],
tf.transpose(self.weights['item_embedding']))
if self.att_concat:
group_embedding_gi = tf.concat([self.weights['group_embedding'], atten_embedding_gi], axis=1)
all_embeddings_gi = self.graph_conv(A_fold_hat_gi, self.n_layers,
tf.concat([group_embedding_gi, tf.concat(
[self.weights['item_embedding'],
self.weights['item_embedding']], axis=1)],
axis=0))
else:
if args.att_norm == 0:
group_embedding_gi = self.weights['group_embedding'] + self.att_coef * atten_embedding_gi
else:
group_embedding_gi = tf.nn.l2_normalize(self.weights['group_embedding'] + self.att_coef * atten_embedding_gi,axis=1)
all_embeddings_gi = self.graph_conv(A_fold_hat_gi, self.n_layers,
tf.concat([group_embedding_gi, self.weights['item_embedding']],
axis=0))
else:
all_embeddings_gi = self.graph_conv(A_fold_hat_gi, self.n_layers,
tf.concat(
[self.weights['group_embedding'], self.weights['item_embedding']],
axis=0))
g_i_embeddings, i_g_embeddings = tf.split(all_embeddings_gi, [self.n_groups, self.n_items], 0)
# print(g_i_embeddings.shape, i_g_embeddings.shape)
if self.gi_side == 1:
if self.att_concat:
all_embeddings_ui = self.graph_conv(A_fold_hat_ui, self.n_layers,
tf.concat([tf.concat([self.weights['user_embedding'],
self.weights['user_embedding']], axis=1),
tf.concat([self.weights['item_embedding'],
self.weights['item_embedding']], axis=1)],
axis=0))
else:
all_embeddings_ui = self.graph_conv(A_fold_hat_ui, self.n_layers,
tf.concat([self.weights['user_embedding'],
self.weights['item_embedding']],
axis=0))
u_i_embeddings, i_u_embeddings = tf.split(all_embeddings_ui, [self.n_users, self.n_items], 0)
u_embeddings = tf.concat([u_g_embeddings, u_i_embeddings], 1)
g_embeddings = tf.concat([g_u_embeddings, g_i_embeddings], 1)
i_embeddings = tf.concat([i_g_embeddings, i_u_embeddings], 1)
elif self.gi_side == 0:
u_embeddings = tf.concat([u_g_embeddings, tf.ones_like(u_g_embeddings, dtype=tf.float32)], 1)
g_embeddings = tf.concat([g_u_embeddings, g_i_embeddings], 1)
i_embeddings = tf.concat([i_g_embeddings, tf.ones_like(i_g_embeddings, dtype=tf.float32)], 1)
# print(g_embeddings.shape, u_embeddings.shape)
# sys.exit(0)
return g_embeddings, u_embeddings, i_embeddings
def _create_lightgcn_embed(self):
if self.node_dropout_flag:
A_fold_hat = self._split_A_hat_node_dropout(self.norm_adj)
else:
A_fold_hat = self._split_A_hat(self.norm_adj)
ego_embeddings = tf.concat([self.weights['group_embedding'], self.weights['user_embedding']], axis=0)
all_embeddings = [ego_embeddings]
for k in range(0, self.n_layers):
temp_embed = []
for f in range(self.n_fold):
temp_embed.append(tf.sparse_tensor_dense_matmul(A_fold_hat[f], ego_embeddings))
side_embeddings = tf.concat(temp_embed, 0)
ego_embeddings = side_embeddings
all_embeddings += [ego_embeddings]
all_embeddings = tf.stack(all_embeddings, 1)
all_embeddings = tf.reduce_mean(all_embeddings, axis=1, keepdims=False)
g_g_embeddings, u_g_embeddings = tf.split(all_embeddings, [self.n_groups, self.n_users], 0)
return g_g_embeddings, u_g_embeddings
def _create_ngcf_embed(self):
if self.node_dropout_flag:
A_fold_hat = self._split_A_hat_node_dropout(self.norm_adj)
else:
A_fold_hat = self._split_A_hat(self.norm_adj)
ego_embeddings = tf.concat([self.weights['group_embedding'], self.weights['user_embedding']], axis=0)
all_embeddings = [ego_embeddings]
for k in range(0, self.n_layers):
temp_embed = []
for f in range(self.n_fold):
temp_embed.append(tf.sparse_tensor_dense_matmul(A_fold_hat[f], ego_embeddings))
side_embeddings = tf.concat(temp_embed, 0)
sum_embeddings = tf.nn.leaky_relu(
tf.matmul(side_embeddings, self.weights['W_gc_%d' % k]) + self.weights['b_gc_%d' % k])
# bi messages of neighbors.
bi_embeddings = tf.multiply(ego_embeddings, side_embeddings)
# transformed bi messages of neighbors.
bi_embeddings = tf.nn.leaky_relu(
tf.matmul(bi_embeddings, self.weights['W_bi_%d' % k]) + self.weights['b_bi_%d' % k])
# non-linear activation.
ego_embeddings = sum_embeddings + bi_embeddings
# message dropout.
# ego_embeddings = tf.nn.dropout(ego_embeddings, 1 - self.mess_dropout[k])
# normalize the distribution of embeddings.
norm_embeddings = tf.nn.l2_normalize(ego_embeddings, axis=1)
all_embeddings += [norm_embeddings]
all_embeddings = tf.concat(all_embeddings, 1)
g_g_embeddings, u_g_embeddings = tf.split(all_embeddings, [self.n_groups, self.n_users], 0)
return g_g_embeddings, u_g_embeddings
def _create_gcn_embed(self):
A_fold_hat = self._split_A_hat(self.norm_adj)
embeddings = tf.concat([self.weights['group_embedding'], self.weights['user_embedding']], axis=0)
all_embeddings = [embeddings]
for k in range(0, self.n_layers):
temp_embed = []
for f in range(self.n_fold):
temp_embed.append(tf.sparse_tensor_dense_matmul(A_fold_hat[f], embeddings))
embeddings = tf.concat(temp_embed, 0)
embeddings = tf.nn.leaky_relu(
tf.matmul(embeddings, self.weights['W_gc_%d' % k]) + self.weights['b_gc_%d' % k])
# embeddings = tf.nn.dropout(embeddings, 1 - self.mess_dropout[k])
all_embeddings += [embeddings]
all_embeddings = tf.concat(all_embeddings, 1)
g_g_embeddings, u_g_embeddings = tf.split(all_embeddings, [self.n_groups, self.n_users], 0)
return g_g_embeddings, u_g_embeddings
def _create_gcmc_embed(self):
A_fold_hat = self._split_A_hat(self.norm_adj)
embeddings = tf.concat([self.weights['group_embedding'], self.weights['user_embedding']], axis=0)
all_embeddings = []
for k in range(0, self.n_layers):
temp_embed = []
for f in range(self.n_fold):
temp_embed.append(tf.sparse_tensor_dense_matmul(A_fold_hat[f], embeddings))
embeddings = tf.concat(temp_embed, 0)
# convolutional layer.
embeddings = tf.nn.leaky_relu(
tf.matmul(embeddings, self.weights['W_gc_%d' % k]) + self.weights['b_gc_%d' % k])
# dense layer.
mlp_embeddings = tf.matmul(embeddings, self.weights['W_mlp_%d' % k]) + self.weights['b_mlp_%d' % k]
# mlp_embeddings = tf.nn.dropout(mlp_embeddings, 1 - self.mess_dropout[k])
all_embeddings += [mlp_embeddings]
all_embeddings = tf.concat(all_embeddings, 1)
g_g_embeddings, u_g_embeddings = tf.split(all_embeddings, [self.n_groups, self.n_users], 0)
return g_g_embeddings, u_g_embeddings
def create_bpr_loss(self, groups, pos_users, neg_users):
# print(groups.shape,pos_users.shape, neg_users.shape ,items.shape)
# groups = tf.nn.l2_normalize(groups, 1)
# pos_users = tf.nn.l2_normalize(pos_users, 1)
# neg_users = tf.nn.l2_normalize(neg_users, 1)
pos_scores = tf.reduce_sum(tf.multiply(groups, pos_users), axis=1)
neg_scores = tf.reduce_sum(tf.multiply(groups, neg_users), axis=1)
# pos_item_scores = tf.reduce_sum(tf.multiply(tf.multiply(groups, pos_users),items), axis=1)
regularizer = tf.nn.l2_loss(self.g_g_embeddings_pre) + tf.nn.l2_loss(
self.pos_u_g_embeddings_pre) + tf.nn.l2_loss(self.neg_u_g_embeddings_pre)
# if self.aug_type == 5:
# regularizer = tf.nn.l2_loss(self.g_g_embeddings_pre) + tf.nn.l2_loss(
# self.pos_u_g_embeddings_pre) + tf.nn.l2_loss(self.neg_u_g_embeddings_pre) \
# + tf.nn.l2_loss(self.gu_atten_embeddings) + tf.nn.l2_loss(self.gi_atten_embeddings)
regularizer = regularizer / self.batch_size
if self.aug_type != -1:
mf_loss = tf.reduce_mean(tf.nn.sigmoid(-(pos_scores - neg_scores)))
else:
mf_loss = tf.reduce_mean(tf.nn.softplus(-(pos_scores - neg_scores)))
emb_loss = self.decay * regularizer
reg_loss = tf.constant(0.0, tf.float32, [1])
return mf_loss, emb_loss, reg_loss
def _convert_sp_mat_to_sp_tensor(self, X):
coo = X.tocoo().astype(np.float32)
# print(coo.toarray().shape)
indices = np.mat([coo.row, coo.col]).transpose()
return tf.SparseTensor(indices, coo.data, coo.shape)
def _convert_csr_to_sparse_tensor_inputs(self, X):
coo = X.tocoo()
indices = np.mat([coo.row, coo.col]).transpose()
return indices, coo.data, coo.shape
def _dropout_sparse(self, X, keep_prob, n_nonzero_elems):
"""
Dropout for sparse tensors.
"""
noise_shape = [n_nonzero_elems]
random_tensor = keep_prob
random_tensor += tf.random_uniform(noise_shape)
dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool)
pre_out = tf.sparse_retain(X, dropout_mask)
return pre_out * tf.div(1., keep_prob)
def load_pretrained_data():
pretrain_path = '%spretrain/%s/%s.npz' % (args.proj_path, args.dataset, 'embedding')
try:
pretrain_data = np.load(pretrain_path)
print('load the pretrained embeddings.')
except Exception:
pretrain_data = None
return pretrain_data
# parallelized sampling on CPU
class sample_thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
with tf.device(cpus[0]):
self.data = data_generator.sample()
class sample_thread_test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
with tf.device(cpus[0]):
self.data = data_generator.sample_test()
# training on GPU
class train_thread(threading.Thread):
def __init__(self, model, sess, sample, sub_mat=None):
threading.Thread.__init__(self)
self.model = model
self.sess = sess
self.sample = sample
self.sub_mat = sub_mat
def run(self):
groups, pos_users, neg_users = self.sample.data
feed_dict = {model.groups: groups, model.pos_users: pos_users,
model.node_dropout: eval(args.node_dropout),
model.mess_dropout: eval(args.mess_dropout),
model.neg_users: neg_users,
model.train: True}
if self.model.aug_type != -1:
if self.model.aug_type in [0, 1]:
feed_dict.update({
self.model.sub_mat['adj_values_sub1']: self.sub_mat['adj_values_sub1'],
self.model.sub_mat['adj_indices_sub1']: self.sub_mat['adj_indices_sub1'],
self.model.sub_mat['adj_shape_sub1']: self.sub_mat['adj_shape_sub1'],
self.model.sub_mat['adj_values_sub2']: self.sub_mat['adj_values_sub2'],
self.model.sub_mat['adj_indices_sub2']: self.sub_mat['adj_indices_sub2'],
self.model.sub_mat['adj_shape_sub2']: self.sub_mat['adj_shape_sub2']
})
else:
for k in range(1, self.model.n_layers + 1):
feed_dict.update({
self.model.sub_mat['adj_values_sub1%d' % k]: self.sub_mat['adj_values_sub1%d' % k],
self.model.sub_mat['adj_indices_sub1%d' % k]: self.sub_mat['adj_indices_sub1%d' % k],
self.model.sub_mat['adj_shape_sub1%d' % k]: self.sub_mat['adj_shape_sub1%d' % k],
self.model.sub_mat['adj_values_sub2%d' % k]: self.sub_mat['adj_values_sub2%d' % k],
self.model.sub_mat['adj_indices_sub2%d' % k]: self.sub_mat['adj_indices_sub2%d' % k],
self.model.sub_mat['adj_shape_sub2%d' % k]: self.sub_mat['adj_shape_sub2%d' % k]
})
self.data = sess.run(
[self.model.opt, self.model.loss, self.model.mf_loss, self.model.emb_loss, self.model.reg_loss,
self.model.ssl_loss],
feed_dict=feed_dict)
class train_thread_test(threading.Thread):
def __init__(self, model, sess, sample, sub_mat=None):
threading.Thread.__init__(self)
self.model = model
self.sess = sess
self.sample = sample
self.sub_mat = sub_mat
def run(self):
groups, pos_users, neg_users = self.sample.data
feed_dict = {model.groups: groups, model.pos_users: pos_users,
model.node_dropout: eval(args.node_dropout),
model.mess_dropout: eval(args.mess_dropout),
model.neg_users: neg_users,
model.train: False}
if self.model.aug_type != -1:
if self.model.aug_type in [0, 1]:
feed_dict.update({
self.model.sub_mat['adj_values_sub1']: self.sub_mat['adj_values_sub1'],
self.model.sub_mat['adj_indices_sub1']: self.sub_mat['adj_indices_sub1'],
self.model.sub_mat['adj_shape_sub1']: self.sub_mat['adj_shape_sub1'],
self.model.sub_mat['adj_values_sub2']: self.sub_mat['adj_values_sub2'],
self.model.sub_mat['adj_indices_sub2']: self.sub_mat['adj_indices_sub2'],
self.model.sub_mat['adj_shape_sub2']: self.sub_mat['adj_shape_sub2']
})
else:
for k in range(1, self.model.n_layers + 1):
feed_dict.update({
self.model.sub_mat['adj_values_sub1%d' % k]: self.sub_mat['adj_values_sub1%d' % k],
self.model.sub_mat['adj_indices_sub1%d' % k]: self.sub_mat['adj_indices_sub1%d' % k],
self.model.sub_mat['adj_shape_sub1%d' % k]: self.sub_mat['adj_shape_sub1%d' % k],
self.model.sub_mat['adj_values_sub2%d' % k]: self.sub_mat['adj_values_sub2%d' % k],
self.model.sub_mat['adj_indices_sub2%d' % k]: self.sub_mat['adj_indices_sub2%d' % k],
self.model.sub_mat['adj_shape_sub2%d' % k]: self.sub_mat['adj_shape_sub2%d' % k]
})
self.data = sess.run([self.model.loss, self.model.mf_loss, self.model.emb_loss, self.model.ssl_loss],
feed_dict=feed_dict)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id)
f0 = time()
config = dict()
config['n_groups'] = data_generator.n_groups
config['n_users'] = data_generator.n_users
config['n_items'] = data_generator.n_items
config['R'] = data_generator.R
config['R_gi'] = data_generator.R_gi
"""
*********************************************************
Generate the Laplacian matrix, where each entry defines the decay factor (e.g., p_ui) between two connected nodes.
"""
plain_adj, norm_adj, mean_adj, pre_adj, plain_adj_gi, norm_adj_gi, mean_adj_gi, pre_adj_gi, plain_adj_ui, norm_adj_ui, mean_adj_ui, pre_adj_ui = data_generator.get_adj_mat()
if args.adj_type == 'plain':
config['norm_adj'] = plain_adj
config['norm_adj_gi'] = plain_adj_gi
config['norm_adj_ui'] = plain_adj_ui
print('use the plain adjacency matrix')
elif args.adj_type == 'norm':