library(dplyr)
## Warning: 程辑包'dplyr'是用R版本4.3.1 来建造的
##
## 载入程辑包:'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: 程辑包'tidyr'是用R版本4.3.1 来建造的
library(ggplot2)
## Warning: 程辑包'ggplot2'是用R版本4.3.1 来建造的
library(recommenderlab)
## Warning: 程辑包'recommenderlab'是用R版本4.3.2 来建造的
## 载入需要的程辑包:Matrix
##
## 载入程辑包:'Matrix'
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
## 载入需要的程辑包:arules
## Warning: 程辑包'arules'是用R版本4.3.2 来建造的
##
## 载入程辑包:'arules'
## The following object is masked from 'package:dplyr':
##
## recode
## The following objects are masked from 'package:base':
##
## abbreviate, write
## 载入需要的程辑包:proxy
## Warning: 程辑包'proxy'是用R版本4.3.1 来建造的
##
## 载入程辑包:'proxy'
## The following object is masked from 'package:Matrix':
##
## as.matrix
## The following objects are masked from 'package:stats':
##
## as.dist, dist
## The following object is masked from 'package:base':
##
## as.matrix
## Registered S3 methods overwritten by 'registry':
## method from
## print.registry_field proxy
## print.registry_entry proxy
library(DT)
## Warning: 程辑包'DT'是用R版本4.3.2 来建造的
library(data.table)
## Warning: 程辑包'data.table'是用R版本4.3.1 来建造的
##
## 载入程辑包:'data.table'
## The following objects are masked from 'package:dplyr':
##
## between, first, last
library(reshape2)
## Warning: 程辑包'reshape2'是用R版本4.3.1 来建造的
##
## 载入程辑包:'reshape2'
## The following objects are masked from 'package:data.table':
##
## dcast, melt
## The following object is masked from 'package:tidyr':
##
## smiths
library(shiny)
## Warning: 程辑包'shiny'是用R版本4.3.1 来建造的
##
## 载入程辑包:'shiny'
## The following objects are masked from 'package:DT':
##
## dataTableOutput, renderDataTable
library(shinydashboard)
## Warning: 程辑包'shinydashboard'是用R版本4.3.2 来建造的
##
## 载入程辑包:'shinydashboard'
## The following object is masked from 'package:graphics':
##
## box
library(data.table)
library(ShinyRatingInput)
library(shinyjs)
## Warning: 程辑包'shinyjs'是用R版本4.3.2 来建造的
##
## 载入程辑包:'shinyjs'
## The following object is masked from 'package:shiny':
##
## runExample
## The following object is masked from 'package:recommenderlab':
##
## show
## The following objects are masked from 'package:arules':
##
## info, show
## The following object is masked from 'package:Matrix':
##
## show
## The following objects are masked from 'package:methods':
##
## removeClass, show
source('helpers.R')
# Set the base URL for the data source
myurl = "https://liangfgithub.github.io/MovieData/"
# Read movie data from the URL, split by "::", and format it into a data frame
movies = readLines(paste0(myurl, 'movies.dat?raw=true'))
movies = strsplit(movies, split = "::", fixed = TRUE, useBytes = TRUE)
movies = matrix(unlist(movies), ncol = 3, byrow = TRUE)
movies = data.frame(movies, stringsAsFactors = FALSE)
colnames(movies) = c('MovieID', 'Title', 'Genres')
movies$MovieID = as.integer(movies$MovieID)
movies$Title = iconv(movies$Title, "latin1", "UTF-8")
# Add image URLs to the movies data frame
small_image_url = "https://liangfgithub.github.io/MovieImages/"
movies$image_url = sapply(movies$MovieID,
function(x) paste0(small_image_url, x, '.jpg?raw=true'))
# Read ratings data from the URL, format and name the columns
ratings = read.csv(paste0(myurl, 'ratings.dat?raw=true'),
sep = ':',
colClasses = c('integer', 'NULL'),
header = FALSE)
colnames(ratings) = c('UserID', 'MovieID', 'Rating', 'Timestamp')
The scheme recommends movies within the user’s preferred genre, prioritizing those with the highest Bayesian average ratings. This method balances both popularity and quality of ratings to provide reliable suggestions.
The first step in our system involves a detailed categorization of movies based on genres. This is achieved by processing the movies dataset to extract and separate each movie into its respective genres. This step is crucial as it lays the foundation for our genre-specific recommendations, ensuring that each movie is accurately classified and can be efficiently retrieved based on genre preferences.
# separate the movie genres
genres = movies[,c(1,2,3)]
genres = genres %>%
separate_rows(Genres, sep = '[|]')
Calculate Average Ratings for Each Movie:
The first step is to calculate the average rating for each movie. This
is achieved by grouping the ratings dataset by
MovieID. For each movie, the number of ratings
(count) and the average rating (ave_ratings)
are computed. This step provides a basic understanding of how each movie
is generally perceived by its audience.
Compute Global Mean of All Ratings:
The next step involves calculating the global mean rating across all
movies, denoted as m. This mean rating represents the
average rating tendency across the entire dataset and serves as a
benchmark for comparing individual movie ratings.
Determine Lower Quartile of Movie Rating
Counts:
To address the issue of movies with fewer ratings potentially skewing
the average, the lower quartile (c) of the movie rating
counts is determined. This statistical measure helps to understand the
distribution of the number of ratings each movie has received, providing
a threshold for comparison.
Apply Bayesian Average Formula:
The Bayesian average formula is applied to adjust each movie’s ratings.
This formula, (ave_ratings * count + c * m) / (count + c),
combines the average rating of each movie with the global mean rating,
adjusted by the respective counts of ratings and the lower quartile
threshold. This approach helps to mitigate the bias that could be
introduced by movies with very few ratings.
Filter and Rank Movies by Genre:
The calculated Bayesian average ratings are then merged with the
genres dataset. This enables the filtering of movies based
on specific genres. Movies within each genre are ranked based on their
Bayesian average ratings, ensuring that the recommendations are tailored
to the user’s genre preferences.
Select Top Movies in Each Genre:
The final step involves selecting the top 10 movies within each genre,
based on their Bayesian average ratings. This selection of movies
represents a balance between popularity and quality, ensuring that the
recommended movies are not only preferred in their respective genres but
also highly rated overall.
# Calculate Average Ratings for Each Movie
# Group the ratings by MovieID, then calculate the count and average rating for each movie
avgrating = ratings %>%
group_by(MovieID) %>%
summarize(count = n(),
ave_ratings = round(mean(Rating), dig=3))
# Calculate Bayesian Average Ratings
# Compute the global mean of all ratings
m = mean(ratings$Rating)
# Determine the lower quartile of movie rating counts
c = quantile(avgrating$count, probs = 0.25)
# Apply Bayesian average formula to adjust movie ratings
scheme = avgrating %>%
mutate(bayesian_ave = (ave_ratings * count + c * m) / (count + c)) %>%
inner_join(genres, by = 'MovieID') %>%
arrange(desc(bayesian_ave)) %>%
group_by(Genres) %>%
slice(1:10) %>%
select(c("MovieID", "Title", "Genres", "bayesian_ave"))
# Prepare the data for creating a sparse matrix
# 'ratings' is assumed to be your original data frame with UserID, MovieID, and Rating columns
user_ids = paste0('u', ratings$UserID) # Prefix 'u' added to user IDs
movie_ids = paste0('m', ratings$MovieID) # Prefix 'm' added to movie IDs
ratings_values = ratings$Rating # Ratings
# Create a data frame to facilitate the creation of the sparse matrix
sparse_matrix_data = data.frame(user = factor(user_ids), movie = factor(movie_ids), rating = ratings_values)
# Generate the sparse matrix using the sparseMatrix function from the Matrix package
Rmat = sparseMatrix(i = as.integer(sparse_matrix_data$user),
j = as.integer(sparse_matrix_data$movie),
x = sparse_matrix_data$rating)
# Set row and column names
rownames(Rmat) = levels(sparse_matrix_data$user)
colnames(Rmat) = levels(sparse_matrix_data$movie)
# Function to calculate row means, excluding zeros
row_means <- function(sparse_mat) {
apply(sparse_mat, 1, function(x) {
non_zeros <- x[x != 0]
if (length(non_zeros) > 0) mean(non_zeros) else 0
})
}
# Calculate means for each row (user)
user_means <- row_means(Rmat)
# Normalize the matrix
normalize_matrix <- function(sparse_mat, means) {
sparse_mat@x <- sparse_mat@x - means[sparse_mat@i + 1]
sparse_mat
}
# Applying the normalization
Rmat_normalized <- normalize_matrix(Rmat, user_means)
# Transpose the matrix to get a movie-user matrix
# num_movies <- 100
num_movies <- ncol(Rmat_normalized)
movie_user_mat <- as.matrix(t(Rmat_normalized)[1:num_movies, ])
similarity_matrix <- 1/2 + 1/2 * as.matrix(proxy::simil(movie_user_mat, method = "cosine", diag = NA, pairwise = TRUE, upper = TRUE))
# Sort and keep top 30 similarities for each movie
top_n_similarity <- function(similarity_row, n = 30) {
# Set non-top-n similarities to NA
sorted_indices <- order(similarity_row, decreasing = TRUE)
similarity_row[sorted_indices[(n+1):length(similarity_row)]] <- NA
similarity_row
}
similarity_matrix <- apply(similarity_matrix, 1, top_n_similarity)
# Round and display specific pairwise similarities
specified_movies <- c('m1', 'm10', 'm100', 'm1510', 'm260', 'm3212')
# specified_movies <- c('m1', 'm10', 'm100', 'm1002')
movie_indices <- match(specified_movies, colnames(similarity_matrix))
pairwise_similarities <- sapply(movie_indices, function(i) {
sapply(movie_indices, function(j) round(similarity_matrix[i, j], 7))
})
colnames(pairwise_similarities) <- specified_movies
rownames(pairwise_similarities) <- specified_movies
print(pairwise_similarities)
## m1 m10 m100 m1510 m260 m3212
## m1 NA NA NA NA 0.6416585 NA
## m10 NA NA NA NA NA NA
## m100 NA NA NA NA NA NA
## m1510 NA NA NA NA NA NA
## m260 0.6416585 NA NA NA NA NA
## m3212 NA NA NA 0.7295948 NA NA
# IBCF function
myIBCF <- function(newuser) {
# Initialize a vector to store predictions
num_movies <- length(newuser)
predictions <- rep(NA, num_movies)
# Iterate over each movie to calculate predictions
for (l in 1:num_movies) {
if (is.na(newuser[l]) || newuser[l] == 0) { # Check if the movie is not rated by the user
similar_movies <- which(!is.na(similarity_matrix[l,])) # Movies similar to movie l
sim_scores <- similarity_matrix[l, similar_movies] # Similarity scores for these movies
# Calculate prediction for movie l
weighted_scores <- sim_scores * newuser[similar_movies]
sum_sim_scores <- sum(sim_scores * (!is.na(newuser[similar_movies])))
if (sum_sim_scores > 0) {
predictions[l] <- sum(weighted_scores) / sum_sim_scores
} else {
predictions[l] <- NA
}
} else {
predictions[l] <- NA
}
}
# Sort predictions and take top 10
top_movies_indices <- order(predictions, decreasing = TRUE)
recommended_movies <- rownames(similarity_matrix)[top_movies_indices]
# Function to convert movie IDs to titles
convertMovieIDtoTitle <- function(movieIDs) {
# Extract numeric part of movie IDs
numericIDs <- as.integer(sub("m", "", movieIDs))
# Find corresponding titles in the movies dataframe
titles <- sapply(numericIDs, function(id) {
title <- movies$Title[which(movies$MovieID == id)]
if (length(title) > 0) {
return(title)
} else {
return(NA)
}
})
return(titles)
}
recommended_movies <- convertMovieIDtoTitle(recommended_movies)
top_recommendations <- recommended_movies[!is.na(predictions[top_movies_indices])]
# If fewer than 10 predictions, suggest additional movies
if (length(top_recommendations) < 10) {
additional_recommendations <- recommended_movies[is.na(predictions[top_movies_indices])]
top_recommendations <- c(top_recommendations, additional_recommendations[1:(10 - length(top_recommendations))])
}
return(top_recommendations[1:min(10, length(top_recommendations))])
}
# Extract ratings for user u1181 and u1351
user_u1181_ratings <- Rmat["u1181", ]
user_u1351_ratings <- Rmat["u1351", ]
# Create a vector for the hypothetical user
# Assuming the matrix has 100 movies, adjust if the number is different
hypothetical_user_ratings <- rep(NA, num_movies)
hypothetical_user_ratings[which(colnames(Rmat) == "m1613")] <- 5
hypothetical_user_ratings[which(colnames(Rmat) == "m1755")] <- 4
# Get recommendations
recommendations_u1181 <- myIBCF(user_u1181_ratings)
recommendations_u1351 <- myIBCF(user_u1351_ratings)
recommendations_hypothetical <- myIBCF(hypothetical_user_ratings)
# Print top 10 recommendations for each user
print("Top 10 recommendations for user u1181:")
## [1] "Top 10 recommendations for user u1181:"
print(recommendations_u1181)
## [1] "My Man Godfrey (1957)"
## [2] "Smoke Signals (1998)"
## [3] "Strange Days (1995)"
## [4] "Go (1999)"
## [5] "Parenthood (1989)"
## [6] "Paralyzing Fear: The Story of Polio in America, A (1998)"
## [7] "Dead Calm (1989)"
## [8] "Smashing Time (1967)"
## [9] "Mister Roberts (1955)"
## [10] "Carlito's Way (1993)"
print("Top 10 recommendations for user u1351:")
## [1] "Top 10 recommendations for user u1351:"
print(recommendations_u1351)
## [1] "Babe: Pig in the City (1998)"
## [2] "Chicken Run (2000)"
## [3] "Stir of Echoes (1999)"
## [4] "Gladiator (2000)"
## [5] "Glory (1989)"
## [6] "Saving Private Ryan (1998)"
## [7] "Fugitive, The (1993)"
## [8] "Star Wars: Episode VI - Return of the Jedi (1983)"
## [9] "Tampopo (1986)"
## [10] "Silence of the Lambs, The (1991)"
print("Top 10 recommendations for the hypothetical user:")
## [1] "Top 10 recommendations for the hypothetical user:"
print(recommendations_hypothetical)
## [1] "Toy Story (1995)" "GoldenEye (1995)"
## [3] "City Hall (1996)" "Curdled (1996)"
## [5] "Ed's Next Move (1996)" "Extreme Measures (1996)"
## [7] "Glimmer Man, The (1996)" "D3: The Mighty Ducks (1996)"
## [9] "Chamber, The (1996)" "Apple Dumpling Gang, The (1975)"
# Define the UI for the Shiny application
ui <- shinyUI(dashboardPage(
skin = "blue",
dashboardHeader(title = "Movie Recommender"),
dashboardSidebar(
sidebarMenu(
menuItem("Recommender by Genre", tabName = "system1", icon = icon("film")),
menuItem("Recommender by Rating", tabName = "system2", icon = icon("star"))
)
),
dashboardBody(includeCSS("movie.css"),
# Tab for Recommender by Genres
tabItems(
tabItem(
tabName = "system1",
fluid = TRUE,
sidebarLayout(
fluidRow(
box(
width = 12,
title = "Step 1: Select your favorite genre",
status = "info",
solidHeader = TRUE,
collapsible = TRUE,
selectInput(
"genre",
"Select a single genre from the dropdown menu",
sort(unique(genres$Genres))
)
)
),
fluidRow(
useShinyjs(),
box(
width = 12,
status = "info",
solidHeader = TRUE,
title = "Step 2: Discover movies you might like",
br(),
withBusyIndicatorUI(
actionButton("btn", "Click here to get your recommendations", class = "btn-warning")
),
br(),
tableOutput("results1")
)
)
)
),
# Tab for Recommender by Rating
tabItem(
tabName = "system2",
fluidRow(
box(width = 12, title = "Step 1: Rate as many movies as possible", status = "info", solidHeader = TRUE, collapsible = TRUE,
div(class = "rateitems",
uiOutput('ratings')
)
)
),
fluidRow(
useShinyjs(),
box(
width = 12,
status = "info",
solidHeader = TRUE,
title = "Step 2: Discover movies you might like",
br(),
withBusyIndicatorUI(actionButton("btn_rate", "Get Recommendations", class = "btn-warning")),
br(),
tableOutput("results2")
)
)
)
)
)
))
# Function to get user ratings from the Shiny app input
get_user_ratings <- function(input_values) {
# Extract movie IDs from the input values
movie_ids <- sapply(names(input_values), function(x) {
if (grepl("select_", x)) {
as.integer(sub("select_", "", x))
} else {
NA
}
})
# Remove NAs
movie_ids <- movie_ids[!is.na(movie_ids)]
# Create a vector with NA for all movies
user_ratings <- rep(NA, nrow(movies))
# Update the vector with user ratings
for (id in movie_ids) {
rating_input_id <- paste0("select_", id)
if (!is.null(input_values[[rating_input_id]])) {
user_ratings[id] <- input_values[[rating_input_id]]
}
}
# Return the user ratings vector
return(user_ratings)
}
server <- function(input, output) {
# Logic for Recommender by Genres
df1 <- eventReactive(input$btn, {
withBusyIndicatorServer("btn", {
useShinyjs()
jsCode <- "document.querySelector('[data-widget=collapse]').click();"
runjs(jsCode)
recom_result1 <- scheme %>% filter(Genres == input$genre)
})
})
output$results1 <- renderUI({
num_rows <- 2
num_movies <- 5
recom_result1 <- df1()
lapply(1:num_rows, function(i) {
list(fluidRow(lapply(1:num_movies, function(j) {
box(width = 2, status = "success", solidHeader = TRUE, title = paste0("Rank ", (i - 1) * num_movies + j),
div(style = "text-align:center",
a(img(src = movies$image_url[movies$MovieID == recom_result1$MovieID[(i - 1) * num_movies + j]], height = 150))
),
div(style="text-align:center; font-size: 100%",
strong(movies$Title[movies$MovieID == recom_result1$MovieID[(i - 1) * num_movies + j]])
)
)
})))
})
})
# Logic for Recommender by Rating
# show the movies to be rated
output$ratings <- renderUI({
num_rows <- 20
num_movies <- 6 # movies per row
lapply(1:num_rows, function(i) {
list(fluidRow(lapply(1:num_movies, function(j) {
list(box(width = 2,
div(style = "text-align:center", img(src = movies$image_url[(i - 1) * num_movies + j], height = 150)),
#div(style = "text-align:center; color: #999999; font-size: 80%", books$authors[(i - 1) * num_books + j]),
div(style = "text-align:center", strong(movies$Title[(i - 1) * num_movies + j])),
div(style = "text-align:center; font-size: 150%; color: #f0ad4e;", ratingInput(paste0("select_", movies$MovieID[(i - 1) * num_movies + j]), label = "", dataStop = 5)))) #00c0ef
})))
})
})
# Calculate recommendations when the sbumbutton is clicked
df2 <- eventReactive(input$btn_rate, {
withBusyIndicatorServer("btn_rate", { # showing the busy indicator
# hide the rating container
useShinyjs()
jsCode <- "document.querySelector('[data-widget=collapse]').click();"
runjs(jsCode)
# Extract user ratings
user_ratings <- get_user_ratings(input)
# Get recommendations
recommendations <- myIBCF(user_ratings)
recommended_movies <- movies[movies$MovieID %in% recommendations, ]
# Create a data table for display
recom_results <- data.table(
Rank = 1:nrow(recommended_movies),
MovieID = recommended_movies$MovieID,
Title = recommended_movies$Title,
Genres = recommended_movies$Genres
)
return(recom_results)
}) # still busy
}) # clicked on button
# display the recommendations
output$results2 <- renderUI({
num_rows <- 2
num_movies <- 5
recom_result <- df2()
lapply(1:num_rows, function(i) {
list(fluidRow(lapply(1:num_movies, function(j) {
box(width = 2, status = "success", solidHeader = TRUE, title = paste0("Rank ", (i - 1) * num_movies + j),
div(style = "text-align:center",
a(img(src = movies$image_url[recom_result$MovieID[(i - 1) * num_movies + j]], height = 150))
),
div(style="text-align:center; font-size: 100%",
strong(movies$Title[recom_result$MovieID[(i - 1) * num_movies + j]])
)
)
}))) # columns
}) # rows
}) # renderUI function
}
# Run the application
shinyApp(ui = ui, server = server)