Convert input to ALS in pyspark

The input for the recommendation is as follows:

[(u'97990079', u'18_34', 2),
 (u'585853655', u'11_8', 1),
 (u'1398696913', u'6_20', 1),
 (u'612168869', u'7_16', 1),
 (u'2272846159', u'11_17', 2)]

which follows the format (user_id, item_id, score).

If I understand correctly, the ALS in the spark to convert user_id, item_idinto an integer before training? If so, the only solutions I can think of right now is to use dictionaries and match all user_idand item_idwith an integer, like

dictionary for item_id : {'18_34': 1, '18_35':2, ...}
dictionary for user_id : {'97990079':1, '585853655':2, ...}

But I was wondering if there is another elegant way to do this? Thanks!

+4
source share
1 answer

- ML. DataFrame:

ratings_df = sqlContext.createDataFrame([
    (u'97990079', u'18_34', 2), (u'585853655', u'11_8', 1),
    (u'1398696913', u'6_20', 1), (u'612168869', u'7_16', 1),
    (u'2272846159', u'11_17', 2)],
    ("user_id", "item_id_str", "rating"))

StringIndexer

from pyspark.ml.feature import StringIndexer

indexer = StringIndexer(inputCol="item_id_str", outputCol="item_id")

, DataFrame :

from pyspark.sql.functions import col

transformed = (indexer
    .fit(ratings_df)
    .transform(ratings_df)
    .withColumn("user_id", col("user_id").cast("integer"))
    .select("user_id", "item_id", "rating"))

RDD[Rating]:

from pyspark.mllib.recommendation import Rating

ratings_rdd = transformed.map(lambda r: Rating(r.user_id, r.item_id, r.rating))

Spark ml.recommendation.ALS:

from pyspark.ml.recommendation import ALS

als = (ALS(userCol="user_id", itemCol="item_id", ratingCol="rating")
  .fit(transformed))
+4

Source: https://habr.com/ru/post/1615977/


All Articles