Sckit learn with GraphViz exports empty outputs

冷暖自知 提交于 2019-12-11 06:05:33

问题


I would like to export decision tree using sklearn.

First I trained a decision tree classifier:

self._selected_classifier = tree.DecisionTreeClassifier()
self._selected_classifier.fit(train_dataframe, train_class)

self._column_names = list(train_dataframe.columns.values)

After that I used the following method in order to export the decision tree:

def _create_graph_visualization(self):
    decision_tree_classifier = self._selected_classifier 

    from sklearn.externals.six import StringIO
    dot_data = StringIO()
    tree.export_graphviz(decision_tree_classifier,
                         out_file=dot_data,
                         feature_names=self._column_names)
    import pydotplus
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    graph.write_pdf("decision_tree_output.pdf")

After many errors regarding missing executables now the program is finished successfully. The file is created, but it is empty. What am I doing wrong?


回答1:


Here is an example with output which works for me, using 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")
graph.write_pdf("dtree.pdf")


来源:https://stackoverflow.com/questions/39810242/sckit-learn-with-graphviz-exports-empty-outputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!