【问题标题】:How do you access tree depth in Python's scikit-learn?如何在 Python 的 scikit-learn 中访问树深度?
【发布时间】:2016-03-16 19:24:12
【问题描述】:

我正在使用 scikit-learn 创建一个随机森林。但是,我想找到每棵树的各个深度。这似乎是一个简单的属性,但根据文档,(http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html) 无法访问它。

如果这不可能,有没有办法从决策树模型中访问树深度?

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python scikit-learn random-forest decision-tree depth


    【解决方案1】:

    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)]
    

    【讨论】:

    • 谢谢!!这正是我一直在寻找的。同样,您知道是否有办法从随机森林中手动删除特定的树?我正在尝试删除小于一定深度的树。
    • 可能就像从列表中删除估算器一样简单。也就是说,要删除第一棵树,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_) 以获得更好的效果。
    • 这个答案不正确,它告诉你森林中每棵树的最大允许深度,而不是实际深度。例如,使用max_depth=10 训练的随机森林将返回:[10, 10, 10, ...]
    • 它返回 max_depth 参数和实际深度值中较低的那个。
    • 查看datascience.stackexchange.com/questions/19842/… 以获取森林中每棵树的实际最大深度。
    猜你喜欢
    • 2017-01-21
    • 2016-04-09
    • 2020-04-01
    • 2021-03-07
    • 2017-12-14
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多