Build a Personalized Recommendation System

User-Based Collaborative Filtering | DATA 607

Author

Sarah Abdelrahman

Published

November 29, 2026

CUNY School of Professional Studies | M.S. in Data Science
Course: DATA 607 — Data Acquisition and Management
Instructor: Professor Darwhin Gomez

Introduction

This assignment extends my previous Global Baseline Estimate using the original movie-rating survey. I implement user-based collaborative filtering (UBCF) from scratch in R, following the Pearson similarity and weighted-average example in the course lecture. My objective is to predict unknown movie ratings, rank unseen movies for each participant, and examine whether personalization improves prediction accuracy over the previous baseline.

1. Original survey data

The original survey contains five participants and six movies. Missing values indicate movies not rated by a participant; they are not zeros. All computations use base R, with knitr only for displaying tables.

movies <- c("Inside Out 2", "Deadpool & Wolverine", "Dune: Part Two",
            "Wicked", "Moana 2", "The Wild Robot")
ratings <- data.frame(
  person = rep(paste("Person", 1:5), each = 6),
  movie = rep(movies, 5),
  rating = c(5, 4, 4, NA, 5, 4,
             4, NA, 5, 4, 3, NA,
             5, 3, NA, 5, 4, 5,
             4, 4, 5, NA, 4, 5,
             NA, 5, 4, 4, 5, 4)
)
stopifnot(!anyDuplicated(ratings[c("person", "movie")]),
          all(is.na(ratings$rating) | ratings$rating %in% 1:5))
knitr::kable(ratings)
person movie rating
Person 1 Inside Out 2 5
Person 1 Deadpool & Wolverine 4
Person 1 Dune: Part Two 4
Person 1 Wicked NA
Person 1 Moana 2 5
Person 1 The Wild Robot 4
Person 2 Inside Out 2 4
Person 2 Deadpool & Wolverine NA
Person 2 Dune: Part Two 5
Person 2 Wicked 4
Person 2 Moana 2 3
Person 2 The Wild Robot NA
Person 3 Inside Out 2 5
Person 3 Deadpool & Wolverine 3
Person 3 Dune: Part Two NA
Person 3 Wicked 5
Person 3 Moana 2 4
Person 3 The Wild Robot 5
Person 4 Inside Out 2 4
Person 4 Deadpool & Wolverine 4
Person 4 Dune: Part Two 5
Person 4 Wicked NA
Person 4 Moana 2 4
Person 4 The Wild Robot 5
Person 5 Inside Out 2 NA
Person 5 Deadpool & Wolverine 5
Person 5 Dune: Part Two 4
Person 5 Wicked 4
Person 5 Moana 2 5
Person 5 The Wild Robot 4

2. User-item matrix and exploration

R <- matrix(ratings$rating, nrow = 5, byrow = TRUE,
            dimnames = list(unique(ratings$person), movies))
knitr::kable(R)
Inside Out 2 Deadpool & Wolverine Dune: Part Two Wicked Moana 2 The Wild Robot
Person 1 5 4 4 NA 5 4
Person 2 4 NA 5 4 3 NA
Person 3 5 3 NA 5 4 5
Person 4 4 4 5 NA 4 5
Person 5 NA 5 4 4 5 4
knitr::kable(data.frame(
  Participants = nrow(R), Movies = ncol(R),
  Observed = sum(!is.na(R)), Missing = sum(is.na(R)),
  Density = mean(!is.na(R)), Global_mean = mean(R, na.rm = TRUE)
), digits = 3)
Participants Movies Observed Missing Density Global_mean
5 6 24 6 0.8 4.333
old <- par(mar = c(8, 6, 2, 1))
for_plot <- R[nrow(R):1, , drop = FALSE]
image(seq_len(ncol(R)), seq_len(nrow(R)),
      t(ifelse(is.na(for_plot), 0, for_plot)),
      col = c("gray85", "#f4d9c1", "#edb78f", "#e4a74e", "#80b6bc", "#23777c"),
      breaks = seq(-0.5, 5.5, 1), axes = FALSE, xlab = "", ylab = "")
