graphvizrandom-forestpydot

Not able to print Random Forest Regressor tree


I looked at several examples and followed them but not able to print tree graphs.

R_forest = RandomForestRegressor(bootstrap=False,
  max_depth=30,
  max_features ='sqrt',
  min_samples_leaf= 4,
  min_samples_split=2,
  n_estimators = 600)
model=R_forest.fit(X_train,y_train)

from sklearn.datasets import *
from sklearn import tree
from sklearn.tree import export_graphviz
import graphviz
import pydot


tree = R_forest.estimators_[5]
# Export the image to a dot file
export_graphviz(tree, out_file = 'tree.dot', feature_names = X_train.columns, 
rounded = True, precision = 1)
# Use dot file to create a graph
(graph, ) = pydot.graph_from_dot_file('tree.dot')
# Write graph to a png file
graph.write_png('tree.png')

I get this error:

FileNotFoundError: [WinError 2] "dot.exe" not found in path.

I followed this solution but still getting same error.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

Screenshot of my system.

Environment Variables

Any help or advise appreciated


Solution

  • If you are able to generate the "tree.dot" file, then you can run the following from the command line (in the directory with "tree.dot") to convert to a png :

    dot -Tpng tree.dot -o tree.png

    If this doesn't work, you can also try using the full path to dot.exe:

    path\to\dot.exe -Tpng tree.dot -o tree.png

    Running from Python using graph.write_png('tree.png') doesn't work on my Windows machine, but the command line operation does.

    Solution from another StackOverflow answer.