Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

7. Modeling with Decision Trees > Displaying the Tree

Displaying the Tree

So now that you have a tree, what should you do with it? Well, one thing you’ll definitely want to do is look at it. printtree is a simple function for displaying the tree in plain text. The output isn’t pretty, but it’s a simple way to view small trees:

def printtree(tree,indent=''):
   # Is this a leaf node?
   if tree.results!=None:
      print str(tree.results)
   else:
      # Print the criteria
      print str(tree.col)+':'+str(tree.value)+'? '

      # Print the branches
      print indent+'T->',
      printtree(tree.tb,indent+'  ')
      print indent+'F->',
      printtree(tree.fb,indent+'  ')

This is another recursive function. It takes a tree returned by buildtree and traverses down it, and it knows it has reached the end of a branch when it reaches the node with results. Until it reaches that point, it prints the criteria for the True and False branches and calls printtree on each of them, each time increasing the indent string.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint