Graphviz 在 PyCharm 上不显示图片

发布于 2025-01-14 16:49:02 字数 938 浏览 5 评论 0原文

我正在使用 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)

I am building a decision tree model using sklearn.

I think the model works just fine, but I have no idea why it is not showing the picture automatically, as matplotlib's show() function would. Does this have something to do with the setting? below is the code:

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红ご颜醉 2025-01-21 16:49:02

首先,您应该使用命令行在设备上安装 Graphviz,而不仅仅是在 PyCharm 中。

sudo apt-get install graphviz

然后你可以像这样查看点文件:

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

first of all you should install Graphviz on your device using command line not just in PyCharm.

sudo apt-get install graphviz

Then you can view the dot file like this:

file = Source.from_file(filename='file name with locatiuon')
file.view(filename=name, directory=location)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文