使用Sklearn的graphviz时出现错误

F. *_* K. 15 scikit-learn

当我尝试使用以下命令导出随机森林图时:

tree.export_graphviz(rnd_clf, out_file = None, feature_names = X_test[::1])
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

NotFittedError: This RandomForestClassifier instance is not fitted yet. 
Call 'fit' with appropriate arguments before using this method.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它一直告诉我这个,即使我已经使用以下方法拟合随机森林分类器:

rnd_clf = RandomForestClassifier(  
             n_estimators=120,
             criterion='gini',
             max_features= None, 
             max_depth = 14 )

rnd_clf.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)

它完美无缺.

sas*_*cha 27

(仅限于文档;没有个人经验)

您正尝试使用签名读取的函数绘制一些DecisionTree:

sklearn.tree.export_graphviz(decision_tree, ...)
Run Code Online (Sandbox Code Playgroud)

但是你正在传递一个RandomForest,这是一个集合.

那不行!

更深入,内部代码在这里:

check_is_fitted(decision_tree, 'tree_')
Run Code Online (Sandbox Code Playgroud)

所以这就是要求tree_DecisionTree 的属性,它存在于DecisionTreeClassifier中.

RandomForestClassifier不存在此属性!因此错误.

您唯一能做的就是:在RandomForest集合中打印每个DecisionTree.为此,您需要遍历random_forest.estimators_以获取基础决策树!


jss*_*367 6

就像其他答案说的那样,您不能对仅一棵树的森林执行此操作。但是,您可以绘制该森林中的一棵树的图。这样做的方法如下:

forest_clf = RandomForestClassifier()
forest_clf.fit(X_train, y_train)
tree.export_graphviz(forest_clf.estimators_[0], out_file='tree_from_forest.dot')
(graph,) = pydot.graph_from_dot_file('tree_from_forest.dot')
graph.write_png('tree_from_forest.png')
Run Code Online (Sandbox Code Playgroud)

不幸的是,没有一种简单的方法可以绘制出森林中“最佳”树或整体树的图形,而只是随机的示例树。