pyspark随机森林分类器的功能重要性与列名

时间:2019-01-24 07:18:40

标签: python apache-spark pyspark random-forest

我正在尝试使用列名称来绘制随机森林分类器的功能重要性。我正在使用Spark 2.3.2和Pyspark。

输入X是句子,我正在使用tfidf(HashingTF + IDF)+ StringIndexer生成特征向量。

我已经将所有阶段包括在管道中。

regexTokenizer = RegexTokenizer(gaps=False,  \
                        inputCol= raw_data_col, \
                        outputCol= "words",  \
                        pattern="[a-zA-Z_]+", \
                        toLowercase=True, \
                        minTokenLength=minimum_token_size)

hashingTF = HashingTF(inputCol="words", outputCol="rawFeatures", numFeatures=number_of_feature)
idf = IDF(inputCol="rawFeatures", outputCol= feature_vec_col)

indexer = StringIndexer(inputCol= label_col_name, outputCol= label_vec_name)
converter = IndexToString(inputCol='prediction', outputCol="original_label", labels=indexer.fit(df).labels)

feature_pipeline = Pipeline(stages=[regexTokenizer, hashingTF, idf, indexer])

estimator = RandomForestClassifier(labelCol=label_col, featuresCol=features_col, numTrees=100)

pipeline = Pipeline(stages=[feature_pipeline, estimator, converter])

model = pipeline.fit(df)

将功能重要性生成为

rdc = model.stages[-2]
print (rdc.featureImportances)

到目前为止很好,但是当我尝试使用下面的thisthis问题中的示例将功能重要性映射到功能列时

attrs = sorted((attr["idx"], attr["name"]) for attr in (chain(*df_pred.schema["featurescol"].metadata["ml_attr"]["attrs"].values())))

[(name, rdc.featureImportances[idx])
   for idx, name in attrs
   if dtModel_1.featureImportances[idx]]

我在ml_attr上收到关键错误

KeyError: 'ml_attr'

打印字典,

print (df_pred.schema["featurescol"].metadata)

它是空的{}

对我在做什么错有任何想法吗?如何获得列名称的功能重要性。

谢谢

1 个答案:

答案 0 :(得分:0)

我无法解决空白元数据问题,但无法通过列名称映射随机森林分类器的功能重要性-我通过以下代码获取它:

router.route('/user/:user_id').get(//);
相关问题