决策树的特征重要度提取(scikit-learn)

2024-04-23 16:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力掌握在我建模的决策树中使用的特性的重要性。我有兴趣发现在节点上选择的每个特征的权重以及术语本身。我的资料是一堆文件。 这是我的决策树代码,我修改了scikit中的代码片段learn that extract(http://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html):

from sklearn.feature_extraction.text import TfidfVectorizer

### Feature extraction
tfidf_vectorizer = TfidfVectorizer(stop_words=stopwords,
                                 use_idf=True, tokenizer=None, ngram_range=(1,2))#ngram_range=(1,0)

tfidf_matrix = tfidf_vectorizer.fit_transform(data[:, 1]) 
terms = tfidf_vectorizer.get_features_names()
### Define Decision Tree and fit
dtclf = DecisionTreeClassifier(random_state=1234)

dt = data.copy()

y = dt["label"]
X = tfidf_matrix

fitdt = dtclf.fit(X, y)

from sklearn.datasets import load_iris
from sklearn import tree

### Visualize Devision Tree

with open('data.dot', 'w') as file:
    tree.export_graphviz(dtclf, out_file = file, feature_names = terms)
file.close()

import subprocess
subprocess.call(['dot', '-Tpdf', 'data.dot', '-o' 'data.pdf'])

### Extract feature importance

importances = dtclf.feature_importances_

indices = np.argsort(importances)[::-1]

# Print the feature ranking
print('Feature Ranking:')

for f in range(tfidf_matrix.shape[1]):
    if importances[indices[f]] > 0:
        print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
        print ("feature name: ", terms[indices[f]])
  1. 假设使用术语[索引[f]](这是特征项向量)将打印用于在某个节点上拆分树的实际特征项,这是正确的吗?
  2. 用GraphViz可视化的决策树有例如X[30],我假设这是指特征项的数值解释。如何提取术语本身,以便验证在1中部署的流程?

更新代码

fitdt = dtclf.fit(X, y)
with open(...):
tree.export_graphviz(dtclf, out_file = file, feature_names = terms)

提前谢谢


Tags: 代码fromimport决策树data特征featurefit
1条回答
网友
1楼 · 发布于 2024-04-23 16:40:24

对于第一个问题,您需要使用terms = tfidf_vectorizer.get_feature_names()从矢量器中获取特征名称。对于第二个问题,您可以使用feature_names = terms调用export_graphviz,以获取变量的实际名称,使其显示在可视化中(请查看export_graphviz的完整文档,以获取可能有助于改进可视化的许多其他选项。

相关问题 更多 >