O'Reilly logo

Programming Collective Intelligence by Toby Segaran

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Call this function with the tree you just built, and you'll get something like this:

>>>reload(treepredict)
>>> treepredict.printtree(tree)
0:google?
T-> 3:21?
  T-> {'Premium': 3}
  F-> 2:yes?
    T-> {'Basic': 1}
    F-> {'None': 1}
F-> 0:slashdot?
  T-> {'None': 3}
  F-> 2:yes?
    T-> {'Basic': 4}
    F-> 3:21?
      T-> {'Basic': 1}
      F-> {'None': 3}

This is a visual representation of the process that the decision tree will go through when trying to make a new classification. The condition on the root node is "is Google in column 0?" If this condition is met, it proceeds to the T-> branch and finds that anyone referred ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required