【问题标题】:scikit-learn decision tree node depthscikit-learn 决策树节点深度
【发布时间】:2017-01-21 10:21:59
【问题描述】:

我的目标是确定决策树中两个样本分离的深度。在 scikit-learn 的开发版本中,您可以使用decision_path() 方法识别到最后一个公共节点:

from sklearn import tree
import numpy as np

clf = tree.DecisionTreeClassifier()
clf.fit(data, outcomes)
n_nodes = clf.tree_.node_count
node_indicator = clf.decision_path(data).toarray()
sample_ids = [0,1]
common_nodes = (node_indicator[sample_ids].sum(axis=0) == len(sample_ids))
common_node_id = np.arange(n_nodes)[common_nodes]
max_node = np.max(common_node_id)

有没有办法确定max_node 在树中出现的深度,可能是clf.tree_.children_rightclf.tree_.chrildren_left

【问题讨论】:

    标签: python scikit-learn decision-tree


    【解决方案1】:

    这是一个可以用来递归遍历节点并计算节点深度的函数

    def get_node_depths(tree):
        """
        Get the node depths of the decision tree
    
        >>> d = DecisionTreeClassifier()
        >>> d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3])
        >>> get_node_depths(d.tree_)
        array([0, 1, 1, 2, 2])
        """
        def get_node_depths_(current_node, current_depth, l, r, depths):
            depths += [current_depth]
            if l[current_node] != -1 and r[current_node] != -1:
                get_node_depths_(l[current_node], current_depth + 1, l, r, depths)
                get_node_depths_(r[current_node], current_depth + 1, l, r, depths)
    
        depths = []
        get_node_depths_(0, 0, tree.children_left, tree.children_right, depths) 
        return np.array(depths)
    

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 2019-12-11
      • 2017-02-23
      • 2020-04-05
      • 2020-08-29
      • 1970-01-01
      • 2017-03-07
      • 2015-03-05
      相关资源
      最近更新 更多