首页 > 解决方案 > 将火花管道转换为数据框

问题描述

Spark Pipeline 框架允许以可重现的方式为机器学习或其他应用程序创建转换管道。但是,在创建数据框时,我希望能够执行探索性分析。

就我而言,我有大约 100 列,其中 80 列是字符串,需要进行一次热编码:

from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer,VectorAssembler
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.classification import LogisticRegressionModel

#cols_to_one_hot_encode_2 is a list of columns that need to be one hot encoded
#cols_to_keep_as_is are columns that are **note** one hot encoded

cols_to_one_hot_encode_3=[i+"_hot" for i in cols_to_one_hot_encode_2]
encoder= OneHotEncoderEstimator(inputCols=cols_to_one_hot_encode_2,
                                 outputCols=cols_to_one_hot_encode_3,dropLast=False)

#assemble pipeline
vectorAssembler = VectorAssembler().setInputCols(cols_to_keep_as_is+cols_to_one_hot_encode_3).setOutputCol("features")
all_stages=indexers
all_stages.append(encoder)
all_stages.append(vectorAssembler)
transformationPipeline=Pipeline(stages=all_stages)
fittedPipeline=transformationPipeline.fit(df_3)
dataset = fittedPipeline.transform(df_3)

#now pass to logistic regression
selectedcols = ["response_variable","features"] #+df_3.columns
dataset_2= dataset.select(selectedcols)

# Create initial LogisticRegression model
lr = LogisticRegression(labelCol="response_variable", featuresCol="features", maxIter=10,elasticNetParam=1)

# Train model with Training Data
lrModel = lr.fit(dataset_2)

当我查看 dataset_2 时display(dataset_2),它会打印:

response_variable       features
0   [0,6508,[1,4,53,155,166,186,205,242,2104,6225,6498],[8220,1,1,1,1,1,1,1,1,1,1]]
0   [0,6508,[1,3,53,155,165,185,207,243,2104,6225,6498],[8220,1,1,1,1,1,1,1,1,1,1]]
0   [0,6508,[1,2,53,158,170,185,206,241,2104,6225,6498],[8222,1,1,1,1,1,1,1,1,1,1]]
0   [0,6508,[1,3,53,156,168,185,205,240,2104,6225,6498],[8222,1,1,1,1,1,1,1,1,1,1]]
0   [0,6508,[1,2,53,155,166,185,205,240,2104,6225,6498],[8223,1,1,1,1,1,1,1,1,1,1]]

这对于进行特征探索完全没用。请注意,one-hot 编码器已将我的特征从约 100 列爆炸到 6508。

我的问题

如何查看管道在后台创建的数据框?这应该是一个具有 6058 个特征和相应行数的数据框,例如:例如,我想要类似:

response_variable    feature_1_hot_1 feature_1_hot_2  feature_1_hot_3 ... (6505 more columns)
0                    1               1                0

etc.

不是重复的

不是如何将向量拆分为列的副本 - 使用 PySpark 那是询问如何基于分隔符进行文字字符串拆分。管道完成的转换不是简单的字符串拆分。请参阅仅为转换使用 Spark ML 管道

标签: apache-sparkpipelinedatabricks

解决方案


如何查看管道在后台创建的数据框?

没有这样的隐藏结构。Spark MLPipelines围绕VectorUDT列和元数据构建以丰富结构。没有包含扩展列的中间结构,如果在哪里,它将无法扩展(Spark 不处理将在此处生成的宽而密集的数据,并且当列数达到数万时查询计划程序会窒息)鉴于当前的实施。

拆分列分析元数据是您最好的也是唯一的选择。


推荐阅读