### Install Development Version of recommenderlab Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Install the current development version of the recommenderlab package from the r-universe repository. This requires specifying the repository URL. ```r install.packages("recommenderlab", repos = c("https://mhahsler.r-universe.dev", "https://cloud.r-project.org/")) ``` -------------------------------- ### Install Stable CRAN Version of recommenderlab Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Use this command to install the latest stable version of the recommenderlab package from CRAN within an R session. ```r install.packages("recommenderlab") ``` -------------------------------- ### Load and Prepare MovieLense Data Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Loads the MovieLense dataset and filters users with more than 100 ratings. Ensure the 'recommenderlab' package is installed and loaded. ```r set.seed(1234) library("recommenderlab") data("MovieLense") MovieLense100 <- MovieLense[rowCounts(MovieLense) > 100, ] MovieLense100 ``` -------------------------------- ### Set up Cross-Validation for Evaluation Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Configures a 10-fold cross-validation scheme for evaluating recommender algorithms. This setup is used to compare different recommendation methods. ```r scheme <- evaluationScheme(MovieLense100, method = "cross-validation", k = 10, given = -5, goodRating = 4) scheme ``` -------------------------------- ### Generate Recommendations and Predictions Source: https://context7.com/mhahsler/recommenderlab/llms.txt Demonstrates basic model training, top-N recommendation generation, and rating prediction workflows. ```r # Create Item-Based Collaborative Filtering recommender rec_ibcf <- Recommender(train, method = "IBCF", parameter = list(k = 30, method = "cosine")) # Create SVD-based recommender rec_svd <- Recommender(train, method = "SVD", parameter = list(k = 50)) # Create Popular Items recommender (non-personalized baseline) rec_pop <- Recommender(train, method = "POPULAR") # Generate top-N recommendations top5 <- predict(rec_ubcf, test, n = 5, type = "topNList") top5 # Recommendations as 'topNList' with n = 5 for 10 users. # View recommendations as list as(top5, "list") # Get best 3 from top-5 list best3 <- bestN(top5, n = 3) as(best3, "list") # Predict ratings for all items predicted_ratings <- predict(rec_ubcf, test, type = "ratings") as(predicted_ratings, "matrix")[1:3, 1:5] # Get complete rating matrix including known ratings full_matrix <- predict(rec_ubcf, test, type = "ratingMatrix") ``` -------------------------------- ### Sample Data Source: https://context7.com/mhahsler/recommenderlab/llms.txt Samples 1000 users from the Jester5k dataset after setting a random seed for reproducibility. ```R set.seed(1234) sample_data <- sample(Jester5k, 1000) ``` -------------------------------- ### Create Train/Test Split Evaluation Scheme Source: https://context7.com/mhahsler/recommenderlab/llms.txt Sets up an evaluation scheme using a simple train/test split. The 'given' parameter specifies the number of items presented to the recommender for training/prediction. ```r library("recommenderlab") data("Jester5k") # Simple train/test split (90% train, 10% test) # given=15 means 15 items given to recommender, rest withheld for testing scheme_split <- evaluationScheme(Jester5k[1:1000], method = "split", train = 0.9, given = 15, goodRating = 5) scheme_split ``` -------------------------------- ### Load Built-in Datasets Source: https://context7.com/mhahsler/recommenderlab/llms.txt Access real-world datasets included with the recommenderlab package for experimentation and benchmarking, such as MovieLense. ```r library("recommenderlab") # MovieLense: 100K movie ratings (1-5 stars) data("MovieLense") MovieLense ``` -------------------------------- ### Create Bootstrap Evaluation Scheme Source: https://context7.com/mhahsler/recommenderlab/llms.txt Sets up an evaluation scheme using bootstrap sampling. The 'given' parameter with a negative value (e.g., -5) indicates the 'All-but-x' protocol, withholding a specified number of items. ```r # Bootstrap sampling with All-but-5 protocol (negative = all-but-x) scheme_boot <- evaluationScheme(Jester5k[1:1000], method = "bootstrap", k = 5, train = 0.9, given = -5, # All but 5 items goodRating = 5) ``` -------------------------------- ### Convert Recommendations to List Format Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Converts the generated top-N recommendations into a list format for easier inspection or further processing. This is useful for viewing the recommended items. ```r as(pre, "list") ``` -------------------------------- ### Generate Top-N Recommendations Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Creates top-N recommendations for new users using a trained recommender model. Specify the trained model and the users for whom to generate recommendations. ```r pre <- predict(rec, MovieLense100[301:302], n = 5) pre ``` -------------------------------- ### Evaluate Recommender Algorithms Source: https://context7.com/mhahsler/recommenderlab/llms.txt Use the `evaluate` function to run recommender algorithms through an evaluation scheme and compute performance metrics. Requires setting up an `evaluationScheme` first. ```r library("recommenderlab") data("Jester5k") # Create evaluation scheme scheme <- evaluationScheme(Jester5k[1:1000], method = "cross-validation", k = 4, given = 3, goodRating = 5) # Evaluate single algorithm for top-N recommendations results_pop <- evaluate(scheme, method = "POPULAR", type = "topNList", n = c(1, 3, 5, 10, 15, 20)) results_pop ``` ```r # Get confusion matrices getConfusionMatrix(results_pop)[[1]] # First fold results ``` ```r # Average across all folds avg(results_pop) ``` ```r # Compare multiple algorithms algorithms <- list( "random" = list(name = "RANDOM", param = NULL), "popular" = list(name = "POPULAR", param = NULL), "UBCF" = list(name = "UBCF", param = list(nn = 50)), "IBCF" = list(name = "IBCF", param = list(k = 50)), "SVD" = list(name = "SVD", param = list(k = 50)) ) results <- evaluate(scheme, algorithms, type = "topNList", n = c(1, 3, 5, 10, 15, 20), progress = TRUE) ``` ```r # Plot ROC curves plot(results, annotate = TRUE, legend = "bottomright") ``` ```r # Plot Precision-Recall curves plot(results, "prec/rec", annotate = TRUE, legend = "topleft") ``` ```r # Evaluate rating predictions (RMSE, MSE, MAE) results_ratings <- evaluate(scheme, algorithms, type = "ratings") plot(results_ratings, ylim = c(0, 10)) ``` -------------------------------- ### Create Cross-Validation Evaluation Scheme Source: https://context7.com/mhahsler/recommenderlab/llms.txt Sets up a k-fold cross-validation evaluation scheme. The 'given' parameter defines the number of items known to the recommender for each fold. ```r # 10-fold cross-validation with Given-3 protocol scheme_cv <- evaluationScheme(Jester5k[1:1000], method = "cross-validation", k = 10, given = 3, goodRating = 5) ``` -------------------------------- ### Load and Inspect Jester5k Dataset Source: https://context7.com/mhahsler/recommenderlab/llms.txt Loads the Jester5k dataset, which contains ratings for 100 jokes by 5000 users. Displays the dimensions and type of the rating matrix. ```R data("Jester5k") Jester5k ``` -------------------------------- ### Load and Inspect MSWeb Dataset Source: https://context7.com/mhahsler/recommenderlab/llms.txt Loads the MSWeb dataset, containing binary web browsing data. Displays the dimensions and type of the rating matrix. ```R data("MSWeb") MSWeb ``` -------------------------------- ### Create and Use Hybrid Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Combines multiple recommender algorithms (POPULAR, UBCF, IBCF) using weighted averaging to create a hybrid recommender. Predictions are generated for a test set. ```r library("recommenderlab") data("Jester5k") train <- Jester5k[1:4000] test <- Jester5k[4001:4010] # Train individual recommenders rec_pop <- Recommender(train, method = "POPULAR") rec_ubcf <- Recommender(train, method = "UBCF", param = list(nn = 50)) rec_ibcf <- Recommender(train, method = "IBCF", param = list(k = 50)) # Create hybrid recommender with weighted averaging rec_hybrid <- HybridRecommender( rec_pop, rec_ubcf, rec_ibcf, weights = c(0.2, 0.5, 0.3), # Weight for each recommender aggregation_type = "sum" # "sum", "max", or "min" ) # Generate hybrid recommendations hybrid_recs <- predict(rec_hybrid, test, n = 10) as(hybrid_recs, "list")[[1]] ``` -------------------------------- ### Create Hybrid Recommender via Recommender Interface Source: https://context7.com/mhahsler/recommenderlab/llms.txt An alternative method to create a hybrid recommender by specifying recommender types, parameters, weights, and aggregation type directly within the Recommender function. ```r # Alternative: Create hybrid through Recommender interface rec_hybrid2 <- Recommender(train, method = "HYBRID", parameter = list( recommenders = list( list(name = "POPULAR", param = NULL), list(name = "UBCF", param = list(nn = 50)), list(name = "IBCF", param = list(k = 30)) ), weights = c(0.2, 0.5, 0.3), aggregation_type = "sum" )) ``` -------------------------------- ### Create Binary Rating Matrix from Matrix Source: https://context7.com/mhahsler/recommenderlab/llms.txt Converts a standard R matrix of 0s and 1s into a sparse binaryRatingMatrix, suitable for implicit feedback. ```r library("recommenderlab") # Create binary matrix from regular matrix m_bin <- matrix(c(1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1), nrow = 3, byrow = TRUE, dimnames = list(user = c("u1", "u2", "u3"), item = c("i1", "i2", "i3", "i4", "i5"))) r_bin <- as(m_bin, "binaryRatingMatrix") r_bin ``` -------------------------------- ### Evaluate Multiple Recommendation Algorithms Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Evaluates several recommendation algorithms including RANDOM, POPULAR, UBCF, and IBCF using the defined cross-validation scheme. This step is crucial for comparing algorithm performance. ```r algorithms <- list(`random items` = list(name = "RANDOM", param = NULL), `popular items` = list(name = "POPULAR", param = NULL), `user-based CF` = list(name = "UBCF", param = list(nn = 3)), `item-based CF` = list(name = "IBCF", param = list(k = 100))) results <- evaluate(scheme, algorithms, type = "topNList", n = c(1, 3, 5, 10), progress = FALSE) ``` -------------------------------- ### Train ALS Implicit Feedback Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains an ALS recommender model specifically for implicit feedback data. The training data must be binarized first. Requires the 'recommenderlab' package. ```r train_bin <- binarize(train, minRating = 5) rec_als_implicit <- Recommender(train_bin, method = "ALS_implicit", parameter = list( n_factors = 10, regularization = 0.1, alpha = 10 )) ``` -------------------------------- ### Generate Recommendations with AR Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Generates item recommendations for a test set using a trained AR recommender. The output is a list of recommended items for each user. ```r test <- jester_bin[3001:3010] recs <- predict(rec_ar, test, n = 5) as(recs, "list") ``` -------------------------------- ### Train ALS Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains an Alternating Least Squares (ALS) recommender model with specified parameters for explicit feedback. Requires the 'recommenderlab' package. ```r rec_als <- Recommender(train, method = "ALS", parameter = list( n_factors = 10, regularization = 0.1, n_iterations = 10, normalize = "center" )) ``` -------------------------------- ### Train User-Based Collaborative Filtering Model Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Trains a user-based collaborative filtering recommender model using a subset of the prepared data. This is suitable for initial model training. ```r train <- MovieLense100[1:300] rec <- Recommender(train, method = "UBCF") rec ``` -------------------------------- ### User-Based Collaborative Filtering (UBCF) Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains a UBCF model using similarity measures and normalization, including support for binary data. ```r library("recommenderlab") data("MovieLense") # Use users with more than 50 ratings for quality MovieLense100 <- MovieLense[rowCounts(MovieLense) > 50] # Train UBCF recommender with custom parameters rec <- Recommender(MovieLense100[1:500], method = "UBCF", parameter = list( method = "cosine", # Similarity measure nn = 25, # Number of nearest neighbors weighted = TRUE, # Weight by similarity normalize = "center", # Normalize ratings min_matching_items = 0, # Min shared items for similarity min_predictive_items = 0 # Min predictive items )) # Get model details model <- getModel(rec) names(model) # "description", "data", "method", "nn", "weighted", etc. # Generate recommendations for new users new_users <- MovieLense100[501:505] recommendations <- predict(rec, new_users, n = 10) as(recommendations, "list")[[1]] # Top 10 movies for first user # Also works for binary data with Jaccard similarity MovieLense_bin <- binarize(MovieLense100, minRating = 4) rec_bin <- Recommender(MovieLense_bin[1:500], method = "UBCF", parameter = list(method = "jaccard", nn = 25)) ``` -------------------------------- ### SVD and Matrix Factorization Source: https://context7.com/mhahsler/recommenderlab/llms.txt Implements SVD and Funk SVD models for latent factor discovery. ```r library("recommenderlab") data("Jester5k") train <- Jester5k[1:4000] test <- Jester5k[4001:4100] # SVD with column-mean imputation rec_svd <- Recommender(train, method = "SVD", parameter = list( k = 50, # Number of latent factors normalize = "center" )) # Funk SVD (gradient descent optimization) rec_svdf <- Recommender(train, method = "SVDF", parameter = list( k = 10, # Number of features gamma = 0.015, # Regularization lambda = 0.001, # Learning rate min_epochs = 50, max_epochs = 200, verbose = FALSE )) ``` -------------------------------- ### Train Association Rule Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains an Association Rule (AR) based recommender using binarized rating data. Requires the 'recommenderlab' package and arules package. Parameters like support, confidence, and maxlen can be tuned. ```r library("recommenderlab") data("Jester5k") # Convert to binary ratings jester_bin <- binarize(Jester5k, minRating = 5) jester_bin <- jester_bin[rowCounts(jester_bin) > 10] # Train association rule-based recommender rec_ar <- Recommender(jester_bin[1:3000], method = "AR", parameter = list( support = 0.01, # Minimum support confidence = 0.3, # Minimum confidence maxlen = 3, # Max rule length sort_measure = "confidence", sort_decreasing = TRUE )) ``` -------------------------------- ### Image Plot of Rating Matrix Source: https://context7.com/mhahsler/recommenderlab/llms.txt Creates an image plot of the first 100 users and 100 movies from the MovieLense dataset to visualize the rating matrix. ```R image(MovieLense[1:100, 1:100], main = "MovieLense Ratings") ``` -------------------------------- ### Item-Based Collaborative Filtering (IBCF) Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains an IBCF model using precomputed item similarities, suitable for large datasets. ```r library("recommenderlab") data("MovieLense") MovieLense100 <- MovieLense[rowCounts(MovieLense) > 50] # Train IBCF recommender rec <- Recommender(MovieLense100[1:500], method = "IBCF", parameter = list( k = 30, # Number of similar items to keep method = "cosine", # Similarity measure normalize = "center", # Normalize ratings normalize_sim_matrix = FALSE, alpha = 0.5, # For conditional similarity na_as_zero = FALSE )) # Inspect the model (reduced similarity matrix) model <- getModel(rec) dim(model$sim) # k x n_items sparse similarity matrix # Recommendations based on item similarity test_users <- MovieLense100[501:510] recs <- predict(rec, test_users, n = 5) as(recs, "list") # IBCF for binary data MovieLense_bin <- binarize(MovieLense100, minRating = 4) rec_bin <- Recommender(MovieLense_bin[1:500], method = "IBCF", parameter = list(k = 30, method = "Jaccard")) ``` -------------------------------- ### Inspect Association Rules Model Source: https://context7.com/mhahsler/recommenderlab/llms.txt Retrieves and inspects the association rules learned by the AR recommender model. Displays the top rules based on the sorting measure. ```r model <- getModel(rec_ar) arules::inspect(head(model$rule_base, 5)) ``` -------------------------------- ### Create Real Rating Matrix from Data Frame Source: https://context7.com/mhahsler/recommenderlab/llms.txt Converts a data frame with user, item, and rating columns into a realRatingMatrix. ```r # Create from data.frame with user/item/rating columns df <- data.frame( user = c("u1", "u1", "u2", "u2", "u3"), item = c("i1", "i2", "i1", "i3", "i2"), rating = c(5, 3, 4, 5, 2) ) r_df <- as(df, "realRatingMatrix") ``` -------------------------------- ### Train User-Based Collaborative Filtering Recommender Source: https://context7.com/mhahsler/recommenderlab/llms.txt Trains a User-Based Collaborative Filtering (UBCF) recommender model using specified parameters like nearest neighbors (nn) and similarity method. ```r library("recommenderlab") data("Jester5k") # Split data into training and test sets train <- Jester5k[1:4000] test <- Jester5k[4001:4010] # View available recommender methods for real rating data recommenderRegistry$get_entries(dataType = "realRatingMatrix") # Create User-Based Collaborative Filtering recommender rec_ubcf <- Recommender(train, method = "UBCF", parameter = list(nn = 50, method = "cosine")) rec_ubcf ``` -------------------------------- ### Compute Similarity and Dissimilarity Source: https://context7.com/mhahsler/recommenderlab/llms.txt Use `similarity` and `dissimilarity` functions to compute user-user or item-item similarities using various measures. Supports constraints like minimum matching items. ```r library("recommenderlab") data("Jester5k") r <- Jester5k[1:100, 1:20] # User-user similarity (Cosine) user_sim <- similarity(r, method = "cosine", which = "users") as.matrix(user_sim)[1:5, 1:5] ``` ```r # Item-item similarity (Pearson correlation) item_sim <- similarity(r, method = "pearson", which = "items") as.matrix(item_sim)[1:5, 1:5] ``` ```r # Cross-similarity between two sets of users sim_cross <- similarity(r[1:10], r[11:20], method = "cosine") ``` ```r # With minimum matching items constraint sim_constrained <- similarity(r, method = "cosine", which = "users", min_matching = 5, # At least 5 shared items min_predictive = 3) # At least 3 predictive items ``` ```r # Dissimilarity (distance) user_dist <- dissimilarity(r, method = "cosine", which = "users") as.matrix(user_dist)[1:5, 1:5] ``` ```r # Binary data similarity with Jaccard r_bin <- binarize(r, minRating = 5) jaccard_sim <- similarity(r_bin, method = "jaccard", which = "items") ``` ```r # Conditional probability-based similarity for items cond_sim <- similarity(r_bin, method = "conditional", which = "items") ``` -------------------------------- ### Visualize Rating Distribution Source: https://context7.com/mhahsler/recommenderlab/llms.txt Generates histograms to visualize the distribution of ratings in the Jester5k dataset, the number of ratings per user in MovieLense, and the average rating per movie in MovieLense. ```R hist(getRatings(Jester5k), breaks = 100, main = "Jester Rating Distribution") hist(rowCounts(MovieLense), breaks = 50, main = "Ratings per User") hist(colMeans(MovieLense), breaks = 30, main = "Average Rating per Movie") ``` -------------------------------- ### Inspect Movie Metadata Source: https://context7.com/mhahsler/recommenderlab/llms.txt Displays the first few rows of the MovieLenseMeta dataset, showing movie titles and their release years. ```R head(MovieLenseMeta) ``` -------------------------------- ### Inspect User Metadata Source: https://context7.com/mhahsler/recommenderlab/llms.txt Displays the first few rows of the MovieLenseUser dataset, showing user IDs, age, sex, occupation, and zip codes. ```R head(MovieLenseUser) ``` -------------------------------- ### Create Real Rating Matrix from Matrix Source: https://context7.com/mhahsler/recommenderlab/llms.txt Converts a standard R matrix into a sparse realRatingMatrix. Handles missing values (NA). ```r library("recommenderlab") # Create rating matrix from a regular matrix m <- matrix(c(5, 3, NA, 1, 4, NA, NA, 2, 5, NA, 3, 4, 3, NA, 4, 2, NA, 5), nrow = 3, byrow = TRUE, dimnames = list(user = c("u1", "u2", "u3"), item = c("i1", "i2", "i3", "i4", "i5", "i6"))) r <- as(m, "realRatingMatrix") r ``` -------------------------------- ### View Joke Texts Source: https://context7.com/mhahsler/recommenderlab/llms.txt Displays the first few entries of the JesterJokes dataset, which contains the text of jokes. ```R head(JesterJokes) ``` -------------------------------- ### Plot Evaluation Results Source: https://github.com/mhahsler/recommenderlab/blob/master/README.md Plots the True Negative Rate (TNR) vs. True Positive Rate (TPR) for top-N lists of different lengths generated by the evaluated algorithms. This visualization helps in understanding algorithm trade-offs. ```r plot(results, annotate = 2, legend = "topleft") ``` -------------------------------- ### Calculate Prediction Accuracy Source: https://context7.com/mhahsler/recommenderlab/llms.txt Use `calcPredictionAccuracy` to compute error metrics for rating predictions and classification metrics for top-N recommendations. Requires a trained recommender and an evaluation scheme. ```r library("recommenderlab") data("Jester5k") # Create evaluation scheme e <- evaluationScheme(Jester5k[1:1000], method = "split", train = 0.9, given = 15, goodRating = 5) # Train recommender rec <- Recommender(getData(e, "train"), "UBCF") # Evaluate rating predictions pred_ratings <- predict(rec, getData(e, "known"), type = "ratings") accuracy_ratings <- calcPredictionAccuracy(pred_ratings, getData(e, "unknown")) accuracy_ratings ``` ```r # Per-user accuracy accuracy_by_user <- calcPredictionAccuracy(pred_ratings, getData(e, "unknown"), byUser = TRUE) head(accuracy_by_user) ``` ```r # Evaluate top-N recommendations pred_topN <- predict(rec, getData(e, "known"), n = 10, type = "topNList") accuracy_topN <- calcPredictionAccuracy(pred_topN, getData(e, "unknown"), given = rowCounts(getData(e, "known")), goodRating = 5) accuracy_topN ``` -------------------------------- ### Inspect Binary Rating Matrix Source: https://context7.com/mhahsler/recommenderlab/llms.txt Provides functions to access and inspect the data of a binaryRatingMatrix. ```r # Access data as(r_bin, "matrix") getList(r_bin) # Get items per user as list rowCounts(r_bin) # Items per user colCounts(r_bin) # Users per item ``` -------------------------------- ### Access Evaluation Data Source: https://context7.com/mhahsler/recommenderlab/llms.txt Retrieves specific subsets of data from a created evaluation scheme, such as the training set, known items for testing, or withheld items for evaluation. ```r # Access evaluation data getData(scheme_split, "train") # Training data getData(scheme_split, "known") # Known items for test users getData(scheme_split, "unknown") # Withheld items for evaluation getData(scheme_split, "given") # Number of given items per user ``` -------------------------------- ### Normalize Rating Data Source: https://context7.com/mhahsler/recommenderlab/llms.txt Applies normalization techniques (center, z-score) to rating data to remove user bias. Supports row-wise, column-wise, or both. ```r library("recommenderlab") data("Jester5k") r <- Jester5k[1:100] # Center normalization (subtract row mean) r_centered <- normalize(r, method = "center") r_centered # Row normalization info stored in the object # Z-score normalization (center and scale by standard deviation) r_zscore <- normalize(r, method = "z-score") # View normalized ratings getRatings(r_centered)[1:10] # Ratings now centered around 0 # Reverse normalization r_original <- denormalize(r_centered) identical(as(r, "matrix"), as(r_original, "matrix")) # TRUE # Column-wise normalization r_col_norm <- normalize(r, method = "center", row = FALSE) # Both row and column normalization r_both <- normalize(normalize(r, row = TRUE), row = FALSE) ``` -------------------------------- ### Inspect Real Rating Matrix Source: https://context7.com/mhahsler/recommenderlab/llms.txt Provides functions to access and inspect the underlying data and statistics of a realRatingMatrix. ```r # Access and inspect ratings getRatingMatrix(r) # Get underlying sparse matrix as(r, "matrix") # Convert back to regular matrix as(r, "list") # Get as list of user ratings as(r, "data.frame") # Get as user/item/rating tuples nratings(r) # Total number of ratings rowCounts(r) # Number of ratings per user colCounts(r) # Number of ratings per item rowMeans(r) # Average rating per user colMeans(r) # Average rating per item ``` -------------------------------- ### Generate Predictions with ALS Source: https://context7.com/mhahsler/recommenderlab/llms.txt Generates rating predictions for a test set using a trained recommender model. The output is an S4 object that can be converted to a matrix. ```r predictions <- predict(rec_svdf, test, type = "ratings") as(predictions, "matrix")[1:5, 1:5] ``` -------------------------------- ### Filter Users with Sufficient Ratings Source: https://context7.com/mhahsler/recommenderlab/llms.txt Filters the MovieLense dataset to include only users who have provided more than 100 ratings. Displays the dimensions of the filtered dataset. ```R MovieLense100 <- MovieLense[rowCounts(MovieLense) > 100] dim(MovieLense100) ``` -------------------------------- ### Binarize Real Ratings Source: https://context7.com/mhahsler/recommenderlab/llms.txt Converts a realRatingMatrix to a binaryRatingMatrix by applying a minimum rating threshold. ```r # Convert real ratings to binary using threshold data("Jester5k") jester_binary <- binarize(Jester5k, minRating = 5) # Rating >= 5 becomes 1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.