从DataFrame到RDD [LabeledPoint]

时间:2015-06-18 21:06:33

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

我正在尝试使用Apache Spark MLlib实现文档分类器,我遇到了一些代表数据的问题。我的代码如下:

import org.apache.spark.sql.{Row, SQLContext}
import org.apache.spark.sql.types.{StringType, StructField, StructType}
import org.apache.spark.ml.feature.Tokenizer
import org.apache.spark.ml.feature.HashingTF
import org.apache.spark.ml.feature.IDF

val sql = new SQLContext(sc)

// Load raw data from a TSV file
val raw = sc.textFile("data.tsv").map(_.split("\t").toSeq)

// Convert the RDD to a dataframe
val schema = StructType(List(StructField("class", StringType), StructField("content", StringType)))
val dataframe = sql.createDataFrame(raw.map(row => Row(row(0), row(1))), schema)

// Tokenize
val tokenizer = new Tokenizer().setInputCol("content").setOutputCol("tokens")
val tokenized = tokenizer.transform(dataframe)

// TF-IDF
val htf = new HashingTF().setInputCol("tokens").setOutputCol("rawFeatures").setNumFeatures(500)
val tf = htf.transform(tokenized)
tf.cache
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(tf)
val tfidf = idfModel.transform(tf)

// Create labeled points
val labeled = tfidf.map(row => LabeledPoint(row.getDouble(0), row.get(4)))

我需要使用数据帧来生成令牌并创建TF-IDF功能。当我尝试将此数据帧转换为RDD [LabeledPoint]时出现问题。我映射数据帧行,但Row的get方法返回Any类型,而不是数据帧架构(Vector)上定义的类型。因此,我无法构建我需要训练ML模型的RDD。

计算TF-IDF后获得RDD [LabeledPoint]的最佳选择是什么?

2 个答案:

答案 0 :(得分:6)

投射对象对我有用。

尝试:

// Create labeled points
val labeled = tfidf.map(row => LabeledPoint(row.getDouble(0), row(4).asInstanceOf[Vector]))

答案 1 :(得分:1)

您需要使用// Create labeled points import org.apache.spark.mllib.linalg.{Vector, Vectors} val labeled = tfidf.map(row => LabeledPoint(row.getDouble(0), row.getAs[Vector](4)))

$.cookie('name', 'value', { expires: 7 });