我正在使用scikit-learn创建随机森林。但是,我想找到每棵树的深度。它似乎是一个简单的属性,但是根据文档(http://scikit-learn.org/stable/modules/generation/sklearn.ensemble.RandomForestClassifier.html),无法访问它。
如果这不可能,是否有一种方法可以从“决策树”模型中访问树的深度?
任何帮助,将不胜感激。谢谢你。
的每个实例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_depth
以及estimator.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)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句