-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtest.py
78 lines (64 loc) · 2.01 KB
/
test.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
'''
@Author: Yu Di
@Date: 2019-08-09 14:04:38
@LastEditors: Yudi
@LastEditTime: 2019-08-15 16:05:55
@Company: Cardinal Operation
@Email: [email protected]
@Description: this is a demo for SVD++ recommendation
'''
import torch
from torch.utils.data import DataLoader, Dataset
from SVDppRecommender import SVDpp
class RateDataset(Dataset):
def __init__(self, user_tensor, item_tensor, target_tensor):
self.user_tensor = user_tensor
self.item_tensor = item_tensor
self.target_tensor = target_tensor
def __getitem__(self, index):
return self.user_tensor[index], self.item_tensor[index], self.target_tensor[index]
def __len__(self):
return self.user_tensor.size(0)
data = {(0,0): 4,
(0,1): 5,
(0,2): 3,
(0,3): 4,
(1,0): 5,
(1,1): 3,
(1,2): 4,
(1,3): 1,
(2,0): 3,
(2,1): 2,
(2,2): 5,
(2,3): 5,
(3,0): 4,
(3,1): 2,
(3,2): 3,
(3,3): 1
}
Iu = {key:[0,1,2,3] for key in range(4)}
user_tensor = torch.LongTensor([key[0] for key in data.keys()])
item_tensor = torch.LongTensor([key[1] for key in data.keys()])
rating_tensor = torch.FloatTensor([val for val in data.values()])
params = {'num_users': 4,
'num_items': 4,
'global_mean': 3,
'latent_dim': 10
}
model = SVDpp(params)
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
dataset = RateDataset(user_tensor, item_tensor, rating_tensor)
train_loader = DataLoader(dataset, batch_size=10, shuffle=True)
for epoch in range(30):
for bid, batch in enumerate(train_loader):
u, i, r = batch[0], batch[1], batch[2]
r = r.float()
# forward pass
preds = model(u, i, Iu)
loss = criterion(preds, r)
# backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('Epoch [{}/30], Loss: {:.4f}'.format(epoch + 1, loss.item()))