-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpmf_explicit.py
191 lines (168 loc) · 7.84 KB
/
pmf_explicit.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
import pandas as pd
import torch
from torch.utils.data import TensorDataset, DataLoader
from user_models import PMF
import os
import argparse
# Function to transform data into DataLoader format for PyTorch
def transform(user_ids, item_ids, score, movie_id_to_index_mapping, batch_size=256):
# Convert MovieIDs to indices
item_indices = [movie_id_to_index_mapping[movie_id] for movie_id in item_ids]
# Adjust user indices to be zero-indexed
user_indices = user_ids - 1
# Create TensorDataset and DataLoader
dataset = TensorDataset(torch.LongTensor(user_indices),
torch.LongTensor(item_indices),
torch.FloatTensor(score))
return DataLoader(dataset, batch_size=batch_size, shuffle=True)
# Arguments
args = argparse.ArgumentParser()
# Set to True for explicit feedback (1 to 5), False for implicit (0 or 1)
args.add_argument("-IMPLICIT", default=False, type=bool)
# Rating threshold for binarizing data, default=1, only for implicit feedback
args.add_argument("-BINARIZATION_THRESHOLD", default=1, type=int)
args = args.parse_args()
explicit = not args.IMPLICIT
base_path = 'data/ml-1m/'
train_path = base_path + "train.csv"
checkpoint_dir = 'pmf_models'
if explicit:
latent_embedding_size = 16
else:
latent_embedding_size = 32
epochs = 1000
save_model = True # Saves the model during training every save_every epochs
save_every = 200
eval_every = 10
only_load = False # Set to False for enabling training loop, True for only loading model
batch_size = 1024
feedback_type = 'explicit' if explicit else 'implicit'
if explicit:
checkpoint_path_start = f'{checkpoint_dir}/pmf_model_{feedback_type}_emb_{latent_embedding_size}_epoch_' + "{}.pth"
else:
checkpoint_path_start = f'{checkpoint_dir}/pmf_model_{feedback_type}_emb_{latent_embedding_size}_thresh_{args.BINARIZATION_THRESHOLD}_epoch_' + "{}.pth"
# Check if the directory exists, and create it if it doesn't
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
# Load and preprocess rating data
ratings = pd.read_csv(train_path)
ratings = ratings.drop(['Gender', 'Age', 'Occupation'], axis=1)
if not explicit:
ratings['Rating'] = (ratings['Rating'] > args.BINARIZATION_THRESHOLD).astype(int)
min_rating, max_rating = ratings['Rating'].min(), ratings['Rating'].max()
n_users, n_movies = len(ratings['UserID'].unique()), len(ratings['MovieID'].unique())
if not only_load:
rating_matrix_df = ratings.pivot(index='UserID', columns='MovieID', values='Rating')
# Scaling ratings to between 0 and 1, this helps our model by constraining predictions
rating_matrix_df = (rating_matrix_df - min_rating) / (max_rating - min_rating)
# Replacing missing ratings with -1 so we can filter them out later
rating_matrix_df[rating_matrix_df.isnull()] = -1
rating_matrix = torch.FloatTensor(rating_matrix_df.values)
pmf_model = PMF(n_users, n_movies, latent_vectors=latent_embedding_size, lam_u=0.05, lam_v=0.05, explicit=explicit,
min_rating=min_rating, max_rating=max_rating)
optimizer = torch.optim.Adam([pmf_model.user_features, pmf_model.movie_features], lr=0.01)
# Load validation data
val_path = base_path + "validation.csv"
val_ratings = pd.read_csv(val_path)
val_ratings = val_ratings.drop(['Gender', 'Age', 'Occupation'], axis=1)
if not explicit:
val_ratings['Rating'] = (val_ratings['Rating'] > args.BINARIZATION_THRESHOLD).astype(int)
movie_ids_sorted = sorted(ratings['MovieID'].unique())
movie_id_to_index_mapping = {}
for i, id in enumerate(movie_ids_sorted):
movie_id_to_index_mapping[id] = i
valid_loader = transform(
val_ratings["UserID"],
val_ratings["MovieID"],
val_ratings["Rating"],
movie_id_to_index_mapping,
batch_size=batch_size
)
if not only_load:
for epoch in range(1, epochs + 1):
optimizer.zero_grad()
loss = pmf_model(rating_matrix)
loss.backward()
optimizer.step()
if epoch % eval_every == 0:
print(f"Epoch {epoch}, Loss: {loss.item():.3f}")
if explicit:
rmse, mae = pmf_model.evaluate(valid_loader=valid_loader, denormalize_predictions=True,
denormalize_labels=False)
print("Epoch ", epoch, "Validation RMSE: ", rmse, "Validation MAE: ", mae)
else:
bce, auc_roc = pmf_model.evaluate(valid_loader=valid_loader, denormalize_predictions=False,
denormalize_labels=False)
print("Epoch ", epoch, "Validation BCE: ", bce, "Validation AUC-ROC: ", auc_roc)
# Save model every 10 epochs for the first 200, then save every 200
if (save_model and epoch < 200 and epoch % 10 == 0) or (save_model and epoch % save_every == 0):
checkpoint_path = checkpoint_path_start.format(epoch)
pmf_model.save_model(checkpoint_path)
print(f"Model saved at epoch {epoch} to {checkpoint_path}")
models = [200, 400, 600, 800, 1000]
for epoch in models:
# Load the final model for prediction (or choose a specific checkpoint)
pmf_model.load_model(checkpoint_path_start.format(epoch))
if explicit:
rmse, mae = pmf_model.evaluate(valid_loader=valid_loader, denormalize_predictions=True,
denormalize_labels=False)
print("Validation RMSE: ", rmse, "Validation MAE: ", mae)
else:
bce, auc_roc = pmf_model.evaluate(valid_loader=valid_loader, denormalize_predictions=False,
denormalize_labels=False)
print("Validation BCE: ", bce, "Validation AUC-ROC: ", auc_roc)
# # Making predictions for a specific user
# user_idx = 7
# predicted_ratings, actual_ratings = pmf_model.predict(user_idx, rating_matrix)
# print("Predictions: \n", predicted_ratings.detach().numpy())
# unique_elements, counts = np.unique(predicted_ratings.detach().numpy(), return_counts=True)
#
# # Printing the counts of each unique element
# print("Counts: ", counts)
# print("Truth: \n", actual_ratings.detach().numpy())
#
# movie_ids_sorted = sorted(ratings['MovieID'].unique())
# movie_id_to_index_mapping = {}
# for i, id in enumerate(movie_ids_sorted):
# movie_id_to_index_mapping[id] = i
#
# movie_ids = ratings[ratings['UserID'] == user_idx + 1]['MovieID'].to_numpy()
# movie_indices = sorted([movie_id_to_index_mapping[movie_id] for movie_id in movie_ids])
# user_embeddings, movie_embeddings = pmf_model.get_embeddings([user_idx for _ in range(len(movie_indices))], movie_indices)
# preds = pmf_model.predict_batch_with_embeddings(user_embeddings, movie_embeddings)
# print(preds)
#
# res = []
# for i in range(len(movie_ids)):
# pred = pmf_model.predict_single_with_embeddings(user_embeddings[i], movie_embeddings[i])
# res.append(pred.item())
#
# unique_elements_res, counts_res = np.unique(res, return_counts=True)
#
# # Printing the counts of each unique element in 'res'
# print("Counts: ", counts_res)
# print(res)
# # Making predictions for a batch of users
# user_indices = [0, 1]
# predicted_ratings, actual_ratings = pmf_model.predict_batch(user_indices, rating_matrix)
#
# for i in range(len(user_indices)):
# print(len(predicted_ratings[i]))
# print("Predictions: \n", predicted_ratings[i])
# print("Truth: \n", actual_ratings[i])
#
# # Making predictions for a batch of users
# user_indices = [1, 2]
# predicted_ratings, actual_ratings = pmf_model.predict_batch(user_indices, val_rating_matrix)
#
# for i in range(len(user_indices)):
# print(len(predicted_ratings[i]))
# print("Predictions: \n", predicted_ratings[i])
# print("Truth: \n", actual_ratings[i])
# print(val_ratings[val_ratings['UserID'] == user_indices[i] + 1])
#
# user_indices = [1, 2]
# movie_indices = [1245, 647]
# user_embs, movie_embs = pmf_model.get_embeddings(user_indices, movie_indices)
# print(pmf_model.predict_batch_with_embeddings(user_embs, movie_embs))
#