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.
1
import org.apache.spark.ml.evaluation.RegressionEvaluator
2
import org.apache.spark.ml.recommendation.ALS
3
import spark.implicits._
4
val ds=spark.read.textFile("file:///opt/spark/data/mllib/als/sample_movielens_ratings.txt")
5
val df=ds.toDF
6
df.show(4)
7
/*
8
+-------------------+
9
| value|
10
+-------------------+
11
|0::2::3::1424380312|
12
|0::3::1::1424380312|
13
|0::5::2::1424380312|
14
|0::9::4::1424380312|
15
+-------------------+
16
only showing top 4 rows
17
*/
18
val df1=df.withColumn("_tmp", split(quot;value", "::")).select(
19
quot;_tmp".getItem(0).as("col1"),
20
quot;_tmp".getItem(1).as("col2"),
21
quot;_tmp".getItem(2).as("col3"),
22
quot;_tmp".getItem(3).as("col4")
23
).drop("_tmp")
24
โ€‹
25
df1.show(5)
26
/*
27
+----+----+----+----------+
28
|col1|col2|col3| col4|
29
+----+----+----+----------+
30
| 0| 2| 3|1424380312|
31
| 0| 3| 1|1424380312|
32
| 0| 5| 2|1424380312|
33
| 0| 9| 4|1424380312|
34
| 0| 11| 1|1424380312|
35
+----+----+----+----------+
36
only showing top 5 rows
37
*/
38
โ€‹
39
val df_with_datatype=df1.selectExpr("cast(col1 as Int) userId",
40
"cast(col2 as Int) movieId",
41
"cast(col3 as Float) rating",
42
"cast(col4 as Long) timestamp")
43
โ€‹
44
val df_filter_null=df_with_datatype.filter("userId is NOT null")
45
.filter("movieId is NOT null")
46
.filter("rating is NOT null")
47
.filter("timestamp is NOT null")
48
49
val Array(training, test) = df_filter_null.randomSplit(Array(0.8, 0.2))
50
โ€‹
51
// Build the recommendation model using ALS on the training data
52
val als = new ALS()
53
.setMaxIter(5)
54
.setRegParam(0.01)
55
.setUserCol("userId")
56
.setItemCol("movieId")
57
.setRatingCol("rating")
58
โ€‹
59
val model = als.fit(training)
60
โ€‹
61
// Evaluate the model by computing the RMSE on the test data
62
// Note we set cold start strategy to 'drop' to ensure we don't get NaN evaluation metrics
63
model.setColdStartStrategy("drop")
64
val predictions = model.transform(test)
65
โ€‹
66
val evaluator = new RegressionEvaluator()
67
.setMetricName("rmse")
68
.setLabelCol("rating")
69
.setPredictionCol("prediction")
70
val rmse = evaluator.evaluate(predictions)
71
println(s"Root-mean-square error = $rmse")
72
โ€‹
73
// Generate top 10 movie recommendations for each user
74
val userRecs = model.recommendForAllUsers(10)
75
// Generate top 10 user recommendations for each movie
76
val movieRecs = model.recommendForAllItems(10)
77
โ€‹
78
// Generate top 10 movie recommendations for a specified set of users
79
val users = ratings.select(als.getUserCol).distinct().limit(3)
80
val userSubsetRecs = model.recommendForUserSubset(users, 10)
81
// Generate top 10 user recommendations for a specified set of movies
82
val movies = ratings.select(als.getItemCol).distinct().limit(3)
83
val movieSubSetRecs = model.recommendForItemSubset(movies, 10)
84
โ€‹
85
/*
86
Root-mean-square error = 1.9694419904333391
87
โ€‹
88
*/
89
โ€‹
90
movieRecs.toDF.show(5,false)
91
โ€‹
92
/*
93
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
94
|movieId|recommendations |
95
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
96
|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]] |
97
|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]] |
98
|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]] |
99
|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]]|
100
|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]] |
101
+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
102
only showing top 5 rows
103
โ€‹
104
โ€‹
105
*/
106
โ€‹
107
โ€‹
108
โ€‹
109
โ€‹
110
โ€‹
Copied!
Last modified 1yr ago
Copy link