如何在python中找出sklearn决策树的大小?

时间:2014-10-28 06:47:54

标签: python machine-learning scikit-learn nodes decision-tree

我正在使用决策树进行一些特征导入,并希望根据节点数知道树的大小。我怎么在python中做到这一点?

使用sklearn网站上的股票示例

x = [[0,0],[0,1]]
y = [0,1] 

from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifer(n_estimators = 10)
clf = clf.fit(x,y)

我可以通过像clf [1],clf [...]之类的东西找到单个树,但是如何根据总节点数确定每棵树的大小?

3 个答案:

答案 0 :(得分:2)

sklearn.tree._tree.Tree对象有一个'node_count'属性:

from sklearn import tree
X = [[0, 0], [1, 1]]
Y = [0, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, Y)
treeObj = clf.tree_
print treeObj.node_count

答案 1 :(得分:0)

与所有语言的所有树一样:

每个节点返回1 +所有子树大小的总和。

在python中,在root上应用此方法:

def size(tree):
    return 1 + sum([size(subtree) for subtree in tree.subtrees])

具体到sklearn,在这里查看源代码[https://github.com/scikit-learn/scikit-learn/tree/master/sklearn]

我认为可以尝试这样做:

nodeNumber = sum( len(tree.value) for tree in clf.estimators_ )

答案 2 :(得分:0)

最大深度是一个非常有用的指标,我没有在API中找到,所以我写了这个:

def dectree_max_depth(tree):
    n_nodes = tree.node_count
    children_left = tree.children_left
    children_right = tree.children_right

    def walk(node_id):
        if (children_left[node_id] != children_right[node_id]):
            left_max = 1 + walk(children_left[node_id])
            right_max = 1 + walk(children_right[node_id])
            return max(left_max, right_max)
        else: # leaf
            return 1

    root_node_id = 0
    return walk(root_node_id)

您可以像这样在森林(rf)中的所有树木上使用它:

[dectree_max_depth(t.tree_) for t in rf.estimators_]

BSD许可证。