【问题标题】:Convert decision tree directly to png [duplicate]将决策树直接转换为png [重复]
【发布时间】:2017-02-11 01:11:13
【问题描述】:

我正在尝试生成一个我想使用点来可视化的决策树。生成的点文件应转换为 png。

虽然我可以使用类似的东西在 dos 中完成最后一个转换步骤

export_graphviz(dectree, out_file="graph.dot")

后跟一个 DOS 命令

dot -Tps graph.dot -o outfile.ps

直接在python中做所有这些都不起作用并产生错误

AttributeError: 'list' object has no attribute 'write_png'

这是我试过的程序代码:

from sklearn import tree  
import pydot
import StringIO

# Define training and target set for the classifier
train = [[1,2,3],[2,5,1],[2,1,7]]
target = [10,20,30]

# Initialize Classifier. Random values are initialized with always the same random seed of value 0 
# (allows reproducible results)
dectree = tree.DecisionTreeClassifier(random_state=0)
dectree.fit(train, target)

# Test classifier with other, unknown feature vector
test = [2,2,3]
predicted = dectree.predict(test)

dotfile = StringIO.StringIO()
tree.export_graphviz(dectree, out_file=dotfile)
graph=pydot.graph_from_dot_data(dotfile.getvalue())
graph.write_png("dtree.png")

我错过了什么?

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    我最终使用了 pydotplus:

    from sklearn import tree  
    import pydotplus
    import StringIO
    
    # Define training and target set for the classifier
    train = [[1,2,3],[2,5,1],[2,1,7]]
    target = [10,20,30]
    
    # Initialize Classifier. Random values are initialized with always the same random seed of value 0 
    # (allows reproducible results)
    dectree = tree.DecisionTreeClassifier(random_state=0)
    dectree.fit(train, target)
    
    # Test classifier with other, unknown feature vector
    test = [2,2,3]
    predicted = dectree.predict(test)
    
    dotfile = StringIO.StringIO()
    tree.export_graphviz(dectree, out_file=dotfile)
    graph=pydotplus.graph_from_dot_data(dotfile.getvalue())
    graph.write_png("dtree.png")
    

    编辑:感谢您的评论,要让它在 pydot 中运行,我必须写:

    (graph,)=pydot.graph_from_dot_data(dotfile.getvalue())
    

    【讨论】:

    • 我只能用pip install pydotplus 安装,不能用conda install pydotplus 安装导致InvalidArchiveError('Error with archive C:\\Users\\Admin\\Anaconda3\\pkgs\\openssl-1.1.1d-he774522_2xysboxfd\\pkg-openssl-1.1.1d-he774522_2.tar.zst. You probably need to delete and re-download or re-create this file. Message from libarchive was:\n\nCould not unlink')
    猜你喜欢
    • 2015-10-22
    • 2023-03-19
    • 2021-11-05
    • 2013-05-01
    • 2014-03-12
    • 1970-01-01
    • 2021-05-19
    • 2017-12-30
    • 2012-07-21
    相关资源
    最近更新 更多