pythonjupyter-notebookgraphviz

How to draw a Graphviz graph in Jupyter Notebook?


Hello I'm now learning machine learning for class.

I want to visualize the tree with graphviz by jupyter notebook.

These are the errors that I have below:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
c:\users\asuspc\appdata\local\programs\python\python36-32\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key)
     60         try:
---> 61             return self[key]
     62         except KeyError:

KeyError: 'dot'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-17-341e4ee6fe08> in <module>()
      4 from sklearn.tree import export_graphviz
      5 from sklearn.datasets import load_iris
----> 6 dot_data = tree.export_graphviz(clf, out_file=iris.dot)
      7 graph = graphviz.Source(dot_data)
      8 graph.render("iris")

c:\users\asuspc\appdata\local\programs\python\python36-32\lib\site-packages\sklearn\utils\__init__.py in __getattr__(self, key)
     61             return self[key]
     62         except KeyError:
---> 63             raise AttributeError(key)
     64 
     65     def __setstate__(self, state):

AttributeError: dot

And these are the code now I'm working on:

import graphviz
import pydotplus
from sklearn import tree
from sklearn.tree import export_graphviz
from sklearn.datasets import load_iris
dot_data = tree.export_graphviz(clf, out_file=iris.dot) 
graph = graphviz.Source(dot_data) 
graph.render("iris") 

Already installed the prerequisites for jupyter notebook.

I don't know why and how to solve the keyError or Attribute Errors.

How can I solve this?


Solution

  • Assuming clf is a decision tree
    export_graphviz(clf,
                    feature_names=X.columns,
                    filled=True,
                    rounded=True)
    
    next step install graph viz windows and make sure dot.exe is in path so that ####you can access it from windows cmd.
    os.system('dot -Tpng tree.dot -o tree.png')
    

    Above should save your dot file as png