-
Notifications
You must be signed in to change notification settings - Fork 14
/
new_main.py
192 lines (182 loc) · 9.1 KB
/
new_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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/17 4:32
# @Author : ZM7
# @File : new_main
# @Software: PyCharm
import datetime
import torch
from sys import exit
import pandas as pd
import numpy as np
from DGSR import DGSR, collate, collate_test
from dgl import load_graphs
import pickle
from utils import myFloder
import warnings
import argparse
import os
import sys
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import torch.nn as nn
from DGSR_utils import eval_metric, mkdir_if_not_exist, Logger
warnings.filterwarnings('ignore')
parser = argparse.ArgumentParser()
parser.add_argument('--data', default='sample', help='data name: sample')
parser.add_argument('--batchSize', type=int, default=50, help='input batch size')
parser.add_argument('--hidden_size', type=int, default=50, help='hidden state size')
parser.add_argument('--epoch', type=int, default=10, help='number of epochs to train for')
parser.add_argument('--lr', type=float, default=0.001, help='learning rate')
parser.add_argument('--l2', type=float, default=0.0001, help='l2 penalty')
parser.add_argument('--user_update', default='rnn')
parser.add_argument('--item_update', default='rnn')
parser.add_argument('--user_long', default='orgat')
parser.add_argument('--item_long', default='orgat')
parser.add_argument('--user_short', default='att')
parser.add_argument('--item_short', default='att')
parser.add_argument('--feat_drop', type=float, default=0.3, help='drop_out')
parser.add_argument('--attn_drop', type=float, default=0.3, help='drop_out')
parser.add_argument('--layer_num', type=int, default=3, help='GNN layer')
parser.add_argument('--item_max_length', type=int, default=50, help='the max length of item sequence')
parser.add_argument('--user_max_length', type=int, default=50, help='the max length of use sequence')
parser.add_argument('--k_hop', type=int, default=2, help='sub-graph size')
parser.add_argument('--gpu', default='4')
parser.add_argument('--last_item', action='store_true', help='aggreate last item')
parser.add_argument("--record", action='store_true', default=False, help='record experimental results')
parser.add_argument("--val", action='store_true', default=False)
parser.add_argument("--model_record", action='store_true', default=False, help='record model')
opt = parser.parse_args()
args, extras = parser.parse_known_args()
os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu
device = torch.device('cuda:0')
print(opt)
if opt.record:
log_file = f'results/{opt.data}_ba_{opt.batchSize}_G_{opt.gpu}_dim_{opt.hidden_size}_ulong_{opt.user_long}_ilong_{opt.item_long}_' \
f'US_{opt.user_short}_IS_{opt.item_short}_La_{args.last_item}_UM_{opt.user_max_length}_IM_{opt.item_max_length}_K_{opt.k_hop}' \
f'_layer_{opt.layer_num}_l2_{opt.l2}'
mkdir_if_not_exist(log_file)
sys.stdout = Logger(log_file)
print(f'Logging to {log_file}')
if opt.model_record:
model_file = f'{opt.data}_ba_{opt.batchSize}_G_{opt.gpu}_dim_{opt.hidden_size}_ulong_{opt.user_long}_ilong_{opt.item_long}_' \
f'US_{opt.user_short}_IS_{opt.item_short}_La_{args.last_item}_UM_{opt.user_max_length}_IM_{opt.item_max_length}_K_{opt.k_hop}' \
f'_layer_{opt.layer_num}_l2_{opt.l2}'
# loading data
data = pd.read_csv('./Data/' + opt.data + '.csv')
user = data['user_id'].unique()
item = data['item_id'].unique()
user_num = len(user)
item_num = len(item)
train_root = f'Newdata/{opt.data}_{opt.item_max_length}_{opt.user_max_length}_{opt.k_hop}/train/'
test_root = f'Newdata/{opt.data}_{opt.item_max_length}_{opt.user_max_length}_{opt.k_hop}/test/'
val_root = f'Newdata/{opt.data}_{opt.item_max_length}_{opt.user_max_length}_{opt.k_hop}/val/'
train_set = myFloder(train_root, load_graphs)
test_set = myFloder(test_root, load_graphs)
if opt.val:
val_set = myFloder(val_root, load_graphs)
print('train number:', train_set.size)
print('test number:', test_set.size)
print('user number:', user_num)
print('item number:', item_num)
f = open(opt.data+'_neg', 'rb')
data_neg = pickle.load(f) # 用于评估测试集
train_data = DataLoader(dataset=train_set, batch_size=opt.batchSize, collate_fn=collate, shuffle=True, pin_memory=True, num_workers=12)
test_data = DataLoader(dataset=test_set, batch_size=opt.batchSize, collate_fn=lambda x: collate_test(x, data_neg), pin_memory=True, num_workers=8)
if opt.val:
val_data = DataLoader(dataset=val_set, batch_size=opt.batchSize, collate_fn=lambda x: collate_test(x, data_neg), pin_memory=True, num_workers=2)
# 初始化模型
model = DGSR(user_num=user_num, item_num=item_num, input_dim=opt.hidden_size, item_max_length=opt.item_max_length,
user_max_length=opt.user_max_length, feat_drop=opt.feat_drop, attn_drop=opt.attn_drop, user_long=opt.user_long, user_short=opt.user_short,
item_long=opt.item_long, item_short=opt.item_short, user_update=opt.user_update, item_update=opt.item_update, last_item=opt.last_item,
layer_num=opt.layer_num).cuda()
optimizer = optim.Adam(model.parameters(), lr=opt.lr, weight_decay=opt.l2)
loss_func = nn.CrossEntropyLoss()
best_result = [0, 0, 0, 0, 0, 0] # hit5,hit10,hit20,mrr5,mrr10,mrr20
best_epoch = [0, 0, 0, 0, 0, 0]
stop_num = 0
for epoch in range(opt.epoch):
stop = True
epoch_loss = 0
iter = 0
print('start training: ', datetime.datetime.now())
model.train()
for user, batch_graph, label, last_item in train_data:
iter += 1
score = model(batch_graph.to(device), user.to(device), last_item.to(device), is_training=True)
loss = loss_func(score, label.to(device))
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_loss += loss.item()
if iter % 400 == 0:
print('Iter {}, loss {:.4f}'.format(iter, epoch_loss/iter), datetime.datetime.now())
epoch_loss /= iter
model.eval()
print('Epoch {}, loss {:.4f}'.format(epoch, epoch_loss), '=============================================')
# val
if opt.val:
print('start validation: ', datetime.datetime.now())
val_loss_all, top_val = [], []
with torch.no_grad:
for user, batch_graph, label, last_item, neg_tar in val_data:
score, top = model(batch_graph.to(device), user.to(device), last_item.to(device), neg_tar=torch.cat([label.unsqueeze(1), neg_tar], -1).to(device), is_training=False)
val_loss = loss_func(score, label.cuda())
val_loss_all.append(val_loss.append(val_loss.item()))
top_val.append(top.detach().cpu().numpy())
recall5, recall10, recall20, ndgg5, ndgg10, ndgg20 = eval_metric(top_val)
print('train_loss:%.4f\tval_loss:%.4f\tRecall@5:%.4f\tRecall@10:%.4f\tRecall@20:%.4f\tNDGG@5:%.4f'
'\tNDGG10@10:%.4f\tNDGG@20:%.4f' %
(epoch_loss, np.mean(val_loss_all), recall5, recall10, recall20, ndgg5, ndgg10, ndgg20))
# test
print('start predicting: ', datetime.datetime.now())
all_top, all_label, all_length = [], [], []
iter = 0
all_loss = []
with torch.no_grad():
for user, batch_graph, label, last_item, neg_tar in test_data:
iter+=1
score, top = model(batch_graph.to(device), user.to(device), last_item.to(device), neg_tar=torch.cat([label.unsqueeze(1), neg_tar],-1).to(device), is_training=False)
test_loss = loss_func(score, label.cuda())
all_loss.append(test_loss.item())
all_top.append(top.detach().cpu().numpy())
all_label.append(label.numpy())
if iter % 200 == 0:
print('Iter {}, test_loss {:.4f}'.format(iter, np.mean(all_loss)), datetime.datetime.now())
recall5, recall10, recall20, ndgg5, ndgg10, ndgg20 = eval_metric(all_top)
if recall5 > best_result[0]:
best_result[0] = recall5
best_epoch[0] = epoch
stop = False
if recall10 > best_result[1]:
if opt.model_record:
torch.save(model.state_dict(), 'save_models/'+ model_file + '.pkl')
best_result[1] = recall10
best_epoch[1] = epoch
stop = False
if recall20 > best_result[2]:
best_result[2] = recall20
best_epoch[2] = epoch
stop = False
# ------select Mrr------------------
if ndgg5 > best_result[3]:
best_result[3] = ndgg5
best_epoch[3] = epoch
stop = False
if ndgg10 > best_result[4]:
best_result[4] = ndgg10
best_epoch[4] = epoch
stop = False
if ndgg20 > best_result[5]:
best_result[5] = ndgg20
best_epoch[5] = epoch
stop = False
if stop:
stop_num += 1
else:
stop_num = 0
print('train_loss:%.4f\ttest_loss:%.4f\tRecall@5:%.4f\tRecall@10:%.4f\tRecall@20:%.4f\tNDGG@5:%.4f'
'\tNDGG10@10:%.4f\tNDGG@20:%.4f\tEpoch:%d,%d,%d,%d,%d,%d' %
(epoch_loss, np.mean(all_loss), best_result[0], best_result[1], best_result[2], best_result[3],
best_result[4], best_result[5], best_epoch[0], best_epoch[1],
best_epoch[2], best_epoch[3], best_epoch[4], best_epoch[5]))