【问题标题】:Recommendation - Creating a new dataframe with conditions建议 - 创建具有条件的新数据框
【发布时间】:2020-04-13 14:41:48
【问题描述】:

我研究 Spark 已经有一段时间了,但今天我卡住了,我正在使用 Audioscrobbler 数据集在推荐模型中工作。

我有基于 ALS 的模型和以下定义用于提出建议:

def makeRecommendations(model: ALSModel, userID: Int,howMany: Int): DataFrame = {
  val toRecommend = model.itemFactors.select($"id".as("artist")).withColumn("user", lit(userID))
     model.transform(toRecommend).
        select("artist", "prediction", "user").
        orderBy($"prediction".desc).
        limit(howMany)
}

它正在生成预期的输出,但现在我想使用 Predictions DF 和 User Data DF 创建一个新的 DataFrames 列表。

DataFrame Example

新的 DF 列表由“Predictions DF”和“Listened”中的 Predicted 值组成,如果用户没有听过艺术家,则为 0,如果用户听过,则为 1,如下所示:

Expected DF

我尝试了以下解决方案:

val recommendationsSeq = someUsers.map { userID =>
     //Gets the artists from user in testData
   val artistsOfUser = testData.where($"user".===(userID)).select("artist").rdd.map(r => r(0)).collect.toList
     // Recommendations for each user
   val recoms        = makeRecommendations(model, userID, numRecom)
     //Insert a column listened with 1 if the artist in the test set for the user and 0 otherwise
   val recomOutput   = recoms.withColumn("listened", when($"artist".isin(artistsOfUser: _*), 1.0).otherwise(0.0)).drop("artist")
     (recomOutput)
}.toSeq

但是当推荐超过 30 个用户时,它非常耗时。我相信有更好的方法来做到这一点,

谁能给点意见?

谢谢,

【问题讨论】:

    标签: dataframe apache-spark recommendation-engine


    【解决方案1】:

    您可以尝试加入数据框,然后进行 goupby 和计数:

    scala> val df1 = Seq((1205,0.9873411,1000019)).toDF("artist","prediction","user")
    scala> df1.show()
    +------+----------+-------+
    |artist|prediction|   user|
    +------+----------+-------+
    |  1205| 0.9873411|1000019|
    +------+----------+-------+
    
    scala> val df2 = Seq((1000019,1205,40)).toDF("user","artist","playcount")
    scala> df2.show()
    +-------+------+---------+
    |   user|artist|playcount|
    +-------+------+---------+
    |1000019|  1205|       40|
    +-------+------+---------+
    
    scala> df1.join(df2,Seq("artist","user")).groupBy('prediction).count().show()
    +----------+-----+
    |prediction|count|
    +----------+-----+
    | 0.9873411|    1|
    +----------+-----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2021-11-04
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      相关资源
      最近更新 更多