‘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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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