2017-07-19 16 views
-2

我读一个csv如如下面阶一个数据帧:如何在Scala中创建特征向量?

+-----------+------------+ 
|x   |y   | 
+-----------+------------+ 
|   0|   0| 
|   0|   33| 
|   0|   58| 
|   0|   96| 
|   0|   1| 
|   1|   21| 
|   0|   10| 
|   0|   65| 
|   1|   7| 
|   1|   28| 
+-----------+------------+ 

然后,我创建如下面的标签和特征向量:

val assembler = new VectorAssembler() 
    .setInputCols(Array("y")) 
    .setOutputCol("features") 


    val output = assembler.transform(daf).select($"x".as("label"), $"features") 

    println(output.show) 

的输出是如:

+-----------+------------+ 
|label | features | 
+-----------+------------+ 
| 0.0| 0.0| 
| 0.0| 33.0| 
| 0.0| 58.0| 
| 0.0| 96.0| 
| 0.0| 1.0| 
| 0.0| 21.0| 
| 0.0| 10.0| 
| 1.0| 65.0| 
| 1.0| 7.0| 
| 1.0| 28.0| 
+-----------+------------+ 

但是,我想要输出像下面的格式

+-----+------------------+ 
|label| features | 
+-----+------------------+ 
| 0.0|(1,[1],[0]) | 
| 0.0|(1,[1],[33]) | 
| 0.0|(1,[1],[58]) | 
| 0.0|(1,[1],[96]) | 
| 0.0|(1,[1],[1]) | 
| 1.0|(1,[1],[21]) | 
| 0.0|(1,[1],[10]) | 
| 0.0|(1,[1],[65]) | 
| 1.0|(1,[1],[7]) | 
| 1.0|(1,[1],[28]) | 
+-----------+------------+ 

我试图

val assembler = new VectorAssembler() 
     .setInputCols(Array("y").map{x => "(1,[1],"+x+")"}) 
     .setOutputCol("features") 

但没有奏效。 任何帮助表示赞赏。

回答

1

这不是你如何使用VectorAssembler。

您需要提供输入列的名称。即

new VectorAssembler().setInputCols(Array("features")) 

考虑到您分享的数据,您最终还是会面临另一个问题。如果只有一点,它就不是什么矢量。 (您的features列)

它应与2列或更多列一起使用。即:

new VectorAssembler().setInputCols(Array("f1","f2","f3")) 
+0

让我们[继续聊天讨论](http://chat.stackoverflow.com/rooms/149555/discussion-between-ricky-and-eliasah)。 – Ricky