scikit-learn decision tree node depth
<p>My goal is to identify at what depth two samples separate within a decision tree. In the development version of scikit-learn you can use the <code>decision_path()</code> method to identify to last common node:</p>

<pre><code>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)
</code></pre>

<p>Is there a way to determine at what depth the <code>max_node</code> occurs within the tree, possibly with <code>clf.tree_.children_right</code> and <code>clf.tree_.chrildren_left</code>?</p>

<p>Here is a function that you could use to recursively traverse the nodes and calculate the node depths</p>

<pre><code>def get_node_depths(tree):
    """
    Get the node depths of the decision tree

    &gt;&gt;&gt; d = DecisionTreeClassifier()
    &gt;&gt;&gt; d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3])
    &gt;&gt;&gt; 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)
</code></pre>

python scikit-learn decision-tree