フォーマットの整備と重複のないユーザー
R データフレームを見てみましょう。これは各列に別の映画が入った、一般的な「ワイド」形式になっています。また、User や映画名が整数形式ではないことにも注目してください。ALS 用にこのデータを正しく前処理する手順に従いましょう。
この演習はコースの一部です
PySpark で作る Recommendation Engines
演習の手順
pyspark.sql.functionsからmonotonically_increasing_idをインポートし、.show()メソッドでRデータフレームを表示します。to_long()関数を使って、Rデータフレームを「ロング」形式に変換します。新しいデータフレーム名はratingsとします。- データフレーム中のユーザーを
.distinct()で一意に抽出したusersというデータフレームを作成し、.coalesce(1)メソッドでパーティションを 1 つにまとめます。 withColumn()の中でmonotonically_increasing_id()メソッドを使い、各ユーザーに固有の整数を付与する新しい列を users データフレームに作成します。列名はuserIdとします。最後のデータフレームには.persist()メソッドを呼び出し、新しい整数 ID が保持されるようにしてください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import monotonically_increasing_id and show R
from pyspark.sql.functions import ____
R.show()
# Use the to_long() function to convert the dataframe to the "long" format.
ratings = to_long(____)
ratings.show()
# Get unique users and repartition to 1 partition
users = ratings.select("____").____().____()
# Create a new column of unique integers called "userId" in the users dataframe.
users = users.withColumn("____", monotonically_increasing_id()).____()
users.show()