2017-07-19 18 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