使用Scikit Learn在Python中为随机林绘制树

2024-09-27 22:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想绘制一个随机森林的决策树。所以,我创建了以下代码:

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

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

谢谢你


Tags: infromimport决策树treepng森林绘制
3条回答

可以绘制一棵树:

from sklearn.tree import export_graphviz
from IPython import display
from sklearn.ensemble import RandomForestRegressor

m = RandomForestRegressor(n_estimators=1, max_depth=3, bootstrap=False, n_jobs=-1)
m.fit(X_train, y_train)

str_tree = export_graphviz(m, 
   out_file=None, 
   feature_names=X_train.columns, # column names
   filled=True,        
   special_characters=True, 
   rotate=True, 
   precision=0.6)

display.display(str_tree)

你可以这样看每棵树

i_tree = 0
for tree_in_forest in FT_cls_gini.estimators_:
    if (i_tree ==3):        
        tree.export_graphviz(tree_in_forest, out_file=dotfile)
        graph = pydotplus.graph_from_dot_data(dotfile.getvalue())        
    i_tree = i_tree + 1
Image(graph.create_png())

假设你的随机森林模型已经拟合好了, 首先,您应该首先导入export_graphviz函数:

from sklearn.tree import export_graphviz

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

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

下一行生成一个png文件

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

相关问题 更多 >

    热门问题