使用 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, Article 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, Article 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 打造推薦引擎