决策树模型,XGBoost,LightGBM和CatBoost模型可视化
安装 graphviz
- 参考文档 http://graphviz.readthedocs.io/en/stable/manual.html#installation
- graphviz安装包下载地址 https://www.graphviz.org/download/
- 将graphviz的安装位置添加到系统环境变量
- 使用
pip install graphviz
安装graphviz python包 - 使用
pip install pydotplus
安装pydotplus python包
决策树模型可视化
以iris
数据为例。训练一个分类决策树,调用export_graphviz
函数导出DOT格式的文件。并用pydotplus包绘制图片。
# 在环境变量中加入安装的Graphviz路径
import os
os.environ["PATH"] += os.pathsep + 'E:/Program Files (x86)/Graphviz2.38/bin'
from sklearn import tree
from sklearn.datasets import load_iris
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
import pydotplus
from IPython.display import Image
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True, special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
XGBoost模型可视化
参考文档 https://xgboost.readthedocs.io/en/latest/python/python_api.html
xgboost中,对应的可视化函数是xgboost.to_graphviz
。以iris
数据为例,训练一个xgb分类模型并可视化
# 在环境变量中加入安装的Graphviz路径
import os
os.environ["PATH"] += os.pathsep + 'E:/Program Files (x86)/Graphviz2.38/bin'
import xgboost as xgb
from sklearn.datasets import load_iris
iris = load_iris()
xgb_clf = xgb.XGBClassifier()
xgb_clf.fit(iris.data, iris.target)
xgb.to_graphviz(xgb_clf, num_trees=1)
也可以通过Digraph对象可以将保存文件并查看
digraph = xgb.to_graphviz(xgb_clf, num_trees=1)
digraph.format = 'png'
digraph.view('./iris_xgb')
xgboost中提供了另一个api plot_tree
,使用matplotlib可视化树模型。效果上没有graphviz清楚。
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 10))
ax = fig.subplots()
xgb.plot_tree(xgb_clf, num_trees=1, ax=ax)
plt.show()
LightGBM模型可视化
参考文档 https://lightgbm.readthedocs.io/en/latest/Python-API.html#plotting
lgb中,对应的可视化函数是lightgbm.create_tree_digraph
。以iris
数据为例,训练一个lgb分类模型并可视化
# 在环境变量中加入安装的Graphviz路径
import os
os.environ["PATH"] += os.pathsep + 'E:/Program Files (x86)/Graphviz2.38/bin'
from sklearn.datasets import load_iris
import lightgbm