source: orange/Orange/doc/reference/treestructure.py @ 9671:a7b056375472

Revision 9671:a7b056375472, 1.8 KB checked in by anze <anze.staric@…>, 2 years ago (diff)

Moved orange to Orange (part 2)

Line 
1# Description: Shows the structure that represents decision trees in Orange
2# Category:    learning, decision trees, classification
3# Classes:     TreeLearner, TreeClassifire, TreeNode,
4# Uses:        lenses
5# Referenced:  TreeLearner.htm
6
7import orange
8
9data = orange.ExampleTable("lenses")
10treeClassifier = orange.TreeLearner(data)
11
12def treeSize(node):
13    if not node:
14        return 0
15
16    size = 1
17    if node.branchSelector:
18        for branch in node.branches:
19            size += treeSize(branch)
20
21    return size
22
23print "Tree size:", treeSize(treeClassifier.tree)
24
25
26def printTree0(node, level):
27    if not node:
28        print " "*level + "<null node>"
29        return
30
31    if node.branchSelector:
32        nodeDesc = node.branchSelector.classVar.name
33        nodeCont = node.distribution
34        print "\n" + "   "*level + "%s (%s)" % (nodeDesc, nodeCont),
35        for i in range(len(node.branches)):
36            print "\n" + "   "*level + ": %s" % node.branchDescriptions[i],
37            printTree0(node.branches[i], level+1)
38    else:
39        nodeCont = node.distribution
40        majorClass = node.nodeClassifier.defaultValue
41        print "--> %s (%s) " % (majorClass, nodeCont),
42
43def printTree(x):
44    if type(x) == orange.TreeClassifier:
45        printTree0(x.tree, 0)
46    elif type(x) == orange.TreeNode:
47        printTree0(x, 0)
48    else:
49        raise TypeError, "invalid parameter"
50
51print "\n\nUnpruned tree"
52printTree(treeClassifier)
53
54def cutTree(node, level):
55    if node and node.branchSelector:
56        if level:
57            for branch in node.branches:
58                cutTree(branch, level-1)
59        else:
60            node.branchSelector = None
61            node.branches = None
62            node.branchDescriptions = None
63
64print "\n\nPruned tree"
65cutTree(treeClassifier.tree, 2)
66printTree(treeClassifier)
67
Note: See TracBrowser for help on using the repository browser.