使用Sklearn' graphviz

时间:2017-09-13 08:01:15

标签: scikit-learn

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

tree.export_graphviz(rnd_clf, out_file = None, feature_names = X_test[::1])

我收到以下错误:

NotFittedError: This RandomForestClassifier instance is not fitted yet. 
Call 'fit' with appropriate arguments before using this method.

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

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

rnd_clf.fit(X_train, y_train)

它完美无缺。

3 个答案:

答案 0 :(得分:24)

(仅通过文档;没有个人经验)

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

sklearn.tree.export_graphviz(decision_tree, ...)

但您传递的是 RandomForest ,这是一个树木集合

那不行!

更深入,内部代码为here

check_is_fitted(decision_tree, 'tree_')

因此,这要求您的DecisionTree属性tree_,该属性存在DecisionTreeClassifier

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

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

答案 1 :(得分: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')

不幸的是,没有简单的方法来绘制森林中的“最佳”树或整体集合树,只是一个随机的示例树。

答案 2 :(得分:1)

enter code herefrom IPython.display import Image
from sklearn.`enter code here`externals.six import StringIO
from sklear`enter code here`n.tree import export_graphviz
import pydotplus
import pydot`enter code here`

    dt = DecisionTreeClassifier(criterion = 'entropy', max_depth = 3, min_samples_split = 20, class_weight = "balanced")
    dtree = dt.fit(ctg_x_train,ctg_y_train)
    
        k
    
    dot_data = StringIO()
    ctg_x_train_names = ctg_x_train.columns
    import matplotlib.pyplot as plt
    fig = plt.figure(figsize = (12,12))
    
    export_graphviz(dtree, out_file=dot_data,filled = True, rounded = True,special_characters = True, feature_names = ctg_x_train_names)
    
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    
    (graph,) = pydot.graph_from_dot_data(dot_data.getvalue())
    Image(graph.create_png())
相关问题