解决failed to execute WindowsPath(‘dot‘), make sure the Graphviz executables are on your systems‘ PATH

import graphviz

jupyter中运行graphviz出现failed to execute WindowsPath(‘dot’), make sure the Graphviz executables are on your systems’ PATH的问题

首先大家习惯先去pip install graphviz去安装,

但之后还是报这个错,网上各种说但是graphviz是个软件,不能单独用Pip安装,我尝试后均以失败告终,最后在我经过各种尝试后,最后终于发现一个极其简单的解决方案:

解决方案:
顺序:
第1步:我先安装pip install graphviz后,发现还是报错
第2步:之后又pip install pygraphviz,然后就好了。
下面是成功的截图

from sklearn.tree import DecisionTreeRegressor
# 建立模型
model_DT = DecisionTreeRegressor(criterion='squared_error',splitter='best',
    max_depth=3,
    min_samples_split=2,
    min_samples_leaf=1)

# 训练模型
model_DT.fit(train_X,train_y)

绘制决策树
```bash
import graphviz
#载入模块
from sklearn import tree
dot_data= tree.export_graphviz(model_DT,
                              filled=True,#填充颜色,颜色越深,不纯度越低
                              rounded=True#框的形状
                              )
graph=graphviz.Source(dot_data)
graph

解决failed to execute WindowsPath(‘dot‘), make sure the Graphviz executables are on your systems‘ PATH_第1张图片
另外还有第二种方法更简单的方法画决策树,
pip install pydotplus 安装pydotplus这个简单不易出错
代码如下:

# 法二 保存决策树
from pydotplus.graphviz import graph_from_dot_data

from sklearn.tree import export_graphviz

dot_data = export_graphviz( # Create dot data

model_DT, filled=True, rounded=True,
out_file=None

)

graph = graph_from_dot_data(dot_data) # Create graph from dot data

graph.write_png('D:/决策树.png') # Write graphto PNG image

不知道为啥保存的图有黑色方框,如下所示:
解决failed to execute WindowsPath(‘dot‘), make sure the Graphviz executables are on your systems‘ PATH_第2张图片
经过网上各种尝试,增加一行代码dot_data=dot_data.replace(‘\n’,‘’),就正常了
添加的代码如下所示:

# 法二 保存决策树
from pydotplus.graphviz import graph_from_dot_data

from sklearn.tree import export_graphviz

dot_data = export_graphviz( # Create dot data

model_DT, filled=True, rounded=True,
out_file=None

)
dot_data=dot_data.replace('\n','')
graph = graph_from_dot_data(dot_data) # Create graph from dot data

graph.write_png('D:/决策树.png') # Write graphto PNG image

解决failed to execute WindowsPath(‘dot‘), make sure the Graphviz executables are on your systems‘ PATH_第3张图片

你可能感兴趣的:(python,jupyter,python,深度学习)