我正在尝试使用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。
答案 0 :(得分:3)
我找到了一种方法,但我不确定这是否是实现我想要的最有效方式。
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)
基本上我正在创建一个用于分类的管道和一个用于数值变量的管道,然后我将它们合并以创建单个"功能"包含两者的列。