python Graphviz不会在PyCharm上显示图片

qmelpv7a  于 2023-11-16  发布在  Python
关注(0)|答案(1)|浏览(170)

我正在使用sklearn构建决策树模型。
我认为模型工作得很好,但我不知道为什么它不像matplotlib的show()函数那样自动显示图片。这与设置有关吗?下面是代码:

import pandas as pd
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
import graphviz

data = pd.read_excel('file location')

target_vars = ['variable1','variable2','variable3']
X = pd.DataFrame()
for i in target_vars:
    X[i]=data[i]

y = data['outcome']

X_tn, X_te, y_tn, y_te = train_test_split(X, y, random_state=0)

regr = tree.DecisionTreeClassifier(criterion='entropy', max_depth=5)

regr.fit(X_tn,y_tn)

y_pred = regr.predict(X_te)
accuracy = (y_pred==y_te).mean()

print('Model Accuracy: ', accuracy)

export_graphviz(regr, out_file='tree.dot', class_names=['1','0'],
                feature_names=target_vars, impurity = True, filled = True)

with open('tree.dot') as f:
    dot_graph = f.read()
graphviz.Source(dot_graph)

字符串

dgenwo3n

dgenwo3n1#

首先,你应该使用命令行在你的设备上安装Graphviz,而不仅仅是在PyCharm中。
sudo apt-get install graphviz
然后你可以像这样查看dot文件:

file = Source.from_file(filename='file name with locatiuon')
file.view(filename=name, directory=location)

字符串

相关问题