In this assignment, I will use the same movie ratings data collected from five participants for six movies in my previous Global Baseline assignment. The dataset contains ratings on a scale from 1 to 5, along with missing values for movies that participants had not seen. I will implement a personalized recommendation system using user-to-user collaborative filtering. This method identifies participants with similar movie rating preferences using cosine similarity and uses their ratings to predict how a participant might rate a movie they have not seen. The movie with the highest predicted rating will be recommended to each participant. I will evaluate the performance of the recommendation system using leave-one-out cross-validation, Root Mean Squared Error (RMSE), and Mean Absolute Error (MAE). I will also compare the performance of the collaborative filtering model with the Global Baseline Estimate from my previous assignment.
One challenge I anticipate is calculating similarities between participants because of the small dataset and missing movie ratings. I will calculate similarity using movies that both participants have rated.
Data Source: Primary movie rating data collected from five participants from the previous Movie Ratings assignment.
library(DBI)
## Warning: package 'DBI' was built under R version 4.4.3
library(RPostgres)
## Warning: package 'RPostgres' was built under R version 4.4.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.3
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.4.3
library(tibble)
library(knitr)
## Warning: package 'knitr' was built under R version 4.4.3
con <- dbConnect(
RPostgres::Postgres(),
dbname = "movie_ratings",
host = "localhost",
port = 5432,
user = "postgres",
password = rstudioapi::askForPassword(
"Enter PostgreSQL password"
)
)
ratings_df <- dbGetQuery(
con,
"
SELECT
p.name AS participant,
m.title AS movie,
r.rating
FROM ratings AS r
JOIN participants AS p
ON r.user_id = p.user_id
JOIN movies AS m
ON r.movie_id = m.movie_id
ORDER BY p.user_id, m.movie_id;
"
)
dbDisconnect(con)
First, I transformed the movie ratings dataframe into a user-item rating matrix. Each row represents a participant, and each column represents a movie. Missing values represent movies that participants have not rated.
rating_matrix <- ratings_df %>%
pivot_wider(
names_from = movie,
values_from = rating
) %>%
column_to_rownames("participant") %>%
as.matrix()
kable(rating_matrix)
| Spider-Man: Brand New Day | Sinners | The Odyssey | Michael | Toy Story 5 | Obsession | |
|---|---|---|---|---|---|---|
| Person 1 | 5 | 4 | NA | 5 | 4 | 4 |
| Person 2 | 4 | 5 | 4 | 5 | NA | 3 |
| Person 3 | 5 | NA | 5 | 4 | 2 | 5 |
| Person 4 | 4 | 4 | NA | 4 | 3 | NA |
| Person 5 | 5 | 5 | 3 | 5 | NA | NA |
Cosine similarity measures the similarity between two participants based on the movies that both participants have rated. A value closer to 1 indicates greater similarity between their rating vectors. I created a function to calculate cosine similarity using only movies rated by both participants. In my implementation, at least two commonly rated movies are required to calculate similarity.
cosine_similarity <- function(x, y) {
common <- !is.na(x) & !is.na(y)
if (sum(common) < 2) {
return(0)
}
x <- x[common]
y <- y[common]
sum(x * y) /
(sqrt(sum(x^2)) * sqrt(sum(y^2)))
}
Next, I created a similarity matrix to calculate the cosine similarity between each pair of participants. The diagonal values were set to zero to prevent participants’ own ratings from being used when predicting missing ratings.
create_similarity_matrix <- function(mat) {
n <- nrow(mat)
similarity <- matrix(
0,
nrow = n,
ncol = n,
dimnames = list(
rownames(mat),
rownames(mat)
)
)
for (i in seq_len(n)) {
for (j in seq_len(n)) {
if (i != j) {
similarity[i, j] <- cosine_similarity(
mat[i, ],
mat[j, ]
)
}
}
}
similarity
}
similarity_matrix <- create_similarity_matrix(
rating_matrix
)
kable(round(similarity_matrix, 3))
| Person 1 | Person 2 | Person 3 | Person 4 | Person 5 | |
|---|---|---|---|---|---|
| Person 1 | 0.000 | 0.982 | 0.964 | 0.995 | 0.995 |
| Person 2 | 0.982 | 0.000 | 0.968 | 0.995 | 0.988 |
| Person 3 | 0.964 | 0.968 | 0.000 | 0.978 | 0.962 |
| Person 4 | 0.995 | 0.995 | 0.978 | 0.000 | 1.000 |
| Person 5 | 0.995 | 0.988 | 0.962 | 1.000 | 0.000 |
The cosine similarity scores between different participants ranged from approximately 0.962 to 1.000, indicating relatively similar rating vectors. Person 4 and Person 5 had the highest cosine similarity score of 1.000, while Person 3 and Person 5 had the lowest similarity score of approximately 0.962.
I created a prediction function that calculates a weighted average of movie ratings from similar participants. Participants with higher similarity scores contribute more to the predicted rating. If no similar participants have rated a particular movie, the movie’s average rating is used. If the movie has no available ratings, the overall average is used.
predict_rating <- function(user, movie, mat, sim) {
similarities <- sim[user, ]
movie_ratings <- mat[, movie]
valid <- !is.na(movie_ratings) &
similarities > 0
if (sum(valid) == 0) {
movie_mean <- mean(
movie_ratings,
na.rm = TRUE
)
if (is.nan(movie_mean)) {
return(mean(mat, na.rm = TRUE))
}
return(movie_mean)
}
predicted_rating <- sum(
similarities[valid] * movie_ratings[valid]
) / sum(similarities[valid])
return(predicted_rating)
}
I then applied the prediction function to each missing rating in the user-item rating matrix.
predicted_matrix <- rating_matrix
for (i in seq_len(nrow(rating_matrix))) {
for (j in seq_len(ncol(rating_matrix))) {
if (is.na(rating_matrix[i, j])) {
predicted_matrix[i, j] <- predict_rating(
i,
j,
rating_matrix,
similarity_matrix
)
}
}
}
I then identified the missing ratings and their corresponding predicted ratings.
predictions <- as.data.frame(predicted_matrix) %>%
rownames_to_column("participant") %>%
pivot_longer(
cols = -participant,
names_to = "movie",
values_to = "predicted_rating"
) %>%
left_join(
ratings_df,
by = c("participant", "movie")
) %>%
filter(is.na(rating)) %>%
select(
participant,
movie,
predicted_rating
)
I selected the movie with the highest predicted rating for each participant as their personalized recommendation.
recommendations <- predictions %>%
group_by(participant) %>%
slice_max(
order_by = predicted_rating,
n = 1,
with_ties = FALSE
) %>%
ungroup() %>%
select(
participant,
movie,
predicted_rating
)
kable(recommendations, digits = 3)
| participant | movie | predicted_rating |
|---|---|---|
| Person 1 | The Odyssey | 3.989 |
| Person 2 | Toy Story 5 | 3.005 |
| Person 3 | Sinners | 4.498 |
| Person 4 | Obsession | 3.994 |
| Person 5 | Obsession | 3.991 |
The user-to-user collaborative filtering model generated one movie recommendation for each participant based on their highest predicted rating for a movie they had not seen. Person 1 was recommended The Odyssey with a predicted rating of 3.99, Person 2 was recommended Toy Story 5 with a predicted rating of 3.00, Person 3 was recommended Sinners with a predicted rating of 4.50, and Persons 4 and 5 were recommended Obsession, both with predicted ratings of approximately 3.99.
To evaluate the performance of the personalized recommendation system, I used leave-one-out cross-validation. This method removes one observed rating at a time, calculates participant similarities using the remaining ratings, and predicts the removed rating. This process is repeated for every observed rating in the dataset.
First, I identified all the observed ratings in the original rating matrix.
observed <- which(
!is.na(rating_matrix),
arr.ind = TRUE
)
Then, I created a dataframe to store the actual and predicted ratings for each iteration.
evaluation <- data.frame(
participant = rownames(rating_matrix)[
observed[, 1]
],
movie = colnames(rating_matrix)[
observed[, 2]
],
actual_rating = rating_matrix[observed],
predicted_rating = NA_real_,
baseline_rating = NA_real_
)
For each iteration, I removed one observed rating from the training matrix and recalculated the similarity matrix. I also calculated the Global Baseline Estimate using the remaining ratings to compare the performance of both recommendation methods.
for (k in seq_len(nrow(observed))) {
i <- observed[k, 1]
j <- observed[k, 2]
train_matrix <- rating_matrix
train_matrix[i, j] <- NA
train_similarity <- create_similarity_matrix(
train_matrix
)
# Collaborative filtering prediction
evaluation$predicted_rating[k] <- predict_rating(
i,
j,
train_matrix,
train_similarity
)
# Global Baseline Estimate
global_mean <- mean(
train_matrix,
na.rm = TRUE
)
user_average <- mean(
train_matrix[i, ],
na.rm = TRUE
)
movie_average <- mean(
train_matrix[, j],
na.rm = TRUE
)
user_effect <- user_average - global_mean
movie_effect <- movie_average - global_mean
if (is.nan(user_effect)) {
user_effect <- 0
}
if (is.nan(movie_effect)) {
movie_effect <- 0
}
evaluation$baseline_rating[k] <-
global_mean + user_effect + movie_effect
}
I evaluated the performance of both recommendation methods using Root Mean Squared Error (RMSE) and Mean Absolute Error (MAE). RMSE measures the difference between actual and predicted ratings while placing greater weight on larger prediction errors. MAE measures the average absolute difference between actual and predicted ratings. Lower values for both metrics indicate better prediction accuracy.
# Collaborative filtering
rmse <- sqrt(
mean(
(evaluation$actual_rating -
evaluation$predicted_rating)^2
)
)
mae <- mean(
abs(
evaluation$actual_rating -
evaluation$predicted_rating
)
)
# Global Baseline Estimate
baseline_rmse <- sqrt(
mean(
(evaluation$actual_rating -
evaluation$baseline_rating)^2
)
)
baseline_mae <- mean(
abs(
evaluation$actual_rating -
evaluation$baseline_rating
)
)
I then created a table to compare the performance of the two recommendation methods.
model_comparison <- data.frame(
Model = c(
"Global Baseline Estimate",
"User-to-User Collaborative Filtering"
),
RMSE = c(
baseline_rmse,
rmse
),
MAE = c(
baseline_mae,
mae
)
)
kable(model_comparison, digits = 3)
| Model | RMSE | MAE |
|---|---|---|
| Global Baseline Estimate | 1.015 | 0.796 |
| User-to-User Collaborative Filtering | 0.911 | 0.771 |
The user-to-user collaborative filtering model achieved an RMSE of 0.911 and an MAE of 0.771, compared to an RMSE of 1.015 and an MAE of 0.796 for the Global Baseline Estimate. Since lower values for both metrics indicate better prediction accuracy, the collaborative filtering model performed better than the Global Baseline Estimate for this dataset.
In this assignment, I implemented a personalized movie recommendation system using user-to-user collaborative filtering. Cosine similarity was used to identify participants with similar movie rating preferences, and a weighted average of their ratings was used to predict ratings for movies that participants had not seen. The movie with the highest predicted rating was selected as the recommendation for each participant. The model was evaluated using leave-one-out cross-validation, RMSE, and MAE. The collaborative filtering model achieved an RMSE of 0.911 and an MAE of 0.771, both of which were lower than those of the Global Baseline Estimate. The results suggest that incorporating similarities between participants improved rating prediction accuracy for this dataset.