从Apache Spark / Scala中的特征向量创建一个数组

时间:2017-09-02 17:21:57

标签: arrays scala apache-spark spark-dataframe

尝试在Apache Spark和scala中创建功能Vector中的所有功能的数组。我需要这样做,以便为我的算法中的各种组合创建一个Breeze Matrix功能。目前,功能包含在功能向量中,我想分别提取每个功能。我一直在看以下问题: Applying IndexToString to features vector in Spark

这是我当前的代码:(数据是Spark DataFrame,所有功能都是双打)

val featureCols = Array("feature1", "feature2", "feature3") 
val featureAssembler = new VectorAssembler().setInputCols(featureCols).setOutputCol("features")
val dataWithFeatures = featureAssembler.transform(data)

//now we slice the features back again
val featureSlicer = featureCols.map {
  col => new VectorSlicer().setInputCol("features").setOutputCol(s"${col}_sliced").setNames(Array(s"${col}"))}
val output = featureSlicer.map(f => f.transform(dataWithFeatures).select(f.getOutputCol).as[Double].collect)
val array = output.flatten.toArray

然而,这失败并出现以下错误:'无法解决CAST(“feature1”由于数据类型不匹配导致AS DOUBLE - 无法将VectorUDT强制转换为DoubleType'

这看起来很奇怪,因为我可以在没有错误的情况下执行以下操作:

val array: Array[Double] = dataWithFeatures.select("feature1").as[Double].collect()

任何想法如何解决这个问题,以及是否有更好的方法,因为创建一系列DataFrame并分别对每个DataFrame执行操作似乎效率低下。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果features列是从所有其他功能列汇编的vector列,则可以选择features列,将其转换为rdd,然后flatMap它:

示例数据

dataWithFeatures.show
+--------+--------+--------+-------------+
|feature1|feature2|feature3|     features|
+--------+--------+--------+-------------+
|       1|       2|       3|[1.0,2.0,3.0]|
|       4|       5|       6|[4.0,5.0,6.0]|
+--------+--------+--------+-------------+
import org.apache.spark.ml.linalg.Vector

dataWithFeatures.select("features").rdd.flatMap(r => r.getAs[Vector](0).toArray).collect
// res19: Array[Double] = Array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)