【发布时间】:2016-05-03 10:22:52
【问题描述】:
我在 HDFS 上的制表符分隔文件中有一些数据,如下所示:
label | user_id | feature
------------------------------
pos | 111 | www.abc.com
pos | 111 | www.xyz.com
pos | 111 | Firefox
pos | 222 | www.example.com
pos | 222 | www.xyz.com
pos | 222 | IE
neg | 333 | www.jkl.com
neg | 333 | www.xyz.com
neg | 333 | Chrome
我需要对其进行转换,为每个 user_id 创建一个特征向量来训练一个org.apache.spark.ml.classification.NaiveBayes 模型。
我目前的方法基本上如下:
- 将原始数据加载到 DataFrame 中
- 使用 StringIndexer 索引特征
- 进入 RDD 并按 user_id 分组,并将特征索引映射到稀疏向量中。
关键是……数据已经按 user_id 进行了预排序。利用它的最佳方法是什么?想到可能发生了多少不必要的工作,我感到很痛苦。
如果一些代码有助于理解我目前的方法,这里是地图的精髓:
val featurization = (vals: (String,Iterable[Row])) => {
// create a Seq of all the feature indices
// Note: the indexing was done in a previous step not shown
val seq = vals._2.map(x => (x.getDouble(1).toInt,1.0D)).toSeq
// create the sparse vector
val featureVector = Vectors.sparse(maxIndex, seq)
// convert the string label into a Double
val label = if (vals._2.head.getString(2) == "pos") 1.0 else 0.0
(label, vals._1, featureVector)
}
d.rdd
.groupBy(_.getString(1))
.map(featurization)
.toDF("label","user_id","features")
【问题讨论】:
标签: apache-spark apache-spark-mllib naivebayes