【问题标题】:Feature Importance extraction of Decision Trees (scikit-learn)决策树的特征重要性提取(scikit-learn)
【发布时间】:2016-03-18 07:11:58
【问题描述】:

我一直在尝试了解我所建模的决策树中使用的特征的重要性。我有兴趣发现在节点上选择的每个特征的权重以及术语本身。我的数据是一堆文件。 这是我的决策树代码,我修改了 scikit-learn 中提取的代码 sn-p (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. 我是否正确假设使用 terms[indices[f]](这是特征项向量)将打印用于在某个节点处拆分树的实际特征项?
  2. 使用 GraphViz 可视化的决策树具有例如 X[30],我假设这是指特征项的数值解释。如何提取术语本身,以便验证我在 #1 中部署的流程?

更新代码

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

提前致谢

【问题讨论】:

  • @maxymoo 更新了两行代码

标签: python tree scikit-learn decision-tree feature-extraction


【解决方案1】:

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

【讨论】:

  • 当我在 export_graphviz 中包含 feature_names = terms 时,图形输出保持不变。所以它仍然是 X[1] get_features() also features = (dict(zip(tfidf_vectorizer.get_feature_names(), tfidf_matrix)))。所以调用函数看起来像:tree.export_graphviz(fit_dt, out_file = file, feature_names=terms)。有什么想法吗?
  • 对不起,我第一次错过了这个问题。你需要设置terms = tfidf_vectorizer.get_feature_names()
  • 我有那行,我必须不小心从帖子中删除它。我重新检查并重新运行了代码,但样式 X[#]
猜你喜欢
  • 2019-12-11
  • 2018-08-16
  • 2017-11-04
  • 2020-05-27
  • 2018-05-15
  • 2013-12-12
相关资源
最近更新 更多