-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.py
209 lines (178 loc) · 7.34 KB
/
main.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
import numpy as np
import torch
import pickle
from model import LightGCL
from utils import metrics, scipy_sparse_mat_to_torch_sparse_tensor
import pandas as pd
from parser import args
from tqdm import tqdm
import time
import torch.utils.data as data
from utils import TrnData
device = 'cuda:' + args.cuda
# hyperparameters
d = args.d
l = args.gnn_layer
temp = args.temp
batch_user = args.batch
epoch_no = args.epoch
max_samp = 40
lambda_1 = args.lambda1
lambda_2 = args.lambda2
dropout = args.dropout
lr = args.lr
decay = args.decay
svd_q = args.q
# load data
path = 'data/' + args.data + '/'
f = open(path+'trnMat.pkl','rb')
train = pickle.load(f)
train_csr = (train!=0).astype(np.float32)
f = open(path+'tstMat.pkl','rb')
test = pickle.load(f)
print('Data loaded.')
print('user_num:',train.shape[0],'item_num:',train.shape[1],'lambda_1:',lambda_1,'lambda_2:',lambda_2,'temp:',temp,'q:',svd_q)
epoch_user = min(train.shape[0], 30000)
# normalizing the adj matrix
rowD = np.array(train.sum(1)).squeeze()
colD = np.array(train.sum(0)).squeeze()
for i in range(len(train.data)):
train.data[i] = train.data[i] / pow(rowD[train.row[i]]*colD[train.col[i]], 0.5)
# construct data loader
train = train.tocoo()
train_data = TrnData(train)
train_loader = data.DataLoader(train_data, batch_size=args.inter_batch, shuffle=True, num_workers=0)
adj_norm = scipy_sparse_mat_to_torch_sparse_tensor(train)
adj_norm = adj_norm.coalesce().cuda(torch.device(device))
print('Adj matrix normalized.')
# perform svd reconstruction
adj = scipy_sparse_mat_to_torch_sparse_tensor(train).coalesce().cuda(torch.device(device))
print('Performing SVD...')
svd_u,s,svd_v = torch.svd_lowrank(adj, q=svd_q)
u_mul_s = svd_u @ (torch.diag(s))
v_mul_s = svd_v @ (torch.diag(s))
del s
print('SVD done.')
# process test set
test_labels = [[] for i in range(test.shape[0])]
for i in range(len(test.data)):
row = test.row[i]
col = test.col[i]
test_labels[row].append(col)
print('Test data processed.')
loss_list = []
loss_r_list = []
loss_s_list = []
recall_20_x = []
recall_20_y = []
ndcg_20_y = []
recall_40_y = []
ndcg_40_y = []
model = LightGCL(adj_norm.shape[0], adj_norm.shape[1], d, u_mul_s, v_mul_s, svd_u.T, svd_v.T, train_csr, adj_norm, l, temp, lambda_1, lambda_2, dropout, batch_user, device)
#model.load_state_dict(torch.load('saved_model.pt'))
model.cuda(torch.device(device))
optimizer = torch.optim.Adam(model.parameters(),weight_decay=0,lr=lr)
#optimizer.load_state_dict(torch.load('saved_optim.pt'))
current_lr = lr
for epoch in range(epoch_no):
if (epoch+1)%50 == 0:
torch.save(model.state_dict(),'saved_model/saved_model_epoch_'+str(epoch)+'.pt')
torch.save(optimizer.state_dict(),'saved_model/saved_optim_epoch_'+str(epoch)+'.pt')
epoch_loss = 0
epoch_loss_r = 0
epoch_loss_s = 0
train_loader.dataset.neg_sampling()
for i, batch in enumerate(tqdm(train_loader)):
uids, pos, neg = batch
uids = uids.long().cuda(torch.device(device))
pos = pos.long().cuda(torch.device(device))
neg = neg.long().cuda(torch.device(device))
iids = torch.concat([pos, neg], dim=0)
# feed
optimizer.zero_grad()
loss, loss_r, loss_s= model(uids, iids, pos, neg)
loss.backward()
optimizer.step()
#print('batch',batch)
epoch_loss += loss.cpu().item()
epoch_loss_r += loss_r.cpu().item()
epoch_loss_s += loss_s.cpu().item()
torch.cuda.empty_cache()
#print(i, len(train_loader), end='\r')
batch_no = len(train_loader)
epoch_loss = epoch_loss/batch_no
epoch_loss_r = epoch_loss_r/batch_no
epoch_loss_s = epoch_loss_s/batch_no
loss_list.append(epoch_loss)
loss_r_list.append(epoch_loss_r)
loss_s_list.append(epoch_loss_s)
print('Epoch:',epoch,'Loss:',epoch_loss,'Loss_r:',epoch_loss_r,'Loss_s:',epoch_loss_s)
if epoch % 3 == 0: # test every 10 epochs
test_uids = np.array([i for i in range(adj_norm.shape[0])])
batch_no = int(np.ceil(len(test_uids)/batch_user))
all_recall_20 = 0
all_ndcg_20 = 0
all_recall_40 = 0
all_ndcg_40 = 0
for batch in tqdm(range(batch_no)):
start = batch*batch_user
end = min((batch+1)*batch_user,len(test_uids))
test_uids_input = torch.LongTensor(test_uids[start:end]).cuda(torch.device(device))
predictions = model(test_uids_input,None,None,None,test=True)
predictions = np.array(predictions.cpu())
#top@20
recall_20, ndcg_20 = metrics(test_uids[start:end],predictions,20,test_labels)
#top@40
recall_40, ndcg_40 = metrics(test_uids[start:end],predictions,40,test_labels)
all_recall_20+=recall_20
all_ndcg_20+=ndcg_20
all_recall_40+=recall_40
all_ndcg_40+=ndcg_40
#print('batch',batch,'recall@20',recall_20,'ndcg@20',ndcg_20,'recall@40',recall_40,'ndcg@40',ndcg_40)
print('-------------------------------------------')
print('Test of epoch',epoch,':','Recall@20:',all_recall_20/batch_no,'Ndcg@20:',all_ndcg_20/batch_no,'Recall@40:',all_recall_40/batch_no,'Ndcg@40:',all_ndcg_40/batch_no)
recall_20_x.append(epoch)
recall_20_y.append(all_recall_20/batch_no)
ndcg_20_y.append(all_ndcg_20/batch_no)
recall_40_y.append(all_recall_40/batch_no)
ndcg_40_y.append(all_ndcg_40/batch_no)
# final test
test_uids = np.array([i for i in range(adj_norm.shape[0])])
batch_no = int(np.ceil(len(test_uids)/batch_user))
all_recall_20 = 0
all_ndcg_20 = 0
all_recall_40 = 0
all_ndcg_40 = 0
for batch in range(batch_no):
start = batch*batch_user
end = min((batch+1)*batch_user,len(test_uids))
test_uids_input = torch.LongTensor(test_uids[start:end]).cuda(torch.device(device))
predictions = model(test_uids_input,None,None,None,test=True)
predictions = np.array(predictions.cpu())
#top@20
recall_20, ndcg_20 = metrics(test_uids[start:end],predictions,20,test_labels)
#top@40
recall_40, ndcg_40 = metrics(test_uids[start:end],predictions,40,test_labels)
all_recall_20+=recall_20
all_ndcg_20+=ndcg_20
all_recall_40+=recall_40
all_ndcg_40+=ndcg_40
#print('batch',batch,'recall@20',recall_20,'ndcg@20',ndcg_20,'recall@40',recall_40,'ndcg@40',ndcg_40)
print('-------------------------------------------')
print('Final test:','Recall@20:',all_recall_20/batch_no,'Ndcg@20:',all_ndcg_20/batch_no,'Recall@40:',all_recall_40/batch_no,'Ndcg@40:',all_ndcg_40/batch_no)
recall_20_x.append('Final')
recall_20_y.append(all_recall_20/batch_no)
ndcg_20_y.append(all_ndcg_20/batch_no)
recall_40_y.append(all_recall_40/batch_no)
ndcg_40_y.append(all_ndcg_40/batch_no)
metric = pd.DataFrame({
'epoch':recall_20_x,
'recall@20':recall_20_y,
'ndcg@20':ndcg_20_y,
'recall@40':recall_40_y,
'ndcg@40':ndcg_40_y
})
current_t = time.gmtime()
metric.to_csv('log/result_'+args.data+'_'+time.strftime('%Y-%m-%d-%H',current_t)+'.csv')
torch.save(model.state_dict(),'saved_model/saved_model_'+args.data+'_'+time.strftime('%Y-%m-%d-%H',current_t)+'.pt')
torch.save(optimizer.state_dict(),'saved_model/saved_optim_'+args.data+'_'+time.strftime('%Y-%m-%d-%H',current_t)+'.pt')