計算稀疏度
你已經知道,ALS 對稀疏的資料集效果不錯。現在來看看 ratings 矩陣中實際上有多少是空的。
請記住,稀疏度的計算方式是:矩陣中包含評分的儲存格數量,除以在給定使用者數與項目(電影)數下,該矩陣理論上可容納的總值數量。換句話說,用矩陣中實際存在的評分數,除以該矩陣中的使用者數與電影數的乘積,然後以 1 減去此比值,就能得到稀疏度,也就是 ratings 矩陣為空的百分比。
本練習屬於課程
使用 PySpark 打造推薦引擎
練習說明
- 計算稀疏度指標的
numerator:統計ratings矩陣中評分的總數。 - 計算
ratings矩陣中distinct()的userIds與distinct()的movieIds數量。 - 計算稀疏度指標的
denominator:以使用者數乘上電影數。 - 計算並印出稀疏度:用
numerator除以denominator,以 1 減去該比值後再乘以 100。加入1.0是為了確保回傳型別為小數而非整數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Count the total number of ratings in the dataset
numerator = ____.select("____").count()
# Count the number of distinct userIds and distinct movieIds
num_users = ____.select("____").____().count()
num_movies = ____.select("____").____().count()
# Set the denominator equal to the number of users multiplied by the number of movies
denominator = ____ * ____
# Divide the numerator by the denominator
sparsity = (1.0 - (____ *1.0)/____)*100
print("The ratings dataframe is ", "%.2f" % sparsity + "% empty.")