我正在使用 sk-learn python 27 并输出了一些决策树特征结果。虽然我不确定如何解释结果。起初,我认为这些功能是从信息最多到信息最少(从上到下)列出的,但检查了\n它建议的值。如何从输出或使用 python 行中识别前 5 个信息最丰富的特征?
from sklearn import tree
tree.export_graphviz(classifierUsed2, feature_names=dv.get_feature_names(), out_file=treeFileName)
# Output below
digraph Tree {
node [shape=box] ;
0 [label="avg-length <= 3.5\ngini = 0.0063\nsamples = 250000\nvalue = [249210, 790]"] ;
1 [label="name-entity <= 2.5\ngini = 0.5\nsamples = 678\nvalue = [338, 340]"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="first-name=wm <= 0.5\ngini = 0.4537\nsamples = 483\nvalue = [168, 315]"] ;
1 -> 2 ;
3 [label="name-entity <= 1.5\ngini = 0.4016\nsamples = 435\nvalue = [121, 314]"] ;
2 -> 3 ;
4 [label="substring=ee <= 0.5\ngini = 0.4414\nsamples = 73\nvalue = [49, 24]"] ;
3 -> 4 ;
5 [label="substring=oy <= 0.5\ngini = 0.4027\nsamples = 68\nvalue = [49, 19]"] ;
4 -> 5 ;
6 [label="substring=im <= 0.5\ngini = 0.3589\nsamples = 64\nvalue = [49, 15]"] ;
5 -> 6 ;
7 [label="lastLetter-firstName=w <= 0.5\ngini = 0.316\nsamples = 61\nvalue = [49, 12]"] ;
6 -> 7 ;
8 [label="firstLetter-firstName=w <= 0.5\ngini = 0.2815\nsamples = 59\nvalue = [49, 10]"] ;
7 -> 8 ;
9 [label="substring=sa <= 0.5\ngini = 0.2221\nsamples = 55\nvalue = [48, 7]"] ;
... many many more lines below
最佳答案
在 Python 中,您可以使用
DecisionTreeClassifier.feature_importances_
,根据 documentation包含The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance [R66].
只需执行
np.argsort
根据功能重要性,您将获得功能排名(不考虑平局)。您可以查看Gini impurity (graphviz 输出中的
\ngini
)以获得第一个想法。越低越好。但是,请注意,如果在多个分割中使用某个特征,您将需要一种组合杂质值的方法。通常,这是通过对给定特征的所有分割取平均信息增益(或“纯度增益”)来完成的。如果您使用feature_importances_
,这一切都会为您完成。
编辑: 我发现问题比我想象的更严重。 graphviz 只是树的图形表示。它详细显示了树和树的每个分支。这是树的表示,而不是特征的表示。特征的信息量(或重要性)并不真正适合这种表示,因为它在树的多个节点上积累信息。
变量classifierUsed2.feature_importances_
包含每个特征的重要性信息。例如,如果您得到 [0, 0.2, 0, 0.1, ...] 第一个特征的重要性为 0,第二个特征的重要性为 0.2,第三个特征的重要性为 0,第四个特征的重要性0.1,依此类推。
让我们按重要性对功能进行排序(最重要的在前):
rank = np.argsort(classifierUsed2.feature_importances_)[::-1]
现在排名包含特征的索引,从最重要的索引开始:[1, 3, 0, 1, ...]
想了解五个最重要的功能吗?
print(rank[:5])
这将打印索引。什么索引对应什么特征?这是你自己应该知道的事情,因为你应该构建了特征矩阵。这很可能有效:
print(dv.get_feature_names()[rank[:5]])
或者也许是这样:
print('\n'.join(dv.get_feature_names()[i] for i in rank[:5]))
关于python-2.7 - 如何解释决策树的图形结果并找到最具信息性的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34871212/