-
Notifications
You must be signed in to change notification settings - Fork 3
/
pagagcn_solver_bce.py
174 lines (146 loc) · 8.39 KB
/
pagagcn_solver_bce.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
import argparse
import torch
import os
import numpy as np
import random as rd
from graph_recsys_benchmark.models import PAGAGCNRecsysModel
from graph_recsys_benchmark.utils import get_folder_path
from graph_recsys_benchmark.solvers import BaseSolver
MODEL_TYPE = 'Graph'
LOSS_TYPE = 'BCE'
MODEL = 'PAPAGCN'
parser = argparse.ArgumentParser()
# Dataset params
parser.add_argument("--dataset", type=str, default='Movielens', help="")
parser.add_argument("--dataset_name", type=str, default='1m', help="")
parser.add_argument("--if_use_features", type=bool, default=False, help="")
parser.add_argument("--num_core", type=int, default=10, help="")
parser.add_argument("--num_feat_core", type=int, default=10, help="")
# Model params
parser.add_argument("--dropout", type=float, default=0, help="")
parser.add_argument("--emb_dim", type=int, default=64, help="")
parser.add_argument("--repr_dim", type=int, default=16, help="")
parser.add_argument("--hidden_size", type=int, default=64, help="")
parser.add_argument("--meta_path_steps", type=list, default=[2, 2, 2, 2, 2, 2, 2], help="")
parser.add_argument("--aggr", type=str, default='concat', help="")
# Train params
parser.add_argument("--init_eval", type=bool, default=True, help="")
parser.add_argument("--num_negative_samples", type=int, default=4, help="")
parser.add_argument("--num_neg_candidates", type=int, default=99, help="")
parser.add_argument("--device", type=str, default='cuda', help="")
parser.add_argument("--gpu_idx", type=str, default='6', help="")
parser.add_argument("--runs", type=int, default=100, help="")
parser.add_argument("--epochs", type=int, default=50, help="")
parser.add_argument("--batch_size", type=int, default=4096, help="")
parser.add_argument("--num_workers", type=int, default=4, help="")
parser.add_argument("--opt", type=str, default='adam', help="")
parser.add_argument("--lr", type=float, default=0.001, help="")
parser.add_argument("--weight_decay", type=float, default=0, help="")
parser.add_argument("--early_stopping", type=int, default=20, help="")
parser.add_argument("--save_epochs", type=list, default=[10, 15, 20], help="")
parser.add_argument("--save_every_epoch", type=int, default=20, help="")
args = parser.parse_args()
# Setup data and weights file path
data_folder, weights_folder, logger_folder = \
get_folder_path(model=MODEL, dataset=args.dataset + args.dataset_name, loss_type=LOSS_TYPE)
# Setup device
if not torch.cuda.is_available() or args.device == 'cpu':
device = 'cpu'
else:
device = 'cuda:{}'.format(args.gpu_idx)
# Setup args
dataset_args = {
'root': data_folder, 'dataset': args.dataset, 'name': args.dataset_name,
'if_use_features': args.if_use_features, 'num_negative_samples': args.num_negative_samples,
'num_core': args.num_core, 'num_feat_core': args.num_feat_core,
'loss_type': LOSS_TYPE
}
model_args = {
'model_type': MODEL_TYPE,
'if_use_features': args.if_use_features,
'emb_dim': args.emb_dim, 'hidden_size': args.hidden_size,
'repr_dim': args.repr_dim, 'dropout': args.dropout,
'meta_path_steps': args.meta_path_steps, 'aggr': args.aggr
}
train_args = {
'init_eval': args.init_eval,
'num_negative_samples': args.num_negative_samples, 'num_neg_candidates': args.num_neg_candidates,
'opt': args.opt,
'runs': args.runs, 'epochs': args.epochs, 'batch_size': args.batch_size,
'num_workers': args.num_workers,
'weight_decay': args.weight_decay, 'lr': args.lr, 'device': device,
'weights_folder': os.path.join(weights_folder, str(model_args)),
'logger_folder': os.path.join(logger_folder, str(model_args)),
'save_epochs': args.save_epochs, 'save_every_epoch': args.save_every_epoch
}
print('dataset params: {}'.format(dataset_args))
print('task params: {}'.format(model_args))
print('train params: {}'.format(train_args))
def _negative_sampling(u_nid, num_negative_samples, train_splition, item_nid_occs):
"""
The negative sampling methods used for generating the training batches
:param u_nid:
:return:
"""
train_pos_unid_inid_map, test_pos_unid_inid_map, neg_unid_inid_map = train_splition
# negative_inids = test_pos_unid_inid_map[u_nid] + neg_unid_inid_map[u_nid]
# nid_occs = np.array([item_nid_occs[nid] for nid in negative_inids])
# nid_occs = nid_occs / np.sum(nid_occs)
# negative_inids = rd.choices(population=negative_inids, weights=nid_occs, k=num_negative_samples)
# negative_inids = negative_inids
negative_inids = test_pos_unid_inid_map[u_nid] + neg_unid_inid_map[u_nid]
negative_inids = rd.choices(population=negative_inids, k=num_negative_samples)
return negative_inids
class PAGAGCNRecsysModel(PAGAGCNRecsysModel):
loss_func = torch.nn.BCEWithLogitsLoss()
def loss(self, batch):
if self.training:
self.cached_repr = self.forward()
pred = self.predict(batch[:, 0], batch[:, 1]).reshape(-1)
label = batch[:, -1].float()
else:
pos_pred = self.predict(batch[:, 0], batch[:, 1])[:1].reshape(-1)
neg_pred = self.predict(batch[:, 0], batch[:, 2]).reshape(-1)
pred = torch.cat([pos_pred, neg_pred])
label = torch.cat([torch.ones_like(pos_pred), torch.zeros_like(neg_pred)]).float()
loss = self.loss_func(pred, label)
return loss
def update_graph_input(self, dataset):
user2item_edge_index = torch.from_numpy(dataset.edge_index_nps['user2item']).long().to(train_args['device'])
year2item_edge_index = torch.from_numpy(dataset.edge_index_nps['year2item']).long().to(train_args['device'])
actor2item_edge_index = torch.from_numpy(dataset.edge_index_nps['actor2item']).long().to(train_args['device'])
director2item_edge_index = torch.from_numpy(dataset.edge_index_nps['director2item']).long().to(train_args['device'])
writer2item_edge_index = torch.from_numpy(dataset.edge_index_nps['writer2item']).long().to(train_args['device'])
genre2item_edge_index = torch.from_numpy(dataset.edge_index_nps['genre2item']).long().to(train_args['device'])
age2user_edge_index = torch.from_numpy(dataset.edge_index_nps['age2user']).long().to(train_args['device'])
gender2user_edge_index = torch.from_numpy(dataset.edge_index_nps['gender2user']).long().to(train_args['device'])
occ2user_edge_index = torch.from_numpy(dataset.edge_index_nps['occ2user']).long().to(train_args['device'])
meta_path_edge_indicis_1 = [user2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_2 = [torch.flip(user2item_edge_index, dims=[0]), user2item_edge_index]
meta_path_edge_indicis_3 = [year2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_4 = [actor2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_5 = [writer2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_6 = [director2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_7 = [genre2item_edge_index, torch.flip(user2item_edge_index, dims=[0])]
meta_path_edge_indicis_8 = [gender2user_edge_index, user2item_edge_index]
meta_path_edge_indicis_9 = [age2user_edge_index, user2item_edge_index]
meta_path_edge_indicis_10 = [occ2user_edge_index, user2item_edge_index]
meta_path_edge_index_list = [
meta_path_edge_indicis_1, meta_path_edge_indicis_2, meta_path_edge_indicis_3,
meta_path_edge_indicis_4, meta_path_edge_indicis_5, meta_path_edge_indicis_6,
meta_path_edge_indicis_7, meta_path_edge_indicis_8, meta_path_edge_indicis_9,
meta_path_edge_indicis_10
]
return self.x, meta_path_edge_index_list
class PAGAGCNSolver(BaseSolver):
def __init__(self, model_class, dataset_args, model_args, train_args):
super(PAGAGCNSolver, self).__init__(model_class, dataset_args, model_args, train_args)
def generate_candidates(self, dataset, u_nid):
pos_i_nids = dataset.test_pos_unid_inid_map[u_nid]
neg_i_nids = np.array(dataset.neg_unid_inid_map[u_nid])
neg_i_nids_indices = np.array(rd.sample(range(neg_i_nids.shape[0]), train_args['num_neg_candidates']), dtype=int)
return pos_i_nids, list(neg_i_nids[neg_i_nids_indices])
if __name__ == '__main__':
dataset_args['_negative_sampling'] = _negative_sampling
solver = PAGAGCNSolver(PAGAGCNRecsysModel, dataset_args, model_args, train_args)
solver.run()