graphviz.backend.ExecutableNotFound: failed to execute
['dot', '-Tpdf', '-O', 'Source.gv'], make sure the Graphviz executables
are on your systems' PATH
链接1
链接2
即可解决问题
测试代码
import graphviz
import numpy as np
from sklearn.tree import export_graphviz, DecisionTreeClassifier
# 定义加载数据的函数
def loaddata():
dataSet = [[0, 0, 0, 0, 'no'],
[0, 0, 0, 1, 'no'],
[0, 1, 0, 1, 'yes'],
[0, 1, 1, 0, 'yes'],
[0, 0, 0, 0, 'no'],
[1, 0, 0, 0, 'no'],
[1, 0, 0, 1, 'no'],
[1, 1, 1, 1, 'yes'],
[1, 0, 1, 2, 'yes'],
[1, 0, 1, 2, 'yes'],
[2, 0, 1, 2, 'yes'],
[2, 0, 1, 1, 'yes'],
[2, 1, 0, 1, 'yes'],
[2, 1, 0, 2, 'yes'],
[2, 0, 0, 0, 'no']]
feature_name = ['age', 'job', 'house', 'credit']
return dataSet, feature_name
if __name__ == '__main__':
myData, feature_name = loaddata()
# 取特征值与目标值
X = np.array(myData)[:, 0:4]
y = np.array(myData)[:, -1]
# 训练模型
model = DecisionTreeClassifier()
model.fit(X, y)
# 预测分类
print(model.predict([[1, 1, 0, 1], [1, 1, 1, 0]]))
# 生成tree.dot文件,字典格式
export_graphviz(
model,
out_file="tree.dot",
feature_names=feature_name,
class_names=['yes', 'no'],
rounded=True,
filled=True
)
# 生成pdf
with open("tree.dot") as f:
dot_grapth = f.read()
dot = graphviz.Source(dot_grapth)
dot.view()