Python – Using sklearn, how to find depth of a decision tree

decision-treepythonscikit-learn

I am training a decision tree with sklearn. When I use:

dt_clf = tree.DecisionTreeClassifier()

the max_depth parameter defaults to None. According to the documentation, if max_depth is None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.

After fitting my model, how do I find out what max_depth actually is? The get_params() function doesn't help. After fitting, get_params() it still says None.

How can I get the actual number for max_depth?

Docs: https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html

Best Answer

Access the max_depth for the underlying Tree object:

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

You may get more accessible attributes from the underlying tree object using:

help(clf.tree_)

These include max_depth, node_count, and other lower-level parameters.

Related Topic