本文介绍了使用Scikit-Learn在Python中为随机森林绘制树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个随机森林的决策树.因此,我创建以下代码:

I want to plot a decision tree of a random forest. So, i create the following code:

clf = RandomForestClassifier(n_estimators=100)
import pydotplus
import six
from sklearn import tree
dotfile = six.StringIO()
i_tree = 0
for tree_in_forest in clf.estimators_:
if (i_tree <1):
    tree.export_graphviz(tree_in_forest, out_file=dotfile)
    pydotplus.graph_from_dot_data(dotfile.getvalue()).write_png('dtree'+ str(i_tree) +'.png')
    i_tree = i_tree + 1

但是它不会产生任何东西.您知道如何从随机森林绘制决策树吗?

But it doesn't generate anything..Have you an idea how to plot a decision tree from random forest ?

谢谢

推荐答案

假设您已经安装了随机森林模型,首先,您应该首先导入export_graphviz函数:

Assuming your Random Forest model is already fitted,first you should first import the export_graphviz function:

from sklearn.tree import export_graphviz

在for循环中,您可以执行以下操作来生成dot文件

In your for cycle you could do the following to generate the dot file

export_graphviz(tree_in_forest,
                feature_names=X.columns,
                filled=True,
                rounded=True)

下一行生成一个png文件

The next line generates a png file

os.system('dot -Tpng tree.dot -o tree.png')

这篇关于使用Scikit-Learn在Python中为随机森林绘制树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 03:06