-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
230 lines (190 loc) · 8.02 KB
/
train.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import numpy as np
import torch
from torch import nn
from torch.optim import Adam
from sklearn.metrics import mean_squared_error
from gmf import GMF
from ncf_mlp import NCF_MLP
from neural_mf import NEURAL_MF
def train_loop(dataloader, model, loss_fn, optimizer, device):
size = len(dataloader.dataset)
model.train()
train_loss = 0
for batch, (user, item, y) in enumerate(dataloader):
user, item, y = user.to(device), item.to(device), y.to(device)
pred = model(user, item)
loss = loss_fn(pred.squeeze(dim = 1), y.to(torch.float32))
train_loss += loss.item()
loss.backward()
optimizer.step()
optimizer.zero_grad()
# If we're using a smaller dataset, print more frequently
if size < 1_000_000:
batch_num = 100
else:
batch_num = 1000
if batch % batch_num == 0:
loss, current = loss.item(), batch * dataloader.batch_size + len(user)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
train_loss /= size
return train_loss
def test_loop(dataloader, model, loss_fn, device, rescale_data=False):
model.eval()
num_batches = len(dataloader)
test_loss = 0
y_list = list()
pred_list = list()
loss_list = list()
test_loss = 0
with torch.no_grad():
for user, item, y in dataloader:
user, item, y = user.to(device), item.to(device), y.to(device)
pred = model(user, item)
loss = loss_fn(pred.squeeze(dim = 1), y.to(torch.float32))
test_loss += loss.item()
y_list.extend(y.tolist())
pred_list.extend(pred.tolist())
test_loss /= num_batches
print(f"Avg loss: {test_loss:>8f} \n")
if rescale_data:
# Need to rescale things back when evaluating
y_list = np.array(y_list) * 5.0
pred_list = np.array(pred_list) * 5.0
test_mse = mean_squared_error(y_list, pred_list)
test_rmse = mean_squared_error(y_list, pred_list, squared=False)
print(f"Test MSE", test_mse)
print(f"Test RMSE", test_rmse)
return test_rmse, test_loss
def get_optimizer_by_type(model, optimizer_type, learning_rate, weight_decay):
if optimizer_type == 'adam':
return torch.optim.Adam(params=model.parameters(),
lr=learning_rate,
weight_decay=weight_decay)
else:
return torch.optim.SGD(model.parameters(), lr=learning_rate)
def train_gmf(train_loader,
test_loader,
num_users,
num_items,
epochs,
latent_dims,
learning_rate,
optimizer_type,
criterion,
device,
weight_decay=None,
top_depth=1,
rescale_data=False):
model = GMF(num_users=num_users,
num_items=num_items,
embed_dim=latent_dims,
top_depth=top_depth).to(device)
optimizer = get_optimizer_by_type(model, optimizer_type, learning_rate, weight_decay)
train_loss_history = []
test_loss_history = []
test_rmse_history = []
for i in range(epochs):
print('Epoch', i+1)
print('------------------------')
train_loss = train_loop(train_loader, model, criterion, optimizer, device)
test_rmse, test_loss = test_loop(test_loader, model, criterion, device, rescale_data=rescale_data)
train_loss_history.append(train_loss)
test_loss_history.append(test_loss)
test_rmse_history.append(test_rmse)
return (model, train_loss_history, test_loss_history, test_rmse_history)
def train_mlp(train_loader,
test_loader,
num_users,
num_items,
epochs,
latent_dims,
learning_rate,
optimizer_type,
criterion,
device,
weight_decay=None,
top_depth=1,
rescale_data=False):
model = NCF_MLP(num_users=num_users,
num_items=num_items,
latent_dims=latent_dims,
top_depth=top_depth).to(device)
optimizer = get_optimizer_by_type(model, optimizer_type, learning_rate, weight_decay)
train_loss_history = []
test_loss_history = []
test_rmse_history = []
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loss = train_loop(train_loader, model, criterion, optimizer, device)
test_rmse, test_loss = test_loop(test_loader, model, criterion, device, rescale_data=rescale_data)
train_loss_history.append(train_loss)
test_loss_history.append(test_loss)
test_rmse_history.append(test_rmse)
return (model, train_loss_history, test_loss_history, test_rmse_history)
def train_joint_nerual_mf(train_loader,
test_loader,
num_users,
num_items,
epochs,
latent_dims,
learning_rate,
optimizer_type,
criterion,
device,
weight_decay=None,
top_depth=1,
rescale_data=False):
"""A naive implementation of GMF + MLP fusion for Neural MF.
In the paper, the GMF and MLP models are pretrained so that the embeddings start
in a good place, and there's a hyperparameter weighing the relative importance
of each model's contriubitions at the start of training the joint model. This
implementation, instead, simply trains everything jointly.
"""
model = NEURAL_MF(num_users=num_users,
num_items=num_items,
latent_dims=latent_dims,
top_depth=top_depth).to(device)
optimizer = get_optimizer_by_type(model, optimizer_type, learning_rate, weight_decay)
for i in range(epochs):
print('Epoch', i+1)
print('------------------------')
train_loop(train_loader, model, criterion, optimizer, device)
test_loop(test_loader, model, criterion, device, rescale_data=rescale_data)
return model
# Note: specifying None for gmf/mlp is equivalent to using train_joint_neural_mf above
def train_neural_mf(train_loader,
test_loader,
gmf_pretrained,
mlp_pretrained,
num_users,
num_items,
epochs,
latent_dims,
learning_rate,
optimizer_type,
criterion,
device,
alpha,
weight_decay=None,
top_depth=1,
rescale_data=False):
model = NEURAL_MF(num_users=num_users,
num_items=num_items,
latent_dims=latent_dims,
gmf=gmf_pretrained,
mlp=mlp_pretrained,
alpha=alpha,
top_depth=top_depth).to(device)
optimizer = get_optimizer_by_type(model, optimizer_type, learning_rate, weight_decay)
train_loss_history = []
test_loss_history = []
test_rmse_history = []
for i in range(epochs):
print('Epoch', i+1)
print('------------------------')
train_loss = train_loop(train_loader, model, criterion, optimizer, device)
test_rmse, test_loss = test_loop(test_loader, model, criterion, device, rescale_data=rescale_data)
train_loss_history.append(train_loss)
test_loss_history.append(test_loss)
test_rmse_history.append(test_rmse)
return (model, train_loss_history, test_loss_history, test_rmse_history)