‘CrossValidatorModel’对象没有属性’featureImportances’

我正在尝试提取使用Pyspark训练的随机森林分类器模型的特征重要性。我参考了以下文章来获取我训练的随机森林模型的特征重要性得分。

PySpark & MLLib: 随机森林特征重要性

然而,当我使用该文章中描述的方法时,我遇到了以下错误

'CrossValidatorModel' object has no attribute 'featureImportances'

这是我用来训练模型的代码

cols = new_data.columnsstages = []label_stringIdx = StringIndexer(inputCol = 'Bought_Fibre', outputCol = 'label')stages += [label_stringIdx]numericCols = new_data.schema.names[1:-1]assembler = VectorAssembler(inputCols=numericCols, outputCol="features")stages += [assembler]pipeline = Pipeline(stages = stages)pipelineModel = pipeline.fit(new_data)new_data.fillna(0, subset=cols)new_data = pipelineModel.transform(new_data)new_data.fillna(0, subset=cols)new_data.printSchema()train_initial, test = new_data.randomSplit([0.7, 0.3], seed = 1045)train_initial.groupby('label').count().toPandas()test.groupby('label').count().toPandas()train_sampled = train_initial.sampleBy("label", fractions={0: 0.1, 1: 1.0}, seed=0)train_sampled.groupBy("label").count().orderBy("label").show()labelIndexer = StringIndexer(inputCol='label',                             outputCol='indexedLabel').fit(train_sampled)featureIndexer = VectorIndexer(inputCol='features',                               outputCol='indexedFeatures',                               maxCategories=2).fit(train_sampled)from pyspark.ml.classification import RandomForestClassifierrf_model = RandomForestClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures")labelConverter = IndexToString(inputCol="prediction", outputCol="predictedLabel",                               labels=labelIndexer.labels)pipeline = Pipeline(stages=[labelIndexer, featureIndexer, rf_model, labelConverter])paramGrid = ParamGridBuilder() \    .addGrid(rf_model.numTrees, [ 200, 400,600,800,1000]) \    .addGrid(rf_model.impurity,['entropy','gini']) \    .addGrid(rf_model.maxDepth,[2,3,4,5]) \    .build()crossval = CrossValidator(estimator=pipeline,                          estimatorParamMaps=paramGrid,                          evaluator=BinaryClassificationEvaluator(),                          numFolds=5)    train_model = crossval.fit(train_sampled)

请帮助解决上述错误,并帮助提取特征


回答:

这是因为CrossValidatorModel没有特征重要性的属性,但RandomForestModel模型有这个属性。

由于您使用PipelineCrossValidator来拟合数据,您需要获取最佳拟合模型中的底层阶段:

# '2' 是 Pipeline 中您的 RandomForestModel 的索引your_model = cvModel.bestModel.stages[2] var_imp = your_model.featureImportances

Related Posts

为什么我们在K-means聚类方法中使用kmeans.fit函数?

我在一个视频中使用K-means聚类技术,但我不明白为…

如何获取Keras中ImageDataGenerator的.flow_from_directory函数扫描的类名?

我想制作一个用户友好的GUI图像分类器,用户只需指向数…

如何查看每个词的tf-idf得分

我试图了解文档中每个词的tf-idf得分。然而,它只返…

如何修复 ‘ValueError: Found input variables with inconsistent numbers of samples: [32979, 21602]’?

我在制作一个用于情感分析的逻辑回归模型时遇到了这个问题…

如何向神经网络输入两个不同大小的输入?

我想向神经网络输入两个数据集。第一个数据集(元素)具有…

逻辑回归与机器学习有何关联

我们正在开会讨论聘请一位我们信任的顾问来做机器学习。一…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注