使用数值和分类变量在 PySpark 中创建“特征”列

agrajag_42

我正在尝试使用 Python 在 Spark 中创建一个“功能”列,以便机器学习库使用。但是,我在生成“特征”列的 VectorAssembler 中遇到了包括数值和分类变量在内的问题。

cat_cols = ["cat_1", "cat_2", "cat_3"]
num_cols = ["num_1", "num_2", "num_3", "num_4"]

indexers = [StringIndexer(inputCol = c, outputCol="{0}_indexed".format(c)) for c in cat_cols]

encoders = [StringIndexer(inputCol = indexer.getOutputCol(), outputCol = "{0}_encoded".format(indexer.getOutputCol())) 
for indexer in indexers]

assembler = VectorAssembler(inputCols = [encoder.getOutputCol() for encoder in encoders], outputCol = "features")

pipeline = Pipeline(stages = indexers + encoders + [assembler])
df = pipeline.fit(df).transform(df)

到目前为止构建的管道可以创建一个仅包含分类变量的“特征”列,但我不知道如何扩展它以使“特征”列同时包含分类变量和数值变量。

请注意,我使用的是 Spark 2.3 和 Python 3。

agrajag_42

我找到了一种方法,但我不确定这是否是实现我想要的最有效方法。

cat_cols = ["cat_1", "cat_2", "cat_3"]
num_cols = ["num_1", "num_2", "num_3", "num_4"]

indexers = [StringIndexer(inputCol = c, outputCol="{0}_indexed".format(c)) for c in cat_cols]

encoders = [StringIndexer(inputCol = indexer.getOutputCol(), outputCol = "{0}_encoded".format(indexer.getOutputCol())) 
for indexer in indexers]

assemblerCat = VectorAssembler(inputCols = [encoder.getOutputCol() for encoder in encoders], outputCol = "cat")

pipelineCat = Pipeline(stages = indexers + encoders + [assemblerCat])
df = pipelineCat.fit(df).transform(df)

assemblerNum = VectorAssembler(inputCols = num_cols, outputCol = "num")

pipelineNum = Pipeline(stages = [assemblerNum])
df = pipelineNum.fit(df).transform(df)

assembler = VectorAssembler(inputCols = ["cat", "num"], outputCol = "features")

pipeline = Pipeline(stages = [assembler])
df = pipeline.fit(df).transform(df)

本质上,我正在为分类变量创建一个管道,为数字变量创建一个管道,然后我将它们合并以创建一个包含两者的单个“特征”列。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Pyspark中创建新列的使用和条件

如何在机器学习中的数值和分类特征上使用统一管道?

在数据框pyspark中创建新的列和行

使用pyspark中的条件创建具有运行总量的列

PySpark使用字典中的映射创建新列

在Spark ML / pyspark中以编程方式创建特征向量

特征选择和分类变量

如何计算 pyspark 数据帧中多列的列中每个分类变量的频率?

如何使用行号inf pyspark创建列

如何使用多列创建pyspark udf?

如何在pyspark中按有序分类变量创建和排序

使用经度和纬度列作为在PySpark中的输入,从TimezoneFinder()创建新的“时区”列

使用文件名创建变量 - PySpark

pyspark中的累积和

如何计算 R 中数值和分类变量的描述性统计量?

使用 pyspark 基于 if 和 else 条件创建新列

PySpark:使用when和contains / isin创建列

Pyspark根据新条件创建新的分类列

使用列表pyspark中的结构创建选择

在pyspark中的Scala UDF中使用默认参数值?

Pyspark-使用数据框中其他两个列的RMSE创建新列

使用 spark/pyspark 在 pyspark 中使用列名及其在其他列中的关联值创建新数据框

在 pyspark 中添加新的列和行

使用pyspark同时进行聚合和特征提取

在 Pyspark 中创建 Total 和总列的百分比

使用pyspark对列中的值求和

PySpark:使用从列创建的元组添加新列

在python中在多个数值变量上绘制分类变量

Pyspark:列和索引的Rank()?