source: orange/docs/reference/rst/code/treestructure.py @ 9372:aef193695ea9

Revision 9372:aef193695ea9, 1.9 KB checked in by mitar, 2 years ago (diff)

Moved documentation to the separate directory.

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")
10tree_classifier = Orange.classification.tree.TreeLearner(data)
11
12def tree_size(node):
13    if not node:
14        return 0
15
16    size = 1
17    if node.branch_selector:
18        for branch in node.branches:
19            size += tree_size(branch)
20
21    return size
22
23print "Tree size:", tree_size(tree_classifier.tree)
24
25
26def printTree0(node, level):
27    if not node:
28        print " "*level + "<null node>"
29        return
30
31    if node.branch_selector:
32        node_desc = node.branch_selector.class_var.name
33        node_cont = node.distribution
34        print "\n" + "   "*level + "%s (%s)" % (node_desc, node_cont),
35        for i in range(len(node.branches)):
36            print "\n" + "   "*level + ": %s" % node.branch_descriptions[i],
37            printTree0(node.branches[i], level+1)
38    else:
39        node_cont = node.distribution
40        major_class = node.node_classifier.default_value
41        print "--> %s (%s) " % (major_class, node_cont),
42
43def print_tree(x):
44    if isinstance(x, Orange.classification.tree.TreeClassifier):
45        print_tree0(x.tree, 0)
46    elif isinstance(x, Orange.classification.tree.Node):
47        print_tree0(x, 0)
48    else:
49        raise TypeError, "invalid parameter"
50
51print "\n\nUnpruned tree"
52print tree_classifier
53
54def cut_tree(node, level):
55    if node and node.branch_selector:
56        if level:
57            for branch in node.branches:
58                cut_tree(branch, level-1)
59        else:
60            node.branch_selector = None
61            node.branches = None
62            node.branch_descriptions = None
63
64print "\n\nPruned tree"
65cut_tree(tree_classifier.tree, 2)
66print tree_classifier
67
Note: See TracBrowser for help on using the repository browser.