-
Notifications
You must be signed in to change notification settings - Fork 47
/
main.py
146 lines (117 loc) · 4.91 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
'''
Created on July 1, 2020
@author: Tinglin Huang ([email protected])
'''
__author__ = "huangtinglin"
import random
import torch
import numpy as np
from time import time
from prettytable import PrettyTable
from utils.parser import parse_args
from utils.data_loader import load_data
from modules.KGIN import Recommender
from utils.evaluate import test
from utils.helper import early_stopping
n_users = 0
n_items = 0
n_entities = 0
n_nodes = 0
n_relations = 0
def get_feed_dict(train_entity_pairs, start, end, train_user_set):
def negative_sampling(user_item, train_user_set):
neg_items = []
for user, _ in user_item.cpu().numpy():
user = int(user)
while True:
neg_item = np.random.randint(low=0, high=n_items, size=1)[0]
if neg_item not in train_user_set[user]:
break
neg_items.append(neg_item)
return neg_items
feed_dict = {}
entity_pairs = train_entity_pairs[start:end].to(device)
feed_dict['users'] = entity_pairs[:, 0]
feed_dict['pos_items'] = entity_pairs[:, 1]
feed_dict['neg_items'] = torch.LongTensor(negative_sampling(entity_pairs,
train_user_set)).to(device)
return feed_dict
if __name__ == '__main__':
"""fix the random seed"""
seed = 2020
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
"""read args"""
global args, device
args = parse_args()
device = torch.device("cuda:"+str(args.gpu_id)) if args.cuda else torch.device("cpu")
"""build dataset"""
train_cf, test_cf, user_dict, n_params, graph, mat_list = load_data(args)
adj_mat_list, norm_mat_list, mean_mat_list = mat_list
n_users = n_params['n_users']
n_items = n_params['n_items']
n_entities = n_params['n_entities']
n_relations = n_params['n_relations']
n_nodes = n_params['n_nodes']
"""cf data"""
train_cf_pairs = torch.LongTensor(np.array([[cf[0], cf[1]] for cf in train_cf], np.int32))
test_cf_pairs = torch.LongTensor(np.array([[cf[0], cf[1]] for cf in test_cf], np.int32))
"""define model"""
model = Recommender(n_params, args, graph, mean_mat_list[0]).to(device)
"""define optimizer"""
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
cur_best_pre_0 = 0
stopping_step = 0
should_stop = False
print("start training ...")
for epoch in range(args.epoch):
"""training CF"""
# shuffle training data
index = np.arange(len(train_cf))
np.random.shuffle(index)
train_cf_pairs = train_cf_pairs[index]
"""training"""
loss, s, cor_loss = 0, 0, 0
train_s_t = time()
while s + args.batch_size <= len(train_cf):
batch = get_feed_dict(train_cf_pairs,
s, s + args.batch_size,
user_dict['train_user_set'])
batch_loss, _, _, batch_cor = model(batch)
batch_loss = batch_loss
optimizer.zero_grad()
batch_loss.backward()
optimizer.step()
loss += batch_loss
cor_loss += batch_cor
s += args.batch_size
train_e_t = time()
if epoch % 10 == 9 or epoch == 1:
"""testing"""
test_s_t = time()
ret = test(model, user_dict, n_params)
test_e_t = time()
train_res = PrettyTable()
train_res.field_names = ["Epoch", "training time", "tesing time", "Loss", "recall", "ndcg", "precision", "hit_ratio"]
train_res.add_row(
[epoch, train_e_t - train_s_t, test_e_t - test_s_t, loss.item(), ret['recall'], ret['ndcg'], ret['precision'], ret['hit_ratio']]
)
print(train_res)
# *********************************************************
# early stopping when cur_best_pre_0 is decreasing for ten successive steps.
cur_best_pre_0, stopping_step, should_stop = early_stopping(ret['recall'][0], cur_best_pre_0,
stopping_step, expected_order='acc',
flag_step=10)
if should_stop:
break
"""save weight"""
if ret['recall'][0] == cur_best_pre_0 and args.save:
torch.save(model.state_dict(), args.out_dir + 'model_' + args.dataset + '.ckpt')
else:
# logging.info('training loss at epoch %d: %f' % (epoch, loss.item()))
print('using time %.4f, training loss at epoch %d: %.4f, cor: %.6f' % (train_e_t - train_s_t, epoch, loss.item(), cor_loss.item()))
print('early stopping at %d, recall@20:%.4f' % (epoch, cur_best_pre_0))