-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutoRec.py
52 lines (33 loc) · 1.22 KB
/
AutoRec.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
import torch
import torch.nn as nn
class AutoRec(nn.Module):
def __init__(self,args,num_users,num_items):
super(AutoRec,self).__init__()
self.args = args
self.num_users = num_users
self.num_items = num_items
self.embedding_size = args.embedding_size
self.alpha_value = args.alpha_value
self.encoder = nn.Sequential(
nn.Linear(self.num_items,self.embedding_size),
nn.Sigmoid()
)
self.decoder = nn.Sequential(
nn.Linear(self.embedding_size,self.num_items),
)
def forward(self,torch_input):
encoder = self.encoder(torch_input)
decoder = self.decoder(encoder)
return decoder
def loss(self,decoder,input,optimizer,mask_input):
cost = 0
temp2 = 0
cost += ((decoder - input) * mask_input).pow(2).sum()
rmse = cost
for i in optimizer.param_groups:
for j in i['params']:
# print(type(j.data), j.shape,j.data.dim())
if j.data.dim() == 2 or j.data.dim()==1:
temp2 += torch.t(j.data).pow(2).sum() # 正则化项
cost += temp2 * self.alpha_value * 0.5
return cost, rmse