スパース性を計算する
ご存じのとおり、ALS はスパースなデータセットでうまく機能します。ratings 行列のどれくらいが実際には空なのか見てみましょう。
スパース性は、行列内で評価が入っているセルの数を、ユーザー数とアイテム数(映画)の積、つまりその行列が取りうる総セル数で割って求めます。言い換えると、行列に存在する評価の数をユーザー数と映画数の積で割り、それを 1 から引くと、スパース性、つまり ratings 行列の空の割合が得られます。
この演習はコースの一部です
PySpark で作る Recommendation Engines
演習の手順
ratings行列に含まれる評価の総数を数えて、スパース性指標のnumerator(分子)を計算しましょう。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.")