Neural network 如何使用pyspark.ml神经网络分类器获得预处理后的特征数?

Neural network 如何使用pyspark.ml神经网络分类器获得预处理后的特征数?,neural-network,pyspark,one-hot-encoding,Neural Network,Pyspark,One Hot Encoding,我正在尝试使用pyspark.ml构建一个神经网络。 问题是我正在使用onehotencoder和其他预处理方法来转换分类变量。我正在考虑的阶段包括: 为分类特征编制索引 使用Onehotencoder 使用向量汇编程序 然后我申请PCA 将“PCA特征”赋予神经网络分类器 但问题是,我不知道在第4步之后,在第5步中为分类器的“层”提供多少特征。 我的问题是如何获得最终的功能数量?这是我的代码,我没有包括导入和数据加载部分 stages = [] for c in Categories:

我正在尝试使用pyspark.ml构建一个神经网络。 问题是我正在使用onehotencoder和其他预处理方法来转换分类变量。我正在考虑的阶段包括:

  • 为分类特征编制索引
  • 使用Onehotencoder
  • 使用向量汇编程序
  • 然后我申请PCA
  • 将“PCA特征”赋予神经网络分类器
  • 但问题是,我不知道在第4步之后,在第5步中为分类器的“层”提供多少特征。 我的问题是如何获得最终的功能数量?这是我的代码,我没有包括导入和数据加载部分

    stages = []
    for c in Categories:
        stringIndexer = StringIndexer(inputCol= c , outputCol=c + "_indexed")
        encoder = OneHotEncoder(inputCol= c + "_indexed", outputCol=c + "_categoryVec")
        stages += [stringIndexer, encoder]
    
    labelIndexer = StringIndexer(inputCol="Target", outputCol="indexedLabel")
    
    final_features = list(map(lambda c: c+"_categoryVec", Categories))+Continuous
    
    
    assembler = VectorAssembler(
        inputCols= final_features,
        outputCol="features")
    
    pca = PCA(k=20, inputCol="features", outputCol="pcaFeatures")
    (train_val, test_val) = train.randomSplit([0.95, 0.05])
    
    num_classes= train.select("Target").distinct().count()
    
    NN= MultilayerPerceptronClassifier(labelCol="indexedLabel", featuresCol='pcaFeatures', maxIter=100,
                                        layers=[????, 5, 5, num_classes], blockSize=10, seed=1234)
    
    
    stages += [labelIndexer]
    stages += [assembler]
    stages += [pca]
    stages += [NN]
    
    pipeline = Pipeline(stages=stages)
    model = pipeline.fit(train_val)
    
    从中,输入参数
    k
    是主成分的数量

    因此,在你的情况下:

    pca=pca(k=20,inputCol=“features”,outputCol=“pcaFeatures”)
    
    功能部件的数量为20个

    更新

    另一种方法是查看其中一个组合向量的长度

    例如,如果您希望在步骤3之后获得长度:

    从pyspark.sql.functions导入udf,col
    nfeatures=assembler.withColumn('len',udf(len,IntegerType())(col('features'))\
    .选择('len')。取(1)
    

    我觉得应该有更好的方法来实现这一点,即不必调用
    take()

    ,这很有意义!我不知道为什么我没有看到它。谢谢。顺便说一句,如果我没有使用PCA,你知道我如何从第3步获得功能的数量吗?len(最终功能)不工作,因为onehotencoder不返回多个列。使用pyspark并不简单。无论如何,我现在将保留PCA以完成我的任务!我猜我错删除了你的评论。对此表示抱歉。