Python决策树可视化,并显示中文

2018-12-26  本文已影响0人  熊定坤

生成可视化决策树代码

from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
clf.fit(X,y)
import pydotplus
from IPython.display import Image
import sklearn.tree as tree
dot= tree.export_graphviz(clf_hh,out_file=None,feature_names=X.columns,
                             class_names=['0','1','2'],
                             max_depth=2,filled=True,rounded=True,special_characters=True)
graph= pydotplus.graph_from_dot_data(dot)
Image(graph.create_png())

错误解决方式

  1. 下载安装GraphViz(这是一个独立软件)
    https://graphviz.gitlab.io/_pages/Download/Download_windows.html
  2. 将GraphViz安装目录的bin目录放到环境变量的path路径中


  3. 安装pydotplus
    cmd下pip install pydotplus
  4. 如果还不行手动添加bin路径
    语句如下
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'  #注意修改你的路径
显示中文
from sklearn import tree
from sklearn.externals.six import StringIO
import graphviz
dot_data = StringIO()
tree.export_graphviz(dt, out_file=dot_data,  #dt 决策树模型 #out_file=dot_data必填
                                         feature_names=score.columns[:-1], 
                                         class_names=['top25','top25-50','top50-75','top75-100'],  
                                         filled=True, rounded=True,  # doctest: +SKIP
                                         special_characters=True)

graph = graphviz.Source(dot_data.getvalue())
graph
graph.render("dx_fig01") #生成PDF文件
上一篇下一篇

猜你喜欢

热点阅读