如何从python3中的xgboost模型中提取决策规则(特征分割)?
我需要从python中安装的xgboost模型中提取决策规则。我使用0.6a2版本的xgboost库,python版本是3.5.2 我的最终目标是使用这些拆分来存储变量(根据拆分) 我没有遇到任何属性的模型,这个版本可以给我分裂如何从python3中的xgboost模型中提取决策规则(特征分割)?,python,xgboost,Python,Xgboost,我需要从python中安装的xgboost模型中提取决策规则。我使用0.6a2版本的xgboost库,python版本是3.5.2 我的最终目标是使用这些拆分来存储变量(根据拆分) 我没有遇到任何属性的模型,这个版本可以给我分裂 plot_tree给了我类似的东西。然而,这是树的可视化 我需要类似于xgboost模型的东西您需要知道树的名称,然后,您可以将其插入到代码中。这是可能的,但并不容易。我建议您使用scikit learn中的GradientBoostingClassifier,它类似于
plot_tree
给了我类似的东西。然而,这是树的可视化
我需要类似于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
...
您可以根据需要进一步处理此列表。您可以通过函数
模型找到作为数据帧的决策规则。\u Booster.trees\u to\u dataframe()
。
Yes
列包含Yes分支的ID
,以及No分支的No
列。通过这种方式可以重建树,因为对于数据帧的每一行,节点ID
都将边定向到Yes
和No
。您可以使用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)
可能需要使用
\[f([0-9]+)如何知道每个功能id实际代表什么?就像f2
实际代表什么一样?@JacquelineP.,功能id只是X矩阵中相应列的序号。
[('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')]
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)