26

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

fzzle
  • 1,466
  • 5
  • 23
  • 28
Mel
  • 6,214
  • 10
  • 54
  • 71

2 Answers2

30

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.

Primusa
  • 13,136
  • 3
  • 33
  • 53
5

The answer according to the docs https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.get_depth is to use the tree.get_depth() function.

hcbh96
  • 81
  • 1
  • 3
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30905438) – Simas Joneliunas Jan 30 '22 at 04:54