-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraining.py
More file actions
59 lines (46 loc) · 1.89 KB
/
Copy pathtraining.py
File metadata and controls
59 lines (46 loc) · 1.89 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
import torch
import torch
import torch.nn as nn
import torch.optim as optim
from giza_actions.action import Action, action
from giza_actions.task import task
from helper import prepare_dataset, create_loaders
from helper import train_model, test_model, convert_to_onnx
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define the model and MF means Matrix Factorization
class MF(nn.Module):
def __init__(self, num_users, num_movies, embedding_size):
super(MF, self).__init__()
self.user_embeddings = nn.Embedding(num_users, embedding_size)
self.movie_embeddings = nn.Embedding(num_movies, embedding_size)
def forward(self, user_ids, movie_ids):
user_embeds = self.user_embeddings(user_ids)
movie_embeds = self.movie_embeddings(movie_ids)
preds = torch.sum(user_embeds * movie_embeds, dim=1)
return preds.to(device)
@action(name="Action: Convert To ONNX", log_prints=True)
def execution():
ratings = prepare_dataset()
# Constants
num_users = ratings['user_idx'].nunique()
num_movies = ratings['movie_idx'].nunique()
embedding_size = 300
learning_rate = 0.01
num_epochs = 100
batch_size = 64
train_loader, test_loader = create_loaders(ratings, batch_size)
model = train_model(MF,
num_users,
num_movies,
embedding_size,
learning_rate,
device,
num_epochs,
train_loader)
criterion = nn.MSELoss()
test_loss = test_model(model, test_loader, criterion, device)
print(f"Test Loss: {test_loss:.4f}")
convert_to_onnx(model, num_movies, device)
if __name__ == "__main__":
action_deploy = Action(entrypoint=execution, name="pytorch-movie_recsys-action")
action_deploy.serve(name="pytorch-movie_recsys-deployment")