提问者:小点点

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


我需要从python中安装的xgboost模型中提取决策规则。我使用0.6a2版本的xgboost库,我的python版本是3.5。2.

我的最终目标是使用这些拆分来存储变量(根据拆分)。

我没有遇到任何属性的模型,这个版本可以给我分裂。

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

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


共3个答案

匿名用户

这是可能的,但不容易。我建议您使用GRadientBoosting分类器,它类似于xgboop,但具有对构建的树的本地访问权限。

但是,使用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')]

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

匿名用户

您可以通过函数模型找到决策规则作为数据帧。_Booster.trees_to_dataframe()Yes列包含yes分支的ID和no分支的No列。通过这种方式,您可以重建树,因为对于数据帧的每一行,节点ID都将边指向YesNo。你可以用networkx这样做:

import networkx as nx

df = model._Booster.trees_to_dataframe()

# Create graph
G = nx.Graph()
# Add all the nodes
G.add_nodes_from(df.ID.tolist())
# Add the edges. This should be simpler in Pandas, but there seems to be a bug with df.apply(tuple, axis=1) at the moment.
yes_pairs = df[['ID', 'Yes']].dropna()
no_pairs = df[['ID', 'No']].dropna()
yes_edges = [tuple([i[0], i[1]]) for i in yes_pairs.values]
no_edges = [tuple([i[0], i[1]]) for i in no_pairs.values]
G.add_edges_from(yes_edges + no_edges)

匿名用户

您需要知道您的树的名称,然后,您可以将它插入到您的代码中。