Not Fitted Error when using Sklearn's graphviz

Viewed 19628

when I am trying to export a random forest graph using the following command:

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

I receive the following error:

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

What I don't understand is why it keeps telling me this, even though I have fitted the random forest classifier using:

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

rnd_clf.fit(X_train, y_train)

and it works perfectly fine.

3 Answers
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())
Related