【问题标题】:How to get access of individual trees of a xgboost model in python /R如何在 python / R 中访问 xgboost 模型的单个树
【发布时间】:2016-10-07 05:53:57
【问题描述】:

如何在 python/R 中访问 xgboost 模型的单个树?

下面我来自sklearn的随机森林树。

estimator = RandomForestRegressor(
    oob_score=True, 
    n_estimators=10, 
    max_features='auto'
) 
estimator.fit(tarning_data,traning_target) 
tree1 = estimator.estimators_[0]
leftChild = tree1.tree_.children_left  
rightChild = tree1.tree_.children_right 

【问题讨论】:

  • 我也想要一个答案,因为它是置信区间所必需的。我知道一旦你训练了提升模型bst,只需调用 bst.predict(data, pred_leaf=True) 输出将是(n_samples, n_estimators) 的矩阵,每条记录表示每棵树中每个样本的预测叶索引,但不知道如何恢复每棵树的实际预测。
  • 你们搞清楚了吗?

标签: python r machine-learning scikit-learn xgboost


【解决方案1】:

您要检查树木吗?

在 Python 中,您可以将树转储为字符串列表:

m = xgb.XGBClassifier(max_depth=2, n_estimators=3).fit(X, y)
m.get_booster().get_dump()

>

['0:[sincelastrun<23.2917] yes=1,no=2,missing=2\n\t1:[sincelastrun<18.0417] yes=3,no=4,missing=4\n\t\t3:leaf=-0.0965415\n\t\t4:leaf=-0.0679503\n\t2:[sincelastrun<695.025] yes=5,no=6,missing=6\n\t\t5:leaf=-0.0992546\n\t\t6:leaf=-0.0984374\n',
 '0:[sincelastrun<23.2917] yes=1,no=2,missing=2\n\t1:[sincelastrun<16.8917] yes=3,no=4,missing=4\n\t\t3:leaf=-0.0928132\n\t\t4:leaf=-0.0676056\n\t2:[sincelastrun<695.025] yes=5,no=6,missing=6\n\t\t5:leaf=-0.0945284\n\t\t6:leaf=-0.0937463\n',
 '0:[sincelastrun<23.2917] yes=1,no=2,missing=2\n\t1:[sincelastrun<18.175] yes=3,no=4,missing=4\n\t\t3:leaf=-0.0878571\n\t\t4:leaf=-0.0610089\n\t2:[sincelastrun<695.025] yes=5,no=6,missing=6\n\t\t5:leaf=-0.0904395\n\t\t6:leaf=-0.0896808\n']

或者将它们转储到一个文件中(格式很好):

m.get_booster().dump_model("out.txt")

>

booster[0]:
0:[sincelastrun<23.2917] yes=1,no=2,missing=2
    1:[sincelastrun<18.0417] yes=3,no=4,missing=4
        3:leaf=-0.0965415
        4:leaf=-0.0679503
    2:[sincelastrun<695.025] yes=5,no=6,missing=6
        5:leaf=-0.0992546
        6:leaf=-0.0984374
booster[1]:
0:[sincelastrun<23.2917] yes=1,no=2,missing=2
    1:[sincelastrun<16.8917] yes=3,no=4,missing=4
        3:leaf=-0.0928132
        4:leaf=-0.0676056
    2:[sincelastrun<695.025] yes=5,no=6,missing=6
        5:leaf=-0.0945284
        6:leaf=-0.0937463
booster[2]:
0:[sincelastrun<23.2917] yes=1,no=2,missing=2
    1:[sincelastrun<18.175] yes=3,no=4,missing=4
        3:leaf=-0.0878571
        4:leaf=-0.0610089
    2:[sincelastrun<695.025] yes=5,no=6,missing=6
        5:leaf=-0.0904395
        6:leaf=-0.0896808

【讨论】:

  • 又如何分别使用每棵树进行分类和评估每棵树?
  • 一个更容易阅读的东西是model.get_booster().trees_to_dataframe(),它将这个字符串输出到pandas DataFrame中。
  • 为什么要使用单个树?树是按顺序生长的,同时减少了模型的整体误差。它们从来没有像在随机森林中那样单独使用。
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 2019-03-03
  • 2016-07-18
  • 2017-01-27
  • 2019-08-07
  • 1970-01-01
  • 2018-03-26
  • 2016-09-20
相关资源
最近更新 更多