graphviz未添加到系统环境解决
错误提示
最近在实验决策树的python代码时,想要可视化的查看生成的决策树,试验了如下的代码
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from graphviz import Source
from sklearn.tree import export_graphviz
import os
IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID)
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2, random_state=42)
tree_clf.fit(X, y)
from graphviz import Source
from sklearn.tree import export_graphviz
export_graphviz(
tree_clf,
out_file=os.path.join(IMAGES_PATH, "iris_tree.dot"),
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
Source.from_file(os.path.join(IMAGES_PATH, "iris_tree.dot"))
出现了一个奇怪的bug
ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH
解决方法
一开始以为是没有安装graphviz
模块,使用pip
命令后发现已经安装
网上搜索发现是还需要安装graphviz
程序,这里以ubuntu系统举例,直接使用apt
命令安装.
sudo apt install graphviz
之后重新运行代码,出现了决策树的可视化结果