PySparkで学ぶBig Data入門
Upendra Devisetty
Science Analyst, CyVerse
協調フィルタリングは、共通の関心を持つユーザーを見つける手法です
推薦システムでよく使われます
主な手法:
ユーザー間協調フィルタリング: 対象ユーザーに似たユーザーを探す
アイテム間協調フィルタリング: 対象ユーザーが関わるアイテムに似たアイテムを推薦する
Rating クラスは (user, product, rating) タプルのラッパーです
RDD を解析し、(user, product, rating) のタプルを作るのに便利です
from pyspark.mllib.recommendation import Rating
r = Rating(user = 1, product = 2, rating = 5.0)
(r[0], r[1], r[2])
(1, 2, 5.0)
予測モデルの評価には、データを訓練用とテスト用に分割することが重要
一般に、訓練用の比率を大きくします
PySpark の randomSplit() は重みに基づきランダム分割し、複数の RDD を返します
data = sc.parallelize([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
training, test=data.randomSplit([0.6, 0.4])
training.collect()
test.collect()
[1, 2, 5, 6, 9, 10]
[3, 4, 7, 8]
spark.mllib の ALS (Alternating Least Squares) は協調フィルタリングを提供
ALS.train(ratings, rank, iterations)
r1 = Rating(1, 1, 1.0)
r2 = Rating(1, 2, 2.0)
r3 = Rating(2, 1, 2.0)
ratings = sc.parallelize([r1, r2, r3])
ratings.collect()
[Rating(user=1, product=1, rating=1.0),
Rating(user=1, product=2, rating=2.0),
Rating(user=2, product=1, rating=2.0)]
model = ALS.train(ratings, rank=10, iterations=10)
predictAll() は、ユーザー×商品の組に対する予測評価を返します
評価なしの RDD を入力し、予測値を生成します
unrated_RDD = sc.parallelize([(1, 2), (1, 1)])
predictions = model.predictAll(unrated_RDD)
predictions.collect()
[Rating(user=1, product=1, rating=1.0000278574351853),
Rating(user=1, product=2, rating=1.9890355703778122)]
rates = ratings.map(lambda x: ((x[0], x[1]), x[2]))
rates.collect()
[((1, 1), 1.0), ((1, 2), 2.0), ((2, 1), 2.0)]
preds = predictions.map(lambda x: ((x[0], x[1]), x[2])) preds.collect()[((1, 1), 1.000027857), ((1, 2), 1.9890355703)]
rates_preds = rates.join(preds)
rates_preds.collect()
[((1, 2), (2.0, 1.9890355703)), ((1, 1), (1.0, 1.000027857))]
MSE は「(実測評価 − 予測評価)²」の平均です
MSE = rates_preds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
PySparkで学ぶBig Data入門