【问题标题】:Graphviz decsion treeGraphviz 决策树
【发布时间】:2017-03-19 10:17:53
【问题描述】:

我想在我的数据集上可视化应用的决策树分类器,看看它是如何分支的。做了几次谷歌搜索,这个链接出现了。我对这些代码很好,直到这一行“f = tree.export_graphviz(clf, out_file=f)”。

from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
with open("iris.dot", 'w') as f:
...     f = tree.export_graphviz(clf, out_file=f)

我的问题是在这段代码之后我如何可视化树?根据链接“http://scikit-learn.org/stable/modules/tree.html”,我必须使用此代码“dot -Tpdf iris.dot -o iris.pdf”来创建 PDF 文件。我不明白我应该在哪里使用它?在 Graphviz 的点工具中?如果是,我会收到此错误“错误::'点'附近的第 1 行中的语法错误”

如果有人回答我的问题,我将不胜感激。谢谢。

【问题讨论】:

    标签: python tree graphviz


    【解决方案1】:

    dot -Tpdf iris.dot -o iris.pdf 是一个可以在 bash 中使用的命令。并且你应该已经安装了 Graphviz 工具。例如,你可以在 ubuntu 上安装它使用命令:sudo apt-get install graphviz

    根据链接“http://scikit-learn.org/stable/modules/tree.html”,如果我们安装了 Python 模块 pydotplus,我们可以直接在 Python 中生成 PDF 文件(或任何其他支持的文件类型):

    import pydotplus 
    dot_data = tree.export_graphviz(clf, out_file=None) 
    graph = pydotplus.graph_from_dot_data(dot_data) 
    graph.write_pdf("iris.pdf") 
    

    对于Shelly的评论,我添加以下代码,这是我的ipython笔记本上运行的完整代码。

    import pydotplus 
    from sklearn.datasets import load_iris
    from sklearn import tree
    iris = load_iris()
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(iris.data, iris.target)
    with open("iris.dot", 'w') as f:
        f = tree.export_graphviz(clf, out_file=f)
    
    dot_data = tree.export_graphviz(clf, out_file=None) 
    graph = pydotplus.graph_from_dot_data(dot_data) 
    graph.write_pdf("iris.pdf") 
    

    【讨论】:

    • 我已经安装了graphviz。问题在于 cmd 中的此代码“dot -Tpdf tree.dot -o tree.pdf”。我收到此错误错误:点:无法打开 tree.dot
    • 当我想通过 pydotplus 执行此操作时,在“dot_data = tree.export_graphviz(clf, out_file=None)”这一行时出现错误。错误如下: AttributeError: 'NoneType' object has no attribute 'write' 我真的不明白为什么会出现这个错误。
    • @Shelly 1."tree.dot" 应替换为正确的点文件路径。如果您使用 "dot -Tpdf tree.dot -o tree.pdf",请确保那里有一个 tree.dot 文件。 2.我在ipython notebook上运行官方文档的代码,没有问题。我已将完整的代码添加到我的答案中。
    • 我确实有 tree.dot 文件。问题是当我在cmd中使用这个命令“dot -Tpdf tree.dot -o tree.pdf”时,它给了我这个错误“'dot'附近的第1行的语法错误”,我真的不明白我该如何解决它或者我的问题在哪里?
    猜你喜欢
    • 2016-03-12
    • 2018-07-05
    • 2017-07-26
    • 2017-05-03
    • 2021-04-10
    • 2018-06-13
    • 2019-03-10
    • 2018-02-09
    • 2022-08-24
    相关资源
    最近更新 更多