xgboost自帶的特征重要性排名以及可視化: plot_importance
import xgboost
from xgboost import XGBClassifier
from sklearn.datasets import load_iris
iris = load_iris()
x, y = iris.data, iris.target
model = XGBClassifier()
model.fit(x, y)
# 如果輸入是沒有表頭的array,會(huì)自動(dòng)以f1,f2開始,需要更換表頭
# 畫樹結(jié)構(gòu)圖的時(shí)候也需要替換表頭
model.get_booster().feature_names = iris.feature_names
# max_num_features指定排名最靠前的多少特征
# height=0.2指定柱狀圖每個(gè)柱子的粗細(xì),默認(rèn)是0.2
# importance_type='weight'默認(rèn)是用特征子樹中的出現(xiàn)次數(shù)(被選擇次數(shù)),還有"gain"和"cover"
xgboost.plot_importance(model, max_num_features=5)
# f_score就是feature score

plot_importance中的表頭,實(shí)際上是調(diào)用的booster的get_score()的接口
model.get_booster().get_score()
# {'f2': 136, 'f3': 146, 'f0': 106, 'f1': 90}
修改表頭
model.get_booster().feature_names = iris.feature_names
model.get_booster().get_score()
# {'petal length (cm)': 136,
# 'petal width (cm)': 146,
# 'sepal length (cm)': 106,
# 'sepal width (cm)': 90}
ubuntu系統(tǒng)下xgboost畫出樹結(jié)構(gòu): to_graphviz
需要下載graphviz
pip install graphviz
sudo apt-get install graphviz # ubuntu系統(tǒng)也需要安裝graphviz
xgboost.to_graphviz(model, num_trees=2) # 索引第2棵樹

修改圖形參數(shù),設(shè)置leaf_node_params為不用文本框的純文本
xgboost.to_graphviz(model, num_trees=1, leaf_node_params={'shape': 'plaintext'})

使用dump_model導(dǎo)出迭代工程,配合to_graphviz解釋
model.get_booster().dump_model("model.txt")
第一個(gè)樹的分割邏輯
booster[0]:
0:[petal length (cm)<2.45000005] yes=1,no=2,missing=1
1:leaf=0.430622011
2:leaf=-0.220048919
leaf_value轉(zhuǎn)化為預(yù)測(cè)概率
leaf_value實(shí)際上是這個(gè)節(jié)點(diǎn)的交叉熵值: 1 / (1 + np.exp(-x))
以第2棵樹為例, 第二層的葉子節(jié)點(diǎn)
左節(jié)點(diǎn)預(yù)測(cè)概率1 / (1 + np.exp(0.2198)) = 0.445,
右節(jié)點(diǎn)的預(yù)測(cè)概率1 / (1 + np.exp(-0.217)) = 0.554
0.445 + 0.554 = 1
windows系統(tǒng)下xgboost畫出樹結(jié)構(gòu): to_graphviz
pip install graphviz
pip install pydot
下載windows下graphviz的zip文件
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
代碼中增加環(huán)境變量
import os
os.environ["path"] += os.pathsep + "E:\pge\pip_package\release\bin"
scr = xgboost.to_graphviz(model, num_trees=2)
# src.format = "jpg"
src.view("influence_factor/tree") # 圖片保存到位置
graphviz不能顯示中文的解決方案
打開tree文件,在第二行 graph [ rankdir = TB ] 下面加入
node [fontname="FangSong"]
使用dot命令重新生成圖片
dot Tjpg tree -o tree.jpg