axis(1, at = seq_len(ncol(R)), labels = movies, las = 2, cex.axis = .75)
axis(2, at = seq_len(nrow(R)), labels = rev(rownames(R)), las = 1)
for (i in seq_len(nrow(for_plot))) for (j in seq_len(ncol(for_plot))) {
  text(j, i, ifelse(is.na(for_plot[i,j]), "NA", for_plot[i,j]))
}

Original movie ratings; gray represents unknown ratings.
par(old)

3. Model implementation

Baseline benchmark

The previous assignment estimated a rating using the global mean plus user and movie deviations. The user deviation adjusts rating level but does not change the order of items for a given user. For a fair comparison, all means are recalculated using only training data in each fold. Predictions are constrained to the 1–5 rating scale.

clip_rating <- function(x) pmin(5, pmax(1, x))
baseline <- function(train, u, i) {
  g <- mean(train, na.rm = TRUE)
  um <- mean(train[u, ], na.rm = TRUE)
  im <- mean(train[, i], na.rm = TRUE)
  if (!is.finite(um)) um <- g
  if (!is.finite(im)) im <- g
  clip_rating(um + im - g)
}

Pearson similarity and UBCF

For each target user, I compare their ratings with other users on movies both have rated. I require at least three shared ratings, exclude constant rating vectors (undefined correlation), and retain only positive correlations. A tiny numerical tolerance excludes correlations effectively equal to zero. The predicted rating is the similarity-weighted mean of eligible neighbors’ ratings for the target movie.

\[\hat r_{ui}=\frac{\sum_{v\in N(u,i)}s_{uv}r_{vi}}{\sum_{v\in N(u,i)}s_{uv}}\]

If no eligible neighbor exists, I use the baseline estimate as a fallback. This ensures complete prediction coverage while tracking how often collaborative filtering itself can make a prediction.

find_neighbors <- function(train, u, i, min_shared = 3) {
  out <- data.frame(user = integer(), shared = integer(),
                    similarity = numeric(), rating = numeric())
  for (v in setdiff(seq_len(nrow(train)), u)) {
    shared <- !is.na(train[u, ]) & !is.na(train[v, ])
    n <- sum(shared)
    if (n < min_shared || is.na(train[v, i])) next
    x <- train[u, shared]; y <- train[v, shared]
    if (sd(x) == 0 || sd(y) == 0) next
    s <- cor(x, y, method = "pearson")
    if (is.finite(s) && s > 1e-12) {
      out <- rbind(out, data.frame(user = v, shared = n,
                       similarity = s, rating = train[v, i]))
    }
  }
  out[order(-out$similarity), , drop = FALSE]
}
predict_ubcf <- function(train, u, i) {
  neighbors <- find_neighbors(train, u, i)
  b <- baseline(train, u, i)
  if (nrow(neighbors) == 0) {
    return(list(prediction = b, baseline = b,
                neighbors = 0L, method = "Baseline fallback"))
  }
  list(prediction = clip_rating(weighted.mean(neighbors$rating,
                                              neighbors$similarity)),
       baseline = b, neighbors = nrow(neighbors), method = "UBCF")
}

Worked example: Person 2 and The Wild Robot

u <- match("Person 2", rownames(R))
i <- match("The Wild Robot", colnames(R))
example_neighbors <- find_neighbors(R, u, i)
example_neighbors$user <- rownames(R)[example_neighbors$user]
knitr::kable(example_neighbors, digits = 3)
user shared similarity rating
Person 3 3 1.000 5
Person 4 3 0.866 5
knitr::kable(as.data.frame(predict_ubcf(R, u, i)), digits = 3)
prediction baseline neighbors method
5 4.167 2 UBCF

4. Personalized recommendations

The output is a ranked list of unseen movies for each participant, with predicted rating, baseline rating, number of eligible neighbors, and prediction method. I recommend the top-ranked unseen movie per user. Ties are broken alphabetically; no already-rated movies are recommended.

missing <- which(is.na(R), arr.ind = TRUE)
make_row <- function(train, u, i) {
  p <- predict_ubcf(train, u, i)
  data.frame(person = rownames(train)[u], movie = colnames(train)[i],
             prediction = p$prediction, baseline = p$baseline,
             neighbors = p$neighbors, method = p$method)
}
recommendations <- do.call(rbind, lapply(seq_len(nrow(missing)), function(k) {
  make_row(R, missing[k, 1], missing[k, 2])
}))
recommendations <- recommendations[order(recommendations$person,
                      -recommendations$prediction, recommendations$movie), ]
