source: orange/orange/doc/Orange/rst/code/treestructure.py @ 7713:d27afc892c9c

Revision 7713:d27afc892c9c, 1.8 KB checked in by markotoplak, 3 years ago (diff)

Tree documentation update.

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.data.Table("lenses")
10treeClassifier = Orange.classification.tree.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 isinstance(x, Orange.classification.tree.TreeClassifier):
45        printTree0(x.tree, 0)
46    elif isinstance(x, Orange.classification.tree.Node):
47        printTree0(x, 0)
48    else:
49        raise TypeError, "invalid parameter"
50
51print "\n\nUnpruned tree"
52print treeClassifier.dump()
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)
66print treeClassifier.dump()
67
Note: See TracBrowser for help on using the repository browser.