def plotTree(myTree, parentpt, nodeTxt): numLeafs = ID3Tree.getNumLeafs(myTree) maxDepth = ID3Tree.getTreeDepth(myTree) firstr = myTree.keys()[0] cntrPt = (plotTree.xOff + (1.0 + float(numLeafs)) / 2.0 / plotTree.totalW, plotTree.yOff) # plot the text and the node plotMidText(cntrPt, parentpt, nodeTxt) plotNode(firstr, cntrPt, parentpt, decisionNode) secondDict = myTree[firstr] plotTree.yOff = plotTree.yOff - 1.0 / plotTree.totalD # plot the tree by Recursive for key in secondDict.keys(): if type(secondDict[key]).__name__ == "dict": plotTree(secondDict[key], cntrPt, str(key)) else: plotTree.xOff = plotTree.xOff + 1.0 / plotTree.totalW plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) plotTree.yOff = plotTree.yOff + 1.0 / plotTree.totalD
def plotTree(myTree, parentpt, nodeTxt): numLeafs = ID3Tree.getNumLeafs(myTree) maxDepth = ID3Tree.getTreeDepth(myTree) firstr = myTree.keys()[0] cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff) # plot the text and the node plotMidText(cntrPt, parentpt, nodeTxt) plotNode(firstr, cntrPt, parentpt, decisionNode) secondDict = myTree[firstr] plotTree.yOff = plotTree.yOff - 1.0 / plotTree.totalD # plot the tree by Recursive for key in secondDict.keys(): if type(secondDict[key]).__name__ == "dict": plotTree(secondDict[key], cntrPt, str(key)) else: plotTree.xOff = plotTree.xOff + 1.0 / plotTree.totalW plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode) plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key)) plotTree.yOff = plotTree.yOff + 1.0 / plotTree.totalD
def createPlot(tree): fig = plt.figure(1, facecolor='white') fig.clf() axprops = dict(xticks=[], yticks=[]) createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) plotTree.totalW = float(ID3Tree.getNumLeafs(tree)) plotTree.totalD = float(ID3Tree.getTreeDepth(tree)) # init plotTree.xOff = -0.5 / plotTree.totalW plotTree.yOff = 1.0 plotTree(tree, (0.5, 1.0), '') plt.show()
myTree = ID3Tree.createTree(DataSet, Labels) print "The final the ID3 Tree is ", myTree print "---------------------------------------\n" # test for the one example print "Labels is ..", Labels # !!!Notice:the Labels has been changed DataSet, Labels = ID3Tree.createDataSet() result = ID3Tree.classifyID3(myTree, Labels, [1, 1]) print "the classify result is ", result print "---------------------------------------\n" # Get the leaf Node LeafNodeNum = ID3Tree.getNumLeafs(myTree) print "This ID3 Tree leaf node num is ", LeafNodeNum print "---------------------------------------\n" # Get the depth of the ID3 MaxDepth = ID3Tree.getTreeDepth(myTree) print "This ID3 tree max depth is ", MaxDepth print "---------------------------------------\n" # Plot the tree TreePlot.createPlot(myTree) print "---------------------------------------\n"