ASSIGNMENT 11: PERSONALIZED RECOMMENDER

Author

Reginald Dorcely

Quarto

Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see https://quarto.org.

Running Code

When you click the Render button a document will be generated that includes both content and the output of embedded code. You can embed code like this:

# ==========================================================
# ASSIGNMENT 11: PERSONALIZED RECOMMENDER
# Author: Reginald Dorcely
# Algorithm: User-to-User Collaborative Filtering
# ==========================================================

# STEP 1: CREATE DATASET

users <- c("Alice", "Brian", "Carla", "David",
           "Elena", "Frank", "Grace")

movies <- c(
  "Spider-Man: Brand New Day",
  "The Odyssey",
  "Toy Story 5",
  "The Super Mario Galaxy Movie",
  "Project Hail Mary"
)

ratings <- matrix(
  c(
    5, 4, 4, 5, 4,
    4, 5, 3, 4, 5,
    5, 4, 5, 4, 4,
    3, 5, 4, 5, 5,
    4, 4, 5, 4, 3,
    5, 3, 4, 5, 4,
    4, 5, 4, 3, 5
  ),
  nrow = 7,
  byrow = TRUE,
  dimnames = list(users, movies)
)

print(ratings)
      Spider-Man: Brand New Day The Odyssey Toy Story 5
Alice                         5           4           4
Brian                         4           5           3
Carla                         5           4           5
David                         3           5           4
Elena                         4           4           5
Frank                         5           3           4
Grace                         4           5           4
      The Super Mario Galaxy Movie Project Hail Mary
Alice                            5                 4
Brian                            4                 5
Carla                            4                 4
David                            5                 5
Elena                            4                 3
Frank                            5                 4
Grace                            3                 5
# STEP 2: EXPLORE DATASET

cat("\nNumber of users:", nrow(ratings))

Number of users: 7
cat("\nNumber of movies:", ncol(ratings))

Number of movies: 5
cat("\nTotal ratings:", length(ratings))

Total ratings: 35
cat("\nGlobal mean:", mean(ratings), "\n")

Global mean: 4.257143 
print(rowMeans(ratings))
Alice Brian Carla David Elena Frank Grace 
  4.4   4.2   4.4   4.4   4.0   4.2   4.2 
print(colMeans(ratings))
   Spider-Man: Brand New Day                  The Odyssey 
                    4.285714                     4.285714 
                 Toy Story 5 The Super Mario Galaxy Movie 
                    4.142857                     4.285714 
           Project Hail Mary 
                    4.285714 
print(summary(as.vector(ratings)))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  3.000   4.000   4.000   4.257   5.000   5.000 
# STEP 3: SPLIT DATA INTO TRAINING AND TESTING

set.seed(123)

train <- ratings

test <- data.frame(
  user = users,
  movie = NA_character_,
  actual = NA_real_
)

for (i in seq_along(users)) {
  
  j <- sample(seq_along(movies), 1)
  
  test$movie[i] <- movies[j]
  test$actual[i] <- ratings[i, j]
  
  train[i, j] <- NA
}

print(train)
      Spider-Man: Brand New Day The Odyssey Toy Story 5
Alice                         5           4          NA
Brian                         4           5          NA
Carla                         5          NA           5
David                         3          NA           4
Elena                         4           4          NA
Frank                         5           3           4
Grace                         4           5           4
      The Super Mario Galaxy Movie Project Hail Mary
Alice                            5                 4
Brian                            4                 5
Carla                            4                 4
David                            5                 5
Elena                            4                 3
Frank                            5                NA
Grace                           NA                 5
print(test)
   user                        movie actual
1 Alice                  Toy Story 5      4
2 Brian                  Toy Story 5      3
3 Carla                  The Odyssey      4
4 David                  The Odyssey      5
5 Elena                  Toy Story 5      5
6 Frank            Project Hail Mary      4
7 Grace The Super Mario Galaxy Movie      3
cat("\nTraining ratings:", sum(!is.na(train)))

Training ratings: 28
cat("\nTesting ratings:", nrow(test), "\n")

Testing ratings: 7 
# STEP 4: DEFINE COSINE 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]
  
  denominator <- sqrt(sum(x^2)) * sqrt(sum(y^2))
  
  if (denominator == 0) return(0)
  
  sum(x * y) / denominator
}


# STEP 5: CREATE USER SIMILARITY MATRIX

similarity <- matrix(
  0,
  nrow = length(users),
  ncol = length(users),
  dimnames = list(users, users)
)

