gpt4 book ai didi

python - 如何从 python3 中的 xgboost 模型中提取决策规则(特征拆分)?

转载 作者:太空狗 更新时间:2023-10-29 21:45:02 24 4
gpt4 key购买 nike

我需要从 python 中拟合的 xgboost 模型中提取决策规则。我使用 0.6a2 版本的 xgboost 库,我的 python 版本是 3.5.2。

我的最终目标是使用这些拆分来对变量进行分类(根据拆分)。

我没有发现这个版本的模型的任何属性可以给我 split 。

plot_tree 给我类似的东西。然而,它是树的可视化。

我需要像 https://stackoverflow.com/a/39772170/4559070 这样的东西对于 xgboost 模型

最佳答案

这是可能的,但并不容易。我建议您使用 scikit-learn 中的 GradientBoostingClassifier,它类似于 xgboost,但可以原生访问构建的树。

但是,使用 xgboost 可以获得模型的文本表示,然后对其进行解析:

from sklearn.datasets import load_iris
from xgboost import XGBClassifier
# build a very simple model
X, y = load_iris(return_X_y=True)
model = XGBClassifier(max_depth=2, n_estimators=2)
model.fit(X, y);
# dump it to a text file
model.get_booster().dump_model('xgb_model.txt', with_stats=True)
# read the contents of the file
with open('xgb_model.txt', 'r') as f:
txt_model = f.read()
print(txt_model)

它将为您打印 6 棵树的文本描述(2 个估计器,每个估计器由 3 棵树组成,每个类一个),其开头如下:

booster[0]:
0:[f2<2.45] yes=1,no=2,missing=1,gain=72.2968,cover=66.6667
1:leaf=0.143541,cover=22.2222
2:leaf=-0.0733496,cover=44.4444
booster[1]:
0:[f2<2.45] yes=1,no=2,missing=1,gain=18.0742,cover=66.6667
1:leaf=-0.0717703,cover=22.2222
2:[f3<1.75] yes=3,no=4,missing=3,gain=41.9078,cover=44.4444
3:leaf=0.124,cover=24
4:leaf=-0.0668394,cover=20.4444
...

例如,现在您可以从此描述中提取所有拆分:

import re
# trying to extract all patterns like "[f2<2.45]"
splits = re.findall('\[f([0-9]+)<([0-9]+.[0-9]+)\]', txt_model)
splits

它将为您打印元组列表(feature_id,split_value),例如

[('2', '2.45'),
('2', '2.45'),
('3', '1.75'),
('3', '1.65'),
('2', '4.95'),
('2', '2.45'),
('2', '2.45'),
('3', '1.75'),
('3', '1.65'),
('2', '4.95')]

您可以根据需要进一步处理此列表。

关于python - 如何从 python3 中的 xgboost 模型中提取决策规则(特征拆分)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com