![](/img/trans.png)
[英]How to map features from the output of a VectorAssembler back to the column names in Spark ML?
[英]Create labledpoints from Spark Dataframe & how to pass list of names to VectorAssembler
我還有一些問題來自https://stackoverflow.com/a/32557330/5235052我正在嘗試從數據框架構建labledPoints,其中我有列中的功能和標簽。 這些功能都是布爾值1/0。
以下是數據框中的示例行:
| 0| 0| 0| 0| 0| 0| 1| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 1| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1|
#Using the code from above answer,
#create a list of feature names from the column names of the dataframe
df_columns = []
for c in df.columns:
if c == 'is_item_return': continue
df_columns.append(c)
#using VectorAssembler for transformation, am using only first 4 columns names
assembler = VectorAssembler()
assembler.setInputCols(df_columns[0:5])
assembler.setOutputCol('features')
transformed = assembler.transform(df)
#mapping also from above link
from pyspark.mllib.regression import LabeledPoint
from pyspark.sql.functions import col
new_df = transformed.select(col('is_item_return'), col("features")).map(lambda row: LabeledPoint(row.is_item_return, row.features))
當我檢查RDD的內容時,我得到了正確的標簽,但是特征向量是錯誤的。
(0.0,(5,[],[]))
有人可以幫我理解,如何將現有數據幀的列名稱作為要素名稱傳遞給VectorAssembler?
這里沒有錯。 你得到的是SparseVector
的字符串表示,它完全反映了你的輸入:
assembler.setInputCols(df_columns[0:5])
),輸出向量長度為5 indices
,因此values
數組為空 為了說明這一點,我們可以使用Scala,它為toSparse
/ toDense
方法提供了有用的toSparse
:
import org.apache.spark.mllib.linalg.Vectors
val v = Vectors.dense(Array(0.0, 0.0, 0.0, 0.0, 0.0))
v.toSparse.toString
// String = (5,[],[])
v.toSparse.toDense.toString
// String = [0.0,0.0,0.0,0.0,0.0]
使用PySpark:
from pyspark.ml.feature import VectorAssembler
df = sc.parallelize([
tuple([0.0] * 5),
tuple([1.0] * 5),
(1.0, 0.0, 1.0, 0.0, 1.0),
(0.0, 1.0, 0.0, 1.0, 0.0)
]).toDF()
features = (VectorAssembler(inputCols=df.columns, outputCol="features")
.transform(df)
.select("features"))
features.show(4, False)
## +---------------------+
## |features |
## +---------------------+
## |(5,[],[]) |
## |[1.0,1.0,1.0,1.0,1.0]|
## |[1.0,0.0,1.0,0.0,1.0]|
## |(5,[1,3],[1.0,1.0]) |
## +---------------------+
它還顯示匯編程序根據非零條目的數量選擇不同的表示。
features.flatMap(lambda x: x).map(type).collect()
## [pyspark.mllib.linalg.SparseVector,
## pyspark.mllib.linalg.DenseVector,
## pyspark.mllib.linalg.DenseVector,
## pyspark.mllib.linalg.SparseVector]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.