-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathrun.py
More file actions
252 lines (194 loc) · 10.1 KB
/
run.py
File metadata and controls
252 lines (194 loc) · 10.1 KB
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
import datetime
import logging
import numpy as np
from argparse import ArgumentParser
import torch
from torch.autograd import Variable
from eval_metrics import precision_at_k, recall_at_k, mapk, ndcg_k
from model.model import GATE
if torch.cuda.is_available():
import torch.cuda as T
else:
import torch as T
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def parse_args():
parser = ArgumentParser(description="double AE with word and neighbor-attention")
parser.add_argument('-e', '--epoch', type=int, default=150, help='number of epochs for GAT')
parser.add_argument('-b', '--batch_size', type=int, default=1024, help='batch size for training')
parser.add_argument('-lr', '--learning_rate', type=float, default=1e-2, help='learning rate')
parser.add_argument('-wd', '--weight_decay', type=float, default=1e-3, help='weight decay')
parser.add_argument('-att', '--num_attention', type=int, default=20, help='the number of dimension of attention')
parser.add_argument('--inner_layers', nargs='+', type=int, default=[100, 50, 100], help='the number of latent factors')
parser.add_argument('--rating_weight', type=int, default=20, help='the weight of the rating entry')
parser.add_argument('--loss', type=str, default='mse', help='the weight of the word entry')
parser.add_argument('-dr', '--dropout_rate', type=float, default=0.5, help='the dropout probability')
parser.add_argument('-seed', type=int, default=0, help='random state to split the data')
return parser.parse_args()
def get_mini_batch(batch_item_index, train_matrix, rating_weight_matrix, item_word_index, item_neighbor_index):
return train_matrix[batch_item_index].toarray(), rating_weight_matrix[batch_item_index].toarray(), \
item_word_index[batch_item_index], item_neighbor_index[batch_item_index]
def pad_data(matrix):
"""
pad data to fit mini-batch training
:param matrix:
:return:
"""
padded_index = matrix.shape[1]
data, data_len = [], []
for i in range(matrix.shape[0]):
seq = matrix.getrow(i).indices
data.append(seq)
data_len.append(len(seq))
longest_len = max(data_len)
padded_data = np.ones((matrix.shape[0], longest_len)) * padded_index
for i, seq in enumerate(data):
padded_data[i, 0:len(seq)] = seq
return padded_data
def pad_list(lists, cut_off_len=300):
padded_index = max(max(lists))
seq_len = []
count = 0
for data in lists:
seq_len.append(len(data))
if len(data) < cut_off_len:
count += 1
logger.debug('content coverage:{}'.format(count / len(seq_len)))
seq_len = np.asarray(seq_len)
seq_len[seq_len > cut_off_len] = cut_off_len
longest_len = max(seq_len)
padded_data = np.ones((len(lists), longest_len)) * padded_index
for i, seq in enumerate(lists):
padded_data[i, 0:seq_len[i]] = seq[:seq_len[i]]
return padded_data, seq_len
def evaluate_model(train_matrix, test_set, item_word_seq, item_neighbor_index, GAT, batch_size):
num_items, num_users = train_matrix.shape
num_batches = int(num_items / batch_size) + 1
item_indexes = np.arange(num_items)
pred_matrix = None
for batchID in range(num_batches):
start = batchID * batch_size
end = start + batch_size
if batchID == num_batches - 1:
if start < num_items:
end = num_items
else:
break
batch_item_index = item_indexes[start:end]
# get mini-batch data
batch_x = train_matrix[batch_item_index].toarray()
batch_word_seq = item_word_seq[batch_item_index]
batch_neighbor_index = item_neighbor_index[batch_item_index]
batch_item_index = Variable(torch.from_numpy(batch_item_index).type(T.LongTensor), requires_grad=False)
batch_word_seq = Variable(torch.from_numpy(batch_word_seq).type(T.LongTensor), requires_grad=False)
batch_neighbor_index = Variable(torch.from_numpy(batch_neighbor_index).type(T.LongTensor), requires_grad=False)
batch_x = Variable(torch.from_numpy(batch_x.astype(np.float32)).type(T.FloatTensor), requires_grad=False)
# Forward pass: Compute predicted y by passing x to the model
rating_pred = GAT(batch_item_index, batch_x, batch_word_seq, batch_neighbor_index)
rating_pred = rating_pred.cpu().data.numpy().copy()
if batchID == 0:
pred_matrix = rating_pred.copy()
else:
pred_matrix = np.append(pred_matrix, rating_pred, axis=0)
topk = 50
pred_matrix[train_matrix.nonzero()] = 0
pred_matrix = pred_matrix.transpose()
# reference: https://stackoverflow.com/a/23734295, https://stackoverflow.com/a/20104162
ind = np.argpartition(pred_matrix, -topk)
ind = ind[:, -topk:]
arr_ind = pred_matrix[np.arange(len(pred_matrix))[:, None], ind]
arr_ind_argsort = np.argsort(arr_ind)[np.arange(len(pred_matrix)), ::-1]
pred_list = ind[np.arange(len(pred_matrix))[:, None], arr_ind_argsort]
precision, recall, MAP, ndcg = [], [], [], []
for k in [5, 10, 15, 20, 30, 40, 50]:
precision.append(precision_at_k(test_set, pred_list, k))
recall.append(recall_at_k(test_set, pred_list, k))
MAP.append(mapk(test_set, pred_list, k))
ndcg.append(ndcg_k(test_set, pred_list, k))
return precision, recall, MAP, ndcg
def train_model(train_matrix, item_matrix, item_neighbor_matrix, word_seq, test_set, args):
num_users, num_items = train_matrix.shape
vocab_size = item_matrix.shape[1]
train_matrix = train_matrix.transpose()
rating_weight_matrix = train_matrix.copy()
rating_weight_matrix[rating_weight_matrix > 0] = args.rating_weight
train_matrix[train_matrix > 0] = 1.0
# pad data for mini-batch
# item_word_index = pad_data(item_matrix).astype(np.int32)
item_neighbor_index = pad_data(item_neighbor_matrix).astype(np.int32)
item_word_seq, word_seq_len = pad_list(word_seq)
logger.debug(str(train_matrix.shape) + ',' + str(item_matrix.shape) + ',' + str(item_neighbor_matrix.shape))
batch_size = args.batch_size
dtype = T.FloatTensor
# Construct our model by instantiating the class defined above
GAT = GATE(num_users, num_items, vocab_size, args.inner_layers, args.dropout_rate, args.num_attention)
if torch.cuda.is_available():
GAT.cuda()
if args.loss == 'mse':
criterion = torch.nn.MSELoss(size_average=False, reduce=False)
elif args.loss == 'bce':
criterion = torch.nn.BCELoss(size_average=False, reduce=False)
GAT_optimizer = torch.optim.Adam(list(filter(lambda p: p.requires_grad, GAT.parameters())),
lr=args.learning_rate, weight_decay=args.weight_decay)
item_indexes = np.arange(num_items)
num_batches = int(num_items / batch_size) + 1
GAT.train()
for t in range(args.epoch):
logger.debug("epoch:{}".format(t))
np.random.shuffle(item_indexes)
avg_cost = 0.
for batchID in range(num_batches):
start = batchID * batch_size
end = start + batch_size
if batchID == num_batches - 1:
if start < num_items:
end = num_items
else:
break
batch_item_index = item_indexes[start:end]
# get mini-batch data
batch_x, batch_x_weight, batch_word_seq, batch_neighbor_index = \
get_mini_batch(batch_item_index, train_matrix, rating_weight_matrix, item_word_seq, item_neighbor_index)
batch_x_weight += 1
batch_item_index = Variable(torch.from_numpy(batch_item_index).type(T.LongTensor), requires_grad=False)
batch_word_seq = Variable(torch.from_numpy(batch_word_seq).type(T.LongTensor), requires_grad=False)
batch_neighbor_index = Variable(torch.from_numpy(batch_neighbor_index).type(T.LongTensor),requires_grad=False)
batch_x = Variable(torch.from_numpy(batch_x.astype(np.float32)).type(dtype), requires_grad=False)
batch_x_weight = Variable(torch.from_numpy(batch_x_weight).type(dtype), requires_grad=False)
# Forward pass: Compute predicted y by passing x to the model
rating_pred = GAT(batch_item_index, batch_x, batch_word_seq, batch_neighbor_index)
# Compute and print loss
loss = (batch_x_weight * criterion(rating_pred, batch_x)).sum() / batch_size
logger.debug('batch_id:{}, loss:{}'.format(batchID, loss.data))
# Zero gradients, perform a backward pass, and update the weights.
GAT_optimizer.zero_grad()
loss.backward()
GAT_optimizer.step()
avg_cost += loss / num_items * batch_size
logger.debug("Avg loss:{}".format(avg_cost))
if t % 10 == 0 and t > 0:
precision, recall, MAP, ndcg = evaluate_model(train_matrix, test_set, item_word_seq, item_neighbor_index, GAT, batch_size)
logger.info('epoch:{}'.format(t))
logger.info(', '.join(str(e) for e in precision))
logger.info(', '.join(str(e) for e in recall))
logger.info(', '.join(str(e) for e in MAP))
logger.info(', '.join(str(e) for e in ndcg))
GAT.eval()
precision, recall, MAP, ndcg = evaluate_model(train_matrix, test_set, item_word_seq, item_neighbor_index, GAT, batch_size)
logger.info('epoch:{}'.format(args.epoch))
logger.info(', '.join(str(e) for e in precision))
logger.info(', '.join(str(e) for e in recall))
logger.info(', '.join(str(e) for e in MAP))
logger.info(', '.join(str(e) for e in ndcg))
logger.info('Parameters:')
for arg, value in sorted(vars(args).items()):
logger.info("%s: %r", arg, value)
logger.info('\n')
def main():
logger.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
args = parse_args()
from dataset import Amazon
train_matrix, train_set, test_set, item_content_matrix, item_relation_matrix, word_seq = Amazon.CDs().generate_dataset(args.seed)
train_model(train_matrix, item_content_matrix, item_relation_matrix, word_seq, test_set, args)
if __name__ == '__main__':
main()