如何解释sklearn决策树树中的children_left属性_

Fel*_*a.H 3 tree decision-tree scikit-learn

我正在尝试使用 sklearn DecisionTreeClassifier 中的“tree_”方法提取最深节点的规则。我很难理解模型中 'children_left' 和 'children_right' 数组的含义。谁能帮忙解释一下?

estimator = DecisionTreeClassifier(max_depth=4, random_state=0)
estimator.fit(X_train, y_train)
estimator.tree_.children_left

[6] array([ 1,  2,  3,  4,  5, -1, -1,  8, -1, -1, 11, 12, -1, -1, 15, -1, -1,
   18, 19, 20, -1, -1, 23, -1, -1, 26, 27, -1, -1, 30, -1, -1, 33, 34,
   35, 36, -1, -1, 39, -1, -1, 42, 43, -1, -1, 46, -1, -1, 49, 50, 51,
   -1, -1, 54, -1, -1, 57, 58, -1, -1, 61, -1, -1])

tree_model.tree_.children_right

[7] array([32, 17, 10,  7,  6, -1, -1,  9, -1, -1, 14, 13, -1, -1, 16, -1, -1,
   25, 22, 21, -1, -1, 24, -1, -1, 29, 28, -1, -1, 31, -1, -1, 48, 41,
   38, 37, -1, -1, 40, -1, -1, 45, 44, -1, -1, 47, -1, -1, 56, 53, 52,
   -1, -1, 55, -1, -1, 60, 59, -1, -1, 62, -1, -1])
Run Code Online (Sandbox Code Playgroud)

在 Sklearn 的例子中,http : //scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html ,它说:

`# The decision estimator has an attribute called tree_  which stores the    entire
# tree structure and allows access to low level attributes. The binary tree
# tree_ is represented as a number of parallel arrays. The i-th element of  each
# array holds information about the node `i`. Node 0 is the tree's root. NOTE:
# Some of the arrays only apply to either leaves or split nodes, resp.`
Run Code Online (Sandbox Code Playgroud)

但它并没有解释 children_left 数组中数字的含义

小智 5

from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
children_left = clf.tree_.children_left
print (children_left)
Run Code Online (Sandbox Code Playgroud)

它打印:

[ 1 -1  3  4  5 -1 -1  8 -1 10 -1 -1 13 14 -1 -1 -1]
Run Code Online (Sandbox Code Playgroud)

你可以在谷歌找到鸢尾花数据的 17 个节点决策树。看到它并与解释进行比较。

现在来解释:

  • 它只代表一个节点的左子节点。
  • 如果值为 -1,则表示该节点没有左节点。然后它是该决策树的叶节点。在这里我们可以看到有 9 个叶子节点。
  • 如果该值 >0,则它已离开节点。因此它不是叶节点。这里 8 个节点不是叶节点。
    • 根有一个左节点。它是 1。
    • 现在 1 没有任何左节点。所以它是叶节点。因此-1.如果一个节点没有左节点,它也将节点数增加到1。所以现在节点数是2。
    • 现在我们回溯到root。然后我们转到root的右节点。它已经离开了节点。现在节点数是 3。
    • 节点 3 有另一个左节点。节点数 4。
    • 节点 4 有另一个左节点。节点数 5。
    • 节点 5 没有任何左节点。所以它是叶子并显示-1。但是现在节点数是 6。
    • 我们回溯到节点 4。我们去它的右子节点。同样,它没有任何左子。所以它是叶子并显示-1。节点数 7.
    • 我们再次回溯到节点 3。我们转到它的右子节点。这个节点有左节点。所以现在节点数是 8。

它继续。希望你得到解释。