从 LightGBM 模型访问树和节点

Tit*_*llo 6 decision-tree nodes random-forest lightgbm

在 sci-kit learn 中,可以访问整个树结构,即树的每个节点。这允许探索在树的每个分裂中使用的属性以及用于测试的值

The binary tree structure has 5 nodes and has the following tree structure:
node=0 test node: go to node 1 if X[:, 3] <= 0.800000011920929 else to node 2.
    node=1 leaf node.
    node=2 test node: go to node 3 if X[:, 2] <= 4.950000047683716 else to node 4.
            node=3 leaf node.
            node=4 leaf node.

Rules used to predict sample 0:
decision id node 0 : (X_test[0, 3] (= 2.4) > 0.800000011920929)
decision id node 2 : (X_test[0, 2] (= 5.1) > 4.950000047683716)
Run Code Online (Sandbox Code Playgroud)

对于随机森林,您可以通过遍历所有决策树来获得相同的信息

for tree in model.estimators_:
    # extract info from tree
Run Code Online (Sandbox Code Playgroud)

可以从 LightGBM 模型中提取相同的信息吗?也就是说,您可以访问:a) 每棵树和 b) 树的每个节点吗?

Joe*_*ard 7

是的,这是可能的

model._Booster.dump_model()["tree_info"]
Run Code Online (Sandbox Code Playgroud)

例如,它被用在lightgbm.plot_tree(). 我必须承认,我自己没有使用过它,也不知道返回结构的详细信息。


小智 5

model.booster_.trees_to_dataframe()返回一个 pandas DataFrame,每棵树每个拆分一行,其中包含拆分特征、拆分值、增益和记录计数等信息。

请参阅此处的文档: https: //lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html#lightgbm.Booster.trees_to_dataframe


小智 1

LightGBM与XGBoost的功能几乎相同;有时我什至会去XGBoost文档寻找LightGBM的功能。您可以在XGBoost中搜索它是如何完成的,也可以直接参考: https: //github.com/Microsoft/LightGBM/issues/845

另外,LightGBM 有一个 sklearn 包装器,可能可以按照您共享的方式在您训练的模型上使用 sklearn 结构。您可能想看看: https://lightgbm.readthedocs.io/en/latest/_modules/lightgbm/sklearn.html

希望能帮到您,如果没有解决,请尽管写信;我会更深入地讨论细节。