是否可以在 scikit-learn 中打印决策树? [英] Is it possible to print the decision tree in scikit-learn?

查看:55
本文介绍了是否可以在 scikit-learn 中打印决策树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 scikit-learn 中打印经过训练的决策树?我想为我的论文训练一个决策树,我想把树的图片放在论文中.这可能吗?

解决方案

有一种导出为 graph_viz 格式的方法:http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html

来自在线文档:

<预><代码>>>>从 sklearn.datasets 导入 load_iris>>>从 sklearn 导入树>>>>>>clf = tree.DecisionTreeClassifier()>>>虹膜 = load_iris()>>>>>>clf = clf.fit(iris.data, iris.target)>>>tree.export_graphviz(clf,... out_file='tree.dot')

然后你可以使用graph viz加载它,或者如果你安装了pydot,那么你可以更直接地做到这一点:http://scikit-learn.org/stable/modules/tree.html

<预><代码>>>>从 sklearn.externals.six 导入 StringIO>>>导入pydot>>>dot_data = StringIO()>>>tree.export_graphviz(clf,out_file=dot_data)>>>图 = pydot.graph_from_dot_data(dot_data.getvalue())>>>graph.write_pdf("iris.pdf")

将生成一个 svg,无法在此处显示,因此您必须点击链接:http://scikit-learn.org/stable/_images/iris.svg

更新

自从我第一次回答这个问题以来,行为似乎发生了变化,现在它返回一个 list,因此你得到这个错误:

AttributeError: 'list' 对象没有属性 'write_pdf'

首先,当您看到此内容时,只需打印对象并检查对象即可,很可能您想要的是第一个对象:

graph[0].write_pdf("iris.pdf")

感谢@NickBraunagel 的评论

Is there a way to print a trained decision tree in scikit-learn? I want to train a decision tree for my thesis and I want to put the picture of the tree in the thesis. Is that possible?

解决方案

There is a method to export to graph_viz format: http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html

So from the online docs:

>>> from sklearn.datasets import load_iris
>>> from sklearn import tree
>>>
>>> clf = tree.DecisionTreeClassifier()
>>> iris = load_iris()
>>>
>>> clf = clf.fit(iris.data, iris.target)
>>> tree.export_graphviz(clf,
...     out_file='tree.dot')    

Then you can load this using graph viz, or if you have pydot installed then you can do this more directly: http://scikit-learn.org/stable/modules/tree.html

>>> from sklearn.externals.six import StringIO  
>>> import pydot 
>>> dot_data = StringIO() 
>>> tree.export_graphviz(clf, out_file=dot_data) 
>>> graph = pydot.graph_from_dot_data(dot_data.getvalue()) 
>>> graph.write_pdf("iris.pdf") 

Will produce an svg, can't display it here so you'll have to follow the link: http://scikit-learn.org/stable/_images/iris.svg

Update

It seems that there has been a change in the behaviour since I first answered this question and it now returns a list and hence you get this error:

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

Firstly when you see this it's worth just printing the object and inspecting the object, and most likely what you want is the first object:

graph[0].write_pdf("iris.pdf")

Thanks to @NickBraunagel for the comment

这篇关于是否可以在 scikit-learn 中打印决策树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