【问题标题】:How can I get information about the trees in a Random Forest in sklearn?如何在 sklearn 中获取有关随机森林中树木的信息?
【发布时间】:2019-03-21 23:20:09
【问题描述】:

我想详细了解我正在使用 sklearn 构建的随机森林回归器。例如,如果我不进行正则化,树木的平均深度是多少?

这样做的原因是我需要对模型进行正则化,并希望了解模型目前的样子。另外,如果我设置例如max_leaf_nodes 是否仍然需要限制 max_depth 或者这种“问题”会自行解决,因为树不能长得太深,因为 max_leaf_nodes 已设置。这有意义还是我想错了方向?我在这个方向找不到任何东西。

【问题讨论】:

    标签: python python-3.x scikit-learn


    【解决方案1】:

    如果您想知道构成随机森林模型的树的平均最大深度,您必须单独访问每棵树并查询其最大深度,然后根据您获得的结果计算统计量。

    让我们首先制作一个随机森林分类器模型的可重现示例(取自Scikit-learn documentation

    from sklearn.ensemble import RandomForestClassifier
    from sklearn.datasets import make_classification
    
    X, y = make_classification(n_samples=1000, n_features=4,
                               n_informative=2, n_redundant=0,
                               random_state=0, shuffle=False)
    
    clf = RandomForestClassifier(n_estimators=100,
                                 random_state=0)
    clf.fit(X, y)
    

    现在我们可以遍历其包含每个决策树的estimators_ 属性。对于每个决策树,我们查询属性tree_.max_depth,存储响应并在完成迭代后取平均值:

    max_depth = list()
    for tree in clf.estimators_:
        max_depth.append(tree.tree_.max_depth)
    
    print("avg max depth %0.1f" % (sum(max_depth) / len(max_depth)))
    

    这将使您了解构成随机森林模型的每棵树的平均最大深度(正如您所询问的,它对于回归模型也完全相同)。

    无论如何,作为一个建议,如果你想规范你的模型,你有更好的测试参数假设在 cross-validationgrid/random search 范式下。在这种情况下,您实际上不需要质疑超参数之间的交互方式,您只需测试不同的组合并根据交叉验证分数获得最佳组合。

    【讨论】:

    • 是的,当然,我将使用网格搜索进行超参数调整,但我想了解问题和方法。
    • 使用我提供的代码,您可以根据您选择的超参数 max_leaf_nodes 和 max_depth 获得有关随机森林中树的平均最大深度所需的统计信息。
    【解决方案2】:

    除了@Luca Massaron 的回答:

    我找到了https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html#sphx-glr-auto-examples-tree-plot-unveil-tree-structure-py,它可以应用到森林中的每棵树上

    for tree in clf.estimators_:
    

    叶子节点的数量可以这样计算:

    n_leaves = np.zeros(n_trees, dtype=int)
    for i in range(n_trees):
        n_nodes = clf.estimators_[i].tree_.node_count
        # use left or right children as you want 
        children_left = clf.estimators_[i].tree_.children_left
        for x in range(n_nodes):
            if children_left[x] == -1:
                n_leaves[i] += 1
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2016-07-23
      • 2017-05-13
      • 2021-03-24
      • 2018-01-18
      • 2017-12-04
      • 2019-08-31
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多