计算按列分组的TF-IDF

时间:2018-05-30 16:39:22

标签: scala apache-spark apache-spark-sql apache-spark-mllib

如何计算按列分组的tf-idf而不是整个数据帧?

假设在数据框中如下

private val sample = Seq(
    (1, "A B C D E"),
    (1, "B C D"),
    (1, "B C D E"),
    (2, "B C D F"),
    (2, "A B C"),
    (2, "B C E F G")
  ).toDF("id","sentences")

在上面的示例中,通过考虑前三个元素,应该为id = 1的句子计算IDF。同样地,通过考虑最后三个元素,应该为Id = 2的句子计算IDF。是否有可能在Spark ml的tf-idf实现中。

2 个答案:

答案 0 :(得分:1)

只是一个蹩脚的尝试:您可以按ID过滤您的序列,并将每个过滤器转换为数据帧并将其保存在列表中,然后使用循环将tf-idf应用于列表中的每个数据帧。

var filters=List[org.apache.spark.sql.DataFrame]()
val mySeq=Seq((1, "A B C D E"),(1, "B C D"),(1, "B C D E"),(2, "B C D F"),(2, "A B C"),(2, "B C E F G")) 
for(i<-List(1,2)){filters=filters:+s.filter{case x=>x._1==i}.toDF("id","sentences")}   

所以例如你有

scala> filters(0).show()
+---+---------+
| id|sentences|
+---+---------+
|  1|A B C D E|
|  1|    B C D|
|  1|  B C D E|
+---+---------+

scala> filters(1).show()
+---+---------+
| id|sentences|
+---+---------+
|  2|  B C D F|
|  2|    A B C|
|  2|B C E F G|
+---+---------+

您可以使用循环或map对每个数据帧进行TF-IDF计算。

您也可以使用某种groupBy,但此操作需要随机播放,这可能会降低群集中的效果

答案 1 :(得分:0)

您可以按id对数据帧进行分组,并在TF-IDF计算之前展平相应的标记化单词。以下是使用Spark TF-IDF doc:

中的示例代码的代码段
val sample = Seq(
  (1, "A B C D E"),
  (1, "B C D"),
  (1, "B C D E"),
  (2, "B C D F"),
  (2, "A B C"),
  (2, "B C E F G")
).toDF("id","sentences")

import org.apache.spark.sql.functions._
import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}

val tokenizer = new Tokenizer().setInputCol("sentences").setOutputCol("words")
val wordsDF = tokenizer.transform(sample)

def flattenWords = udf( (s: Seq[Seq[String]]) => s.flatMap(identity) )

val groupedDF = wordsDF.groupBy("id").
  agg(flattenWords(collect_list("words")).as("grouped_words"))

val hashingTF = new HashingTF().
  setInputCol("grouped_words").setOutputCol("rawFeatures").setNumFeatures(20)
val featurizedData = hashingTF.transform(groupedDF)
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)

rescaledData.show
// +---+--------------------+--------------------+--------------------+
// | id|       grouped_words|         rawFeatures|            features|
// +---+--------------------+--------------------+--------------------+
// |  1|[a, b, c, d, e, b...|(20,[1,2,10,14,18...|(20,[1,2,10,14,18...|
// |  2|[b, c, d, f, a, b...|(20,[1,2,8,10,14,...|(20,[1,2,8,10,14,...|
// +---+--------------------+--------------------+--------------------+