# Collaborative filtering

Collaborative filtering is commonly used for recommender systems. These techniques aim to fill in the missing entries of a user-item association matrix. spark.ml currently supports model-based collaborative filtering, in which users and products are described by a small set of latent factors that can be used to predict missing entries. spark.ml uses the alternating least squares (ALS) algorithm to learn these latent factors. The implementation in spark.ml has the following parameters:

numBlocks is the number of blocks the users and items will be partitioned into in order to parallelize computation (defaults to 10). rank is the number of latent factors in the model (defaults to 10). maxIter is the maximum number of iterations to run (defaults to 10). regParam specifies the regularization parameter in ALS (defaults to 1.0). implicitPrefs specifies whether to use the explicit feedback ALS variant or one adapted for implicit feedback data (defaults to false which means using explicit feedback). alpha is a parameter applicable to the implicit feedback variant of ALS that governs the baseline confidence in preference observations (defaults to 1.0). nonnegative specifies whether or not to use nonnegative constraints for least squares (defaults to false). Note: The DataFrame-based API for ALS currently only supports integers for user and item ids. Other numeric types are supported for the user and item id columns, but the ids must be within the integer value range.

Explicit vs. implicit feedback The standard approach to matrix factorization-based collaborative filtering treats the entries in the user-item matrix as explicit preferences given by the user to the item, for example, users giving ratings to movies.

It is common in many real-world use cases to only have access to implicit feedback (e.g. views, clicks, purchases, likes, shares etc.). The approach used in spark.ml to deal with such data is taken from Collaborative Filtering for Implicit Feedback Datasets. Essentially, instead of trying to model the matrix of ratings directly, this approach treats the data as numbers representing the strength in observations of user actions (such as the number of clicks, or the cumulative duration someone spent viewing a movie). Those numbers are then related to the level of confidence in observed user preferences, rather than explicit ratings given to items. The model then tries to find latent factors that can be used to predict the expected preference of a user for an item.

Scaling of the regularization parameter We scale the regularization parameter regParam in solving each least squares problem by the number of ratings the user generated in updating user factors, or the number of ratings the product received in updating product factors. This approach is named “ALS-WR” and discussed in the paper “Large-Scale Parallel Collaborative Filtering for the Netflix Prize”. It makes regParam less dependent on the scale of the dataset, so we can apply the best parameter learned from a sampled subset to the full dataset and expect similar performance.

Cold-start strategy When making predictions using an ALSModel, it is common to encounter users and/or items in the test dataset that were not present during training the model. This typically occurs in two scenarios:

In production, for new users or items that have no rating history and on which the model has not been trained (this is the “cold start problem”). During cross-validation, the data is split between training and evaluation sets. When using simple random splits as in Spark’s CrossValidator or TrainValidationSplit, it is actually very common to encounter users and/or items in the evaluation set that are not in the training set By default, Spark assigns NaN predictions during ALSModel.transform when a user and/or item factor is not present in the model. This can be useful in a production system, since it indicates a new user or item, and so the system can make a decision on some fallback to use as the prediction.

However, this is undesirable during cross-validation, since any NaN predicted values will result in NaN results for the evaluation metric (for example when using RegressionEvaluator). This makes model selection impossible.

Spark allows users to set the coldStartStrategy parameter to “drop” in order to drop any rows in the DataFrame of predictions that contain NaN values. The evaluation metric will then be computed over the non-NaN data and will be valid. Usage of this parameter is illustrated in the example below.

Note: currently the supported cold start strategies are “nan” (the default behavior mentioned above) and “drop”. Further strategies may be supported in future.

```
import org.apache.spark.ml.evaluation.RegressionEvaluator
import org.apache.spark.ml.recommendation.ALS
import spark.implicits._
val ds=spark.read.textFile("file:///opt/spark/data/mllib/als/sample_movielens_ratings.txt")
val df=ds.toDF
df.show(4)
/*
+-------------------+
|              value|
+-------------------+
|0::2::3::1424380312|
|0::3::1::1424380312|
|0::5::2::1424380312|
|0::9::4::1424380312|
+-------------------+
only showing top 4 rows
*/
val df1=df.withColumn("_tmp", split($"value", "::")).select(
  $"_tmp".getItem(0).as("col1"),
  $"_tmp".getItem(1).as("col2"),
  $"_tmp".getItem(2).as("col3"),
  $"_tmp".getItem(3).as("col4")
).drop("_tmp")

df1.show(5)
/*
+----+----+----+----------+
|col1|col2|col3|      col4|
+----+----+----+----------+
|   0|   2|   3|1424380312|
|   0|   3|   1|1424380312|
|   0|   5|   2|1424380312|
|   0|   9|   4|1424380312|
|   0|  11|   1|1424380312|
+----+----+----+----------+
only showing top 5 rows
*/

val df_with_datatype=df1.selectExpr("cast(col1 as Int) userId",
                  "cast(col2 as Int) movieId",
                  "cast(col3 as Float) rating",
                  "cast(col4 as Long) timestamp")

val df_filter_null=df_with_datatype.filter("userId is NOT null")
                   .filter("movieId is NOT null")
                   .filter("rating is NOT null")
                   .filter("timestamp is NOT null")
                   
val Array(training, test) = df_filter_null.randomSplit(Array(0.8, 0.2))

// Build the recommendation model using ALS on the training data
val als = new ALS()
  .setMaxIter(5)
  .setRegParam(0.01)
  .setUserCol("userId")
  .setItemCol("movieId")
  .setRatingCol("rating")

val model = als.fit(training)

// Evaluate the model by computing the RMSE on the test data
// Note we set cold start strategy to 'drop' to ensure we don't get NaN evaluation metrics
model.setColdStartStrategy("drop")
val predictions = model.transform(test)

val evaluator = new RegressionEvaluator()
  .setMetricName("rmse")
  .setLabelCol("rating")
  .setPredictionCol("prediction")
val rmse = evaluator.evaluate(predictions)
println(s"Root-mean-square error = $rmse")

// Generate top 10 movie recommendations for each user
val userRecs = model.recommendForAllUsers(10)
// Generate top 10 user recommendations for each movie
val movieRecs = model.recommendForAllItems(10)

// Generate top 10 movie recommendations for a specified set of users
val users = ratings.select(als.getUserCol).distinct().limit(3)
val userSubsetRecs = model.recommendForUserSubset(users, 10)
// Generate top 10 user recommendations for a specified set of movies
val movies = ratings.select(als.getItemCol).distinct().limit(3)
val movieSubSetRecs = model.recommendForItemSubset(movies, 10)

/*
Root-mean-square error = 1.9694419904333391

*/

movieRecs.toDF.show(5,false)

/*
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|movieId|recommendations                                                                                                                                                       |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|31     |[[12, 3.9116766], [6, 3.2745547], [14, 3.123588], [8, 3.0202165], [7, 2.7595513], [9, 2.2341797], [17, 1.9346341], [21, 1.8659948], [15, 1.8418702], [25, 1.713342]]  |
|85     |[[18, 5.2397203], [16, 4.9212985], [8, 4.5497913], [25, 4.4582], [7, 4.301504], [0, 4.2436285], [21, 3.2146235], [6, 3.1708229], [28, 3.1625175], [14, 2.8124433]]    |
|65     |[[23, 4.797905], [18, 2.9681492], [0, 2.8323104], [14, 2.2709212], [5, 2.2471752], [11, 2.1821382], [25, 2.0922368], [15, 2.0393076], [1, 1.911113], [6, 1.8635347]]  |
|53     |[[22, 6.043746], [8, 4.958887], [26, 4.9108295], [21, 4.8912897], [20, 3.9612412], [24, 3.9306047], [14, 2.8171947], [28, 2.5926101], [16, 2.2719743], [3, 2.2049422]]|
|78     |[[5, 1.380609], [25, 1.25078], [23, 1.1319652], [29, 1.1171162], [9, 1.0972868], [17, 1.0794944], [2, 1.0715297], [22, 1.055237], [4, 1.0450754], [26, 1.0372707]]    |
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
only showing top 5 rows


*/





```