for (i in seq_along(users)) {
  for (j in seq_along(users)) {
    
    similarity[i, j] <-
      cosine_similarity(train[i, ], train[j, ])
  }
}

diag(similarity) <- 1

cat("\nUSER SIMILARITY MATRIX\n")

USER SIMILARITY MATRIX
print(round(similarity, 3))
      Alice Brian Carla David Elena Frank Grace
Alice 1.000 0.976 0.995 0.962 0.995 0.994 0.978
Brian 0.976 1.000 0.982 0.983 0.980 0.948 1.000
Carla 0.995 0.982 1.000 0.956 0.993 0.985 0.978
David 0.962 0.983 0.956 1.000 0.956 0.975 0.993
Elena 0.995 0.980 0.993 0.956 1.000 0.977 0.980
Frank 0.994 0.948 0.985 0.975 0.977 1.000 0.955
Grace 0.978 1.000 0.978 0.993 0.980 0.955 1.000
# STEP 6: PERSONALIZED PREDICTION FUNCTION

predict_rating <- function(user, movie, k = 3) {
  
  weights <- similarity[user, ]
  values <- train[, movie]
  
  eligible <- names(weights) != user &
    !is.na(values) &
    weights > 0
  
  weights <- weights[eligible]
  values <- values[eligible]
  
  if (length(weights) == 0) {
    return(mean(train, na.rm = TRUE))
  }
  
  nearest <- head(
    order(weights, decreasing = TRUE),
    k
  )
  
  prediction <- weighted.mean(
    values[nearest],
    weights[nearest]
  )
  
  max(1, min(5, prediction))
}


# STEP 7: GENERATE PERSONALIZED RECOMMENDATIONS

recommend_movies <- function(user, n = 3) {
  
  candidates <- movies[is.na(train[user, ])]
  
  if (length(candidates) == 0) {
    return(NULL)
  }
  
  predictions <- sapply(
    candidates,
    function(movie) predict_rating(user, movie)
  )
  
  result <- data.frame(
    User = user,
    Movie = candidates,
    Predicted_Rating = as.numeric(predictions)
  )
  
  result <- result[
    order(-result$Predicted_Rating),
  ]
  
  result <- head(result, n)
  
  result$Rank <- seq_len(nrow(result))
  
  result
}

recommendations <- do.call(
  rbind,
  lapply(users, recommend_movies)
)

cat("\nPERSONALIZED RECOMMENDATIONS\n")

PERSONALIZED RECOMMENDATIONS
print(recommendations, row.names = FALSE)
  User                        Movie Predicted_Rating Rank
 Alice                  Toy Story 5         4.335275    1
 Brian                  Toy Story 5         4.331311    1
 Carla                  The Odyssey         3.668658    1
 David                  The Odyssey         4.339212    1
 Elena                  Toy Story 5         4.336529    1
 Frank            Project Hail Mary         3.669388    1
 Grace The Super Mario Galaxy Movie         4.333911    1
# STEP 8: EVALUATE PERSONALIZED MODEL

test$predicted <- mapply(
  predict_rating,
  test$user,
  test$movie
)

test$error <- test$actual - test$predicted

RMSE <- sqrt(mean(test$error^2))

MAE <- mean(abs(test$error))

cat("\nPERSONALIZED MODEL RESULTS\n")

PERSONALIZED MODEL RESULTS
print(test)
   user                        movie actual predicted      error
1 Alice                  Toy Story 5      4  4.335275 -0.3352752
2 Brian                  Toy Story 5      3  4.331311 -1.3313108
3 Carla                  The Odyssey      4  3.668658  0.3313423
4 David                  The Odyssey      5  4.339212  0.6607884
5 Elena                  Toy Story 5      5  4.336529  0.6634714
6 Frank            Project Hail Mary      4  3.669388  0.3306121
7 Grace The Super Mario Galaxy Movie      3  4.333911 -1.3339113
cat("\nRMSE:", round(RMSE, 4))

RMSE: 0.8246
cat("\nMAE:", round(MAE, 4), "\n")

MAE: 0.7124 
# STEP 9: GLOBAL BASELINE ESTIMATE

global_mean <- mean(train, na.rm = TRUE)

user_bias <- rowMeans(
  train, na.rm = TRUE
) - global_mean

movie_bias <- colMeans(
  train, na.rm = TRUE
) - global_mean

movie_bias[is.na(movie_bias)] <- 0

test$baseline <- mapply(
  
  function(user, movie) {
    
    prediction <- global_mean +
      user_bias[user] +
      movie_bias[movie]
    
    max(1, min(5, prediction))
  },
  
  test$user,
  test$movie
)

baseline_RMSE <- sqrt(
  mean((test$actual - test$baseline)^2)
)

baseline_MAE <- mean(
  abs(test$actual - test$baseline)
)


# STEP 10: COMPARE MODEL PERFORMANCE

comparison <- data.frame(
  
  Model = c(
    "Global Baseline",
    "Personalized UBCF"
  ),
  
  RMSE = c(
    baseline_RMSE,
    RMSE
  ),
  
  MAE = c(
    baseline_MAE,
    MAE
  )
)

cat("\nMODEL PERFORMANCE COMPARISON\n")

MODEL PERFORMANCE COMPARISON
print(comparison, row.names = FALSE)
             Model     RMSE       MAE
   Global Baseline 1.052858 0.9098639
 Personalized UBCF 0.824625 0.7123874
# STEP 11: VISUALIZATIONS

# Graph 1: Average movie ratings

barplot(
  colMeans(ratings),
  names.arg = c(
    "Spider-Man",
    "Odyssey",
    "Toy Story",
    "Mario",
    "Hail Mary"
  ),
  col = "steelblue",
  ylim = c(0, 5),
  main = "Average Movie Ratings",
  ylab = "Average Rating"
)

# Graph 2: Rating distribution

barplot(
  table(ratings),
  col = "darkgreen",
  main = "Distribution of Movie Ratings",
  xlab = "Rating",
  ylab = "Frequency"
)

# Graph 3: User similarity heatmap

heatmap(
  similarity,
  Rowv = NA,
  Colv = NA,
  scale = "none",
  col = heat.colors(20),
  main = "User Similarity Heatmap"
)

# Graph 4: Model performance comparison

barplot(
  t(as.matrix(comparison[, c("RMSE", "MAE")])),
  beside = TRUE,
  names.arg = c("Baseline", "Personalized"),
  col = c("steelblue", "orange"),
  main = "Model Performance Comparison",
  ylab = "Prediction Error",
  legend.text = c("RMSE", "MAE")
)

# Graph 5: Actual vs predicted ratings

plot(
  test$actual,
  test$predicted,
  xlim = c(1, 5),
  ylim = c(1, 5),
  pch = 19,
  col = "blue",
  xlab = "Actual Ratings",
  ylab = "Predicted Ratings",
  main = "Actual vs Predicted Ratings"
)

abline(0, 1, col = "red", lty = 2, lwd = 2)

# Graph 6: Personalized recommendations

barplot(
  recommendations$Predicted_Rating,
  names.arg = recommendations$User,
  col = "darkcyan",
  ylim = c(0, 5),
  main = "Personalized Movie Recommendations",
  ylab = "Predicted Rating"
)

# STEP 12: EXPORT RESULTS

write.csv(
  recommendations,
  "Personalized_Recommendations.csv",
  row.names = FALSE
)

write.csv(
  comparison,
  "Model_Performance.csv",
  row.names = FALSE
)

write.csv(
  test,
  "Actual_vs_Predicted.csv",
  row.names = FALSE
)

write.csv(
  similarity,
  "User_Similarity_Matrix.csv"
)


# STEP 13: AUTOMATED CONCLUSION

cat("\nFINAL CONCLUSION\n")

FINAL CONCLUSION
if (RMSE < baseline_RMSE) {
  
  cat("\nPersonalized UBCF has a lower RMSE.")
  
} else if (RMSE > baseline_RMSE) {
  
  cat("\nGlobal Baseline has a lower RMSE.")
  
} else {
  
  cat("\nBoth models have the same RMSE.")
}

Personalized UBCF has a lower RMSE.
if (MAE < baseline_MAE) {
  
  cat("\nPersonalized UBCF has a lower MAE.")
  
} else if (MAE > baseline_MAE) {
  
  cat("\nGlobal Baseline has a lower MAE.")
  
} else {
  
  cat("\nBoth models have the same MAE.")
}

Personalized UBCF has a lower MAE.
cat("\n\nOutput directory:", getwd())


Output directory: C:/Users/Reggie/OneDrive/Documentos/ersonalized Recommender_Approach/Personalized_files
cat("\nAssignment completed.\n")

Assignment completed.
# END OF CODE