使用 PySpark 构建推荐引擎
Jamen Long
Data Scientist at Nike
F. Maxwell Harper 和 Joseph A. Konstan,2015
The MovieLens Datasets: History and Context.
ACM Transitions on Interactive Intelligent Systems (TiiS) 5, 4,文章 19(2015 年 12 月),19 页。
DOI=http://dx.doi.org/10.1145/2827872
F. Maxwell Harper 和 Joseph A. Konstan,2015
The MovieLens Datasets: History and Context.
ACM Transitions on Interactive Intelligent Systems (TiiS) 5, 4,文章 19(2015 年 12 月),19 页。
DOI=http://dx.doi.org/10.1145/2827872
评分: 20,000,000+
用户: 138,493
电影: 27,278
df.show()
df.columns()

# 矩阵中的评分数量
numerator = ratings.count()
# 唯一用户与电影数
users = ratings.select("userId").distinct().count()
movies = ratings.select("movieId").distinct().count()
# 矩阵中的评分数量 numerator = ratings.count() # 唯一用户与电影数 users = ratings.select("userId").distinct().count() movies = ratings.select("movieId").distinct().count()# 若无空单元,矩阵可包含的评分数 denominator = users * movies
# 矩阵中的评分数量
numerator = ratings.count()
# 唯一用户与电影数
users = ratings.select("userId").distinct().count()
movies = ratings.select("movieId").distinct().count()
# 若无空单元,矩阵可包含的评分数
denominator = users * movies
# 计算稀疏性
sparsity = 1 - (numerator*1.0 / denominator)
print ("Sparsity: "), sparsity
Sparsity: .998
ratings.select("userId").distinct().count()
671
# 按 userId 分组
ratings.groupBy("userId")
# 每位用户的播放次数
ratings.groupBy("userId").count().show()
+------+-----+
|userId|count|
+------+-----+
| 148| 76|
| 243| 12|
| 31| 232|
| 137| 16|
| 251| 19|
| 85| 752|
| 65| 737|
| 255| 9|
| 53| 190|
| 133| 302|
| 296| 74|
| 78| 301|
| 108| 136|
| 155| 3|
| 193| 174|
| 101| 1|
+------+-----+
from pyspark.sql.functions import min, max, avg
# 每位用户的最小播放次数
msd.groupBy("userId").count()
.select(min("count")).show()
+----------+
|min(count)|
+----------+
| 1|
+----------+
# 每位用户的最大播放次数
ratings.groupBy("userId").count()
.select(max("count")).show()
+----------+
|max(count)|
+----------+
| 1162|
+----------+
# 每位用户的平均播放次数
ratings.groupBy("userId").count()
.select(avg("count")).show()
+----------+
|avg(count)|
+----------+
| 233.34579|
+----------+
# 移除少于 20 条评分的用户
ratings.groupBy("userId").count().filter(col("count") >= 20).show()
+------+-----+
|userId|count|
+------+-----+
| 148| 76|
| 31| 232|
| 85| 752|
| 65| 737|
| 53| 190|
| 133| 302|
| 296| 74|
| 78| 301|
| 108| 136|
| 193| 174|
+------+-----+
使用 PySpark 构建推荐引擎