recommendations$rank <- ave(seq_len(nrow(recommendations)),
                            recommendations$person, FUN = seq_along)
rownames(recommendations) <- NULL
knitr::kable(recommendations, digits = 3)
person movie prediction baseline neighbors method rank
Person 1 Wicked 4.343 4.400 2 UBCF 1
Person 2 The Wild Robot 5.000 4.167 2 UBCF 1
Person 2 Deadpool & Wolverine 3.464 3.667 2 UBCF 2
Person 3 Dune: Part Two 4.835 4.567 3 UBCF 1
Person 4 Wicked 4.376 4.400 2 UBCF 1
Person 5 Inside Out 2 5.000 4.567 1 UBCF 1
top1 <- subset(recommendations, rank == 1)
knitr::kable(top1, digits = 3)
person movie prediction baseline neighbors method rank
1 Person 1 Wicked 4.343 4.400 2 UBCF 1
2 Person 2 The Wild Robot 5.000 4.167 2 UBCF 1
4 Person 3 Dune: Part Two 4.835 4.567 3 UBCF 1
5 Person 4 Wicked 4.376 4.400 2 UBCF 1
6 Person 5 Inside Out 2 5.000 4.567 1 UBCF 1
old <- par(mar = c(10, 4, 2, 1))
barplot(t(as.matrix(recommendations[c("baseline", "prediction")])),
        beside = TRUE, ylim = c(0, 5.7), col = c("#91a5b8", "#23777c"),
        names.arg = paste(recommendations$person, recommendations$movie, sep = ": "),
        las = 2, cex.names = .65, ylab = "Predicted rating",
        legend.text = c("Global baseline", "UBCF + fallback"),
        args.legend = list(x = "topright", bty = "n", cex = .8))

Predicted ratings for the six originally unrated movies.
par(old)

5. Model evaluation

Because there are only 24 observed ratings, I use leave-one-out cross-validation rather than a single random split. Each fold hides exactly one observed rating, recalculates similarities and baseline estimates from the remaining 23 observations, and predicts the held-out rating. The original six missing ratings remain unknown throughout evaluation. No held-out rating is used for training or neighbor selection.

observed <- which(!is.na(R), arr.ind = TRUE)
cv <- do.call(rbind, lapply(seq_len(nrow(observed)), function(k) {
  u <- observed[k, 1]; i <- observed[k, 2]
  actual <- R[u, i]
  train <- R
  train[u, i] <- NA_real_
  row <- make_row(train, u, i)
  row$actual <- actual
  row
}))
stopifnot(nrow(cv) == sum(!is.na(R)),
          all(is.finite(cv$prediction)), all(is.finite(cv$baseline)))
knitr::kable(cv, digits = 3)
person movie prediction baseline neighbors method actual
Person 1 Inside Out 2 4.279 4.279 0 Baseline fallback 5
Person 2 Inside Out 2 4.319 4.319 0 Baseline fallback 4
Person 3 Inside Out 2 4.000 4.279 1 UBCF 5
Person 4 Inside Out 2 5.000 4.819 1 UBCF 4
Person 1 Deadpool & Wolverine 5.000 4.152 1 UBCF 4
Person 3 Deadpool & Wolverine 4.000 4.692 1 UBCF 3
Person 4 Deadpool & Wolverine 3.000 4.152 1 UBCF 4
Person 5 Deadpool & Wolverine 4.000 3.612 1 UBCF 5
Person 1 Dune: Part Two 4.000 4.819 1 UBCF 4
Person 2 Dune: Part Two 3.696 3.696 0 Baseline fallback 5
Person 4 Dune: Part Two 4.279 4.279 0 Baseline fallback 5
Person 5 Dune: Part Two 4.000 4.819 1 UBCF 4
Person 2 Wicked 4.152 4.152 0 Baseline fallback 4
Person 3 Wicked 3.946 3.946 0 Baseline fallback 5
Person 5 Wicked 4.652 4.652 0 Baseline fallback 4
Person 1 Moana 2 4.000 3.946 1 UBCF 5
Person 2 Moana 2 4.442 4.442 0 Baseline fallback 3
Person 3 Moana 2 4.500 4.402 2 UBCF 4
Person 4 Moana 2 4.000 4.402 1 UBCF 4
Person 5 Moana 2 3.946 3.946 0 Baseline fallback 5
Person 1 The Wild Robot 4.634 4.819 2 UBCF 4
Person 3 The Wild Robot 4.000 4.279 1 UBCF 5
Person 4 The Wild Robot 4.279 4.279 0 Baseline fallback 5
Person 5 The Wild Robot 4.000 4.819 1 UBCF 4

Evaluation metrics

RMSE penalizes larger prediction errors, whereas MAE measures the average absolute error. Lower values are better. Coverage reports the proportion of test cases with at least one eligible UBCF neighbor before fallback.

\[RMSE=\sqrt{\frac{1}{n}\sum_{j=1}^{n}(r_j-\hat r_j)^2}\]

\[MAE=\frac{1}{n}\sum_{j=1}^{n}|r_j-\hat r_j|\]

rmse <- function(actual, predicted) sqrt(mean((actual - predicted)^2))
mae <- function(actual, predicted) mean(abs(actual - predicted))
metrics <- data.frame(
  Model = c("Global baseline", "UBCF + baseline fallback"),
  RMSE = c(rmse(cv$actual, cv$baseline), rmse(cv$actual, cv$prediction)),
  MAE = c(mae(cv$actual, cv$baseline), mae(cv$actual, cv$prediction))
)
knitr::kable(metrics, digits = 4)
Model RMSE MAE
Global baseline 0.8845 0.7883
UBCF + baseline fallback 0.8358 0.7198
coverage <- mean(cv$neighbors > 0)
knitr::kable(data.frame(Test_cases = nrow(cv),
  UBCF_cases = sum(cv$neighbors > 0),
  Fallback_cases = sum(cv$neighbors == 0),
  UBCF_coverage_pct = 100 * coverage,
  Overall_coverage_pct = 100 * mean(is.finite(cv$prediction))), digits = 2)
Test_cases UBCF_cases Fallback_cases UBCF_coverage_pct Overall_coverage_pct
24 14 10 58.33 100
improvement <- 100 * (1 - metrics[2, 2:3] / metrics[1, 2:3])
knitr::kable(improvement, digits = 2, caption = "Relative error reduction (%)")
Relative error reduction (%)
RMSE MAE
2 5.51 8.69
barplot(as.matrix(metrics[c("RMSE", "MAE")]), beside = TRUE,
        col = c("#91a5b8", "#23777c"), ylim = c(0, 1.2),
        ylab = "Error (rating points)", legend.text = metrics$Model,
        args.legend = list(x = "topright", bty = "n", cex = .8))

Cross-validation errors on the same 24 held-out observations. Lower is better.

6. Results and limitations

The personalized system achieved RMSE of 0.8358 and MAE of 0.7198, compared with 0.8845 and 0.7883 for the baseline. The relative error reductions were 5.5% and 8.7%, respectively. The comparison evaluates the complete system with its fallback, not pure UBCF alone.

UBCF produced direct predictions for 14 of 24 held-out cases. The remaining cases required fallback. Using all observed data for final recommendations, UBCF directly predicted 6 of the 6 originally missing ratings.

The survey is very small and ratings are concentrated between 3 and 5. Pearson similarity based on few common movies may be unstable, and constant rating patterns prevent correlation estimates. Leave-one-out folds overlap considerably, so the observed improvements do not establish statistical significance or generalization to a larger population. Most users have only one unseen movie, which limits meaningful ranking evaluation. I therefore focus on rating prediction metrics rather than claiming reliable Precision@K or Recall@K. Actual ratings for the originally unseen movies remain unknown.

7. Conclusion

This assignment demonstrates how user-specific rating patterns can be incorporated into a personalized recommender. The UBCF system with baseline fallback reduced both prediction errors on this survey, while providing a ranked recommendation for every participant. A larger and more diverse survey would allow more reliable similarity estimates and stronger ranking evaluation.

References

  • Gomez, D. (2026). Data 607 — Recommender Systems introduction. CUNY School of Professional Studies. Course lecture and Quarto source code. Brightspace lecture.
  • Abdelrahman, S. (2026). Week 3A Global Baseline Estimate. RPubs. Original survey data and baseline methodology.