In this example, we'll build a simple collaborative filtering-based recommender system using PyTorch. We'll use matrix factorization, a popular technique for recommendation systems, and evaluate the quality of recommendations using the Root Mean Squared Error (RMSE) metric, which is commonly used to measure the accuracy of predicted ratings.
Overview of the Example
Problem: Predict user ratings for items (e.g., movies, products) based on historical user-item interactions.
Model: Use matrix factorization to learn latent factors for users and items.
Dataset: We'll simulate a small user-item rating matrix for demonstration purposes (in practice, you would use a real dataset like MovieLens).
Metric: Evaluate the model using RMSE to measure the difference between predicted and actual ratings.
Step-by-Step Implementation
1. Import Libraries
We'll use PyTorch for building the model, NumPy for data manipulation, and scikit-learn for calculating RMSE.
python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from sklearn.metrics import mean_squared_error
from math import sqrt
2. Simulate a User-Item Rating Matrix
For simplicity, we'll create a small synthetic dataset. In practice, you would load a real dataset (e.g., MovieLens).
python
# Simulate a user-item rating matrix (5 users, 6 items)
# Ratings are on a scale of 1 to 5, with 0 indicating missing ratings
ratings = np.array([
[5, 3, 0, 1, 0, 0],
[4, 0, 0, 1, 0, 0],
[1, 1, 0, 5, 0, 0],
[0, 0, 0, 4, 0, 0],
[0, 1, 2, 0, 0, 0],
])
n_users, n_items = ratings.shape
n_factors = 3 # Number of latent factors
3. Prepare Data for Training
We'll convert the rating matrix into a list of (user, item, rating) tuples for training, ignoring missing ratings (zeros).
python
# Create training data (user, item, rating) for non-zero entries
train_data = []
for user in range(n_users):
for item in range(n_items):
if ratings[user, item] > 0:
train_data.append((user, item, ratings[user, item]))
# Convert to PyTorch tensors
train_data = [(torch.tensor(u, dtype=torch.long),
torch.tensor(i, dtype=torch.long),
torch.tensor(r, dtype=torch.float)) for u, i, r in train_data]
4. Define the Matrix Factorization Model
We'll define a PyTorch model that learns user and item embeddings (latent factors) and predicts ratings as the dot product of these embeddings.
python
class MatrixFactorization(nn.Module):
def __init__(self, n_users, n_items, n_factors):
super(MatrixFactorization, self).__init__()
# User and item embeddings
self.user_factors = nn.Embedding(n_users, n_factors)
self.item_factors = nn.Embedding(n_items, n_factors)
# Initialize embeddings with small random values
nn.init.normal_(self.user_factors.weight, std=0.01)
nn.init.normal_(self.item_factors.weight, std=0.01)
def forward(self, user, item):
# Dot product of user and item embeddings
return (self.user_factors(user) * self.item_factors(item)).sum(1)
# Instantiate the model
model = MatrixFactorization(n_users, n_items, n_factors)
5. Define Loss Function and Optimizer
We'll use Mean Squared Error (MSE) as the loss function, as it aligns with our goal of minimizing the difference between predicted and actual ratings.
We'll train the model on the non-zero ratings in the training data.
python
n_epochs = 100
for epoch in range(n_epochs):
total_loss = 0
for user, item, rating in train_data:
# Forward pass
pred = model(user, item)
loss = criterion(pred, rating)
total_loss += loss.item()
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch {epoch + 1}/{n_epochs}, Loss: {total_loss / len(train_data):.4f}')
7. Make Predictions
After training, we can use the model to predict ratings for all user-item pairs, including those with missing ratings.
python
# Predict ratings for all user-item pairs
model.eval()
predicted_ratings = np.zeros((n_users, n_items))
with torch.no_grad():
for user in range(n_users):
for item in range(n_items):
user_tensor = torch.tensor(user, dtype=torch.long)
item_tensor = torch.tensor(item, dtype=torch.long)
predicted_ratings[user, item] = model(user_tensor, item_tensor).item()
print("\nPredicted Ratings Matrix:")
print(np.round(predicted_ratings, 2))
8. Evaluate the Model Using RMSE
We'll calculate the RMSE between the actual ratings and the predicted ratings for the non-zero entries in the original rating matrix.
python
# Extract actual and predicted ratings for non-zero entries
actual_ratings = []
predicted_ratings_nonzero = []
for user, item, rating in train_data:
actual_ratings.append(rating.item())
predicted_ratings_nonzero.append(predicted_ratings[user.item(), item.item()])
# Calculate RMSE
rmse = sqrt(mean_squared_error(actual_ratings, predicted_ratings_nonzero))
print(f'\nRMSE: {rmse:.4f}')
9. Interpret the Results
The RMSE measures the average error in the predicted ratings. A lower RMSE indicates better performance.
In practice, you might also use other metrics like Mean Absolute Error (MAE) or ranking-based metrics like Precision@K or Recall@K if the goal is to recommend top-N items rather than predict exact ratings.
Full Code
Here is the complete code for reference:
python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from sklearn.metrics import mean_squared_error
from math import sqrt
# Simulate a user-item rating matrix (5 users, 6 items)
ratings = np.array([
[5, 3, 0, 1, 0, 0],
[4, 0, 0, 1, 0, 0],
[1, 1, 0, 5, 0, 0],
[0, 0, 0, 4, 0, 0],
[0, 1, 2, 0, 0, 0],
])
n_users, n_items = ratings.shape
n_factors = 3 # Number of latent factors
# Create training data (user, item, rating) for non-zero entries
train_data = []
for user in range(n_users):
for item in range(n_items):
if ratings[user, item] > 0:
train_data.append((user, item, ratings[user, item]))
# Convert to PyTorch tensors
train_data = [(torch.tensor(u, dtype=torch.long),
torch.tensor(i, dtype=torch.long),
torch.tensor(r, dtype=torch.float)) for u, i, r in train_data]
# Define the Matrix Factorization model
class MatrixFactorization(nn.Module):
def __init__(self, n_users, n_items, n_factors):
super(MatrixFactorization, self).__init__()
self.user_factors = nn.Embedding(n_users, n_factors)
self.item_factors = nn.Embedding(n_items, n_factors)
nn.init.normal_(self.user_factors.weight, std=0.01)
nn.init.normal_(self.item_factors.weight, std=0.01)
def forward(self, user, item):
return (self.user_factors(user) * self.item_factors(item)).sum(1)
# Instantiate the model
model = MatrixFactorization(n_users, n_items, n_factors)
# Define loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
# Train the model
n_epochs = 100
for epoch in range(n_epochs):
total_loss = 0
for user, item, rating in train_data:
pred = model(user, item)
loss = criterion(pred, rating)
total_loss += loss.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch {epoch + 1}/{n_epochs}, Loss: {total_loss / len(train_data):.4f}')
# Predict ratings for all user-item pairs
model.eval()
predicted_ratings = np.zeros((n_users, n_items))
with torch.no_grad():
for user in range(n_users):
for item in range(n_items):
user_tensor = torch.tensor(user, dtype=torch.long)
item_tensor = torch.tensor(item, dtype=torch.long)
predicted_ratings[user, item] = model(user_tensor, item_tensor).item()
print("\nPredicted Ratings Matrix:")
print(np.round(predicted_ratings, 2))
# Evaluate using RMSE
actual_ratings = []
predicted_ratings_nonzero = []
for user, item, rating in train_data:
actual_ratings.append(rating.item())
predicted_ratings_nonzero.append(predicted_ratings[user.item(), item.item()])
rmse = sqrt(mean_squared_error(actual_ratings, predicted_ratings_nonzero))
print(f'\nRMSE: {rmse:.4f}')
Notes
Real-World Datasets: For a real-world application, you can use datasets like MovieLens, Amazon Reviews, or Netflix Prize data. These datasets are typically sparse, and you would need to preprocess them to extract user-item interactions.
Improvements: You can improve the model by adding biases (user and item biases), regularization, or using more advanced techniques like neural collaborative filtering (NCF) or deep learning-based recommenders.
Evaluation Metrics: For top-N recommendation tasks, consider using ranking-based metrics like Precision@K, Recall@K, or NDCG instead of RMSE.
Hyperparameter Tuning: Experiment with the number of latent factors (n_factors), learning rate, and number of epochs to improve performance.
This example provides a solid foundation for building and evaluating a recommender system using PyTorch.