环境
- 不管用哪种可视化的模型,都需要配置graphviz图形驱动用来对结果进行展示,其他的安装包如下所示:
import pydotplus
from sklearn import tree
from IPython.display import Image
二叉树可视化代码
import os
from sklearn import tree
from sklearn.datasets import load_iris
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(train_x, train_y)
import pydotplus
from IPython.display import Image
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=df_all.columns.tolist()[:-1],
class_names=['0','1','2'],
filled=True, rounded=True, special_characters=False)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.set('label', 'Tree 30 from Xgboost Tree')
graph.set('labelloc', 't')
nodes = graph.get_node_list()
for index, node in enumerate(nodes):
if node.get_name().startswith('node'):
node.set('style', 'filled')
Image(graph.create_png())
graph.write_png('decision_tree.png')
xgboost可视化代码
def model_plot_trees(clf, features, **n):
"""绘制树模型"""
with open('xgb.fmap', 'w', encoding="utf-8") as fmap:
for k, ft in enumerate(features):
fmap.write(''.join(str([k, ft, 'p']) + '\n'))
c_node_params = {'shape': 'box',
'style': 'filled,rounded',
'fillcolor': '#78bceb'
}
l_node_params = {'shape': 'box',
'style': 'filled',
'fillcolor': '#e48038'
}
digraph = xgb.to_graphviz(clf, num_trees=30, condition_node_params=c_node_params,
leaf_node_params=l_node_params, fmap='xgb.fmap')
digraph.view('./oil_xgb_trees')
for i in range(n.get('n')):
xgb.plot_tree(clf, num_trees=i, condition_node_params=c_node_params,
leaf_node_params=l_node_params, fmap='xgb.fmap')
plt.show()
model_plot_trees(xgb_model, df_all.columns.tolist()[:-1])