我有一个scala.collection.immutable.Vector
类型的向量,并希望将其转换为org.apache.spark.ml.linalg.Vector
类型的向量。
例如,我想要以下内容;
import org.apache.spark.ml.linalg.Vectors
val scalaVec = Vector(1,2,3)
val sparkVec = Vectors.dense(scalaVec)
请注意,我只需键入val sparkVec = Vectors.dense(1,2,3)
,但我想转换现有的scala集合向量。我想这样做是为了将这些DenseVectors嵌入到DataFrame中以提供给spark.ml管道。
答案 0 :(得分:3)
Vectors.dense可以采用一系列双精度数。可能导致您麻烦的是Vectors.dense在您的示例中不会接受您在scalaVec中使用的Ints。所以以下失败:
val test = Seq(1,2,3,4,5).to[scala.Vector].toArray
Vectors.dense(test)
import org.apache.spark.ml.linalg.Vectors
test: Array[Int] = Array(1, 2, 3, 4, 5)
<console>:67: error: overloaded method value dense with alternatives:
(values: Array[Double])org.apache.spark.ml.linalg.Vector <and>
(firstValue: Double,otherValues: Double*)org.apache.spark.ml.linalg.Vector cannot be applied to (Array[Int])
Vectors.dense(test)
虽然这有效:
val testDouble = Seq(1,2,3,4,5).map(x=>x.toDouble).to[scala.Vector].toArray
Vectors.dense(testDouble)
testDouble: Array[Double] = Array(1.0, 2.0, 3.0, 4.0, 5.0)
res11: org.apache.spark.ml.linalg.Vector = [1.0,2.0,3.0,4.0,5.0]