Spark MLib - 从RDD [Vector]功能和RDD [Vector]标签创建LabeledPoint

时间:2016-03-11 21:36:00

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

我正在使用两个代表文档和标签的文本文件构建训练集。

Documents.txt

hello world
hello mars

Labels.txt

0
1

我已阅读这些文件,并将我的文档数据转换为tf-idf加权term-document matrix,表示为RDD[Vector]。我也已阅读并为我的标签创建了RDD[Vector]

val docs: RDD[Seq[String]] = sc.textFile("Documents.txt").map(_.split(" ").toSeq)
val labs: RDD[Vector] = sc.textFile("Labels.txt")
  .map(s => Vectors.dense(s.split(',').map(_.toDouble)))

val hashingTF = new HashingTF()
val tf: RDD[Vector] = hashingTF.transform(docs)
tf.cache()

val idf = new IDF(minDocFreq = 3).fit(tf)
val tfidf: RDD[Vector] = idf.transform(tf)

我想使用tfidflabs来创建RDD[LabeledPoint],但我不确定如何应用具有两个不同RDDs的映射。这甚至可能/有效,还是我需要重新考虑我的方法?

1 个答案:

答案 0 :(得分:2)

处理此问题的一种方法是join基于索引:

import org.apache.spark.RangePartitioner

// Add indices
val idfIndexed = idf.zipWithIndex.map(_.swap)
val labelsIndexed = labels.zipWithIndex.map(_.swap)

// Create range partitioner on larger RDD
val partitioner = new RangePartitioner(idfIndexed.partitions.size, idfIndexed)

// Join with custom partitioner
labelsIndexed.join(idfIndexed, partitioner).values