如何在Python的Scikit-learn中获取决策树深度?

33
1个回答

56
每个实例的`RandomForestClassifier`都有一个`estimators_`属性,它是一个包含多个DecisionTreeClassifier实例的列表。文档显示,`DecisionTreeClassifier`实例具有`tree_`属性,这是`Tree`类(我认为是未记录的)的一个实例。在解释器中的一些探索显示,每个`Tree`实例都有一个`max_depth`参数,看起来这可能是您要查找的内容--再次强调,这是未经记录的。
无论如何,如果`forest`是您的`RandomForestClassifier`实例,则:
>>> [estimator.tree_.max_depth for estimator in forest.estimators_]
[9, 10, 9, 11, 9, 9, 11, 7, 13, 10]

这应该能解决问题。

每个估算器还有一个get_depth()方法,可以用更简洁的语法检索相同的值:

>>> [estimator.get_depth() for estimator in forest.estimators_]
[9, 10, 9, 11, 9, 9, 11, 7, 13, 10]
为了避免混淆,需要注意每个估计器(而不是每个估计器的tree_)都有一个叫做max depth 的属性,它返回参数的设置而不是实际树的深度。下面的示例说明了estimator.get_depth()estimator.tree_.max_depthestimator.max_depth之间的关系:
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=3, random_state=4, max_depth=6)
iris = load_iris()
clf.fit(iris['data'], iris['target'])
[(est.get_depth(), est.tree_.max_depth, est.max_depth) for est in clf.estimators_]

输出:

[(6, 6, 6), (3, 3, 6), (4, 4, 6)]

将最大深度设置为默认值None会使第一棵树扩展到深度7,并且输出结果如下:

[(7, 7, None), (3, 3, None), (4, 4, None)]

谢谢!这正是我一直在寻找的。同样,您知道是否有一种方法手动从随机森林中删除特定的树吗?我正在尝试删除深度小于某个值的树。 - iltp38
可能只需从列表中删除估计器即可。也就是说,要删除第一棵树,可以使用 del forest.estimators_[0]。或者仅保留深度为10或以上的树:forest.estimators_ = [e for e in forest.estimators_ if e.tree.max_depth >= 10]。但看起来 RandomForestClassifier 并不是以这种方式构建的,通过修改 forest.estimators_ 可能会破坏某些东西。您可以尝试并查看结果是否合理。如果是,请更新 forest.n_estimators = len(forest.estimators_) 以确保安全。 - jme
6
这个答案是不正确的,它告诉您随机森林中每棵树的最大允许深度,而不是实际深度。例如,使用max_depth=10训练的随机森林将返回:[10, 10, 10, ...] - jon_simon
1
它返回max_depth参数和实际深度值中较小的那个。 - Ken Fehling
1
请查看此链接 https://datascience.stackexchange.com/questions/19842/anyway-to-know-all-details-of-trees-grown-using-randomforestclassifier-in-scikit/36228#36228,以获取随机森林中每棵树的实际最大深度的所有详细信息。 - Terence Parr
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接