在数据分析中,经常使用到 sklearn 进行决策树分析,用于挑选合适的变量。决策树一般自上而下,每个决策都可能引出两个或多个结果,把这种自上而下的决策,画成图形,就很像一棵树。每个决策对应树的枝干,而最终的结果可以看成枝干上的叶子。从根到叶子的路径可以看成一个结果的决策过程,叫做规则。有的时候需要深入寻找一些决策点的信息,所以就需要了解在 sklearn 中 decision tree 是怎么一种存在形式。

decision tree 的可视化

这里的测试数据是 iris 数据包,sklearn 中有一个 export_graphviz的函数,可以把决策树的树结构可视化, 不过需要提前安装graphviz

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0)
estimator.fit(X_train, y_train)

# virtualization
from sklearn.tree import export_graphviz
export_graphviz(estimator, out_file='tree.dot')

这里生成一个dot格式文件,需要使用graphviz转换为其他格式:

dot -Tpng tree.dot -o treeIris.png

一般在 jupyter notebook 里更喜欢直接显示,这里需要提前安装 Python 的graphviz包,这里graphviz软件应该提前在系统中安装好:

# 安装graphviz python 包
pip install graphviz

直接在 notebook 中显示树结构:

import graphviz

dotdata = export_graphviz(estimator,out_file=None, filled=True)      
graphviz.Source(dotdata)

在 notebook 中直接显示的话,鼠标移到上面的节点时,会有相应的数字提示,这些数字是对应的 node id,从最上面的根节点开始,记为0,后面依次递增。

decision tree 中的 tree_

decision tree 中有一个tree_ 属性,记录了决策树的许多信息,可以看看

_tree = estimator.tree__
dir(_tree)

'capacity',
'children_left',
'children_right',
'compute_feature_importances',
'decision_path',
'feature',
'impurity',
'max_depth',
'max_n_classes',
'n_classes',
'n_features',
'n_node_samples',
'n_outputs',
'node_count',
'threshold',
'value',
'weighted_n_node_samples'

里面保存了许多决策树过程的结果,如果想要获取决策树决策过程的信息,可以关注这些属性。

这里挑选了一些用到的一些信息进行说明:

  • max_depth,如果从0开始,那么 root 的深度为 0,上图的max_depth 为3
  • node_count, 节点的数量
  • children_left,nth-node(第n个节点)对应的左边子节点
  • children_right, nth-node对应的右边子节点
  • decision_path, 决策过程,记录了 i 样本被分到了 j 节点上,表示为 (i, j)
  • threshold,决策运行的标准,根据这些阈值来划分节点,进行决策
  • value,保存节点中样品数量信息,一般按照不同 class 保存

上面的信息多数保存在list类型的结构中,可以直接根据 nth-node 进行索引。对于叶子节点(leaf node),其 children_leftchildren_right对应值为 -1,而threshold值为 -2,可以根据这些信息来判断节点是属于叶节点还是枝干节点。

参考

  1. Understanding the decision tree structure
  2. Get sample number in each node
  3. Sample Number