1
2
3
4
5 """ Defines the class _DecTreeNode_, used to represent decision trees
6
7 _DecTreeNode_ is derived from _Tree.TreeNode_
8
9 """
10 from ML.DecTree import Tree
11
13 """ This is used to represent decision trees
14
15 _DecTreeNode_s are simultaneously the roots and branches of decision trees.
16 Everything is nice and recursive.
17
18 _DecTreeNode_s can save the following pieces of internal state, accessible via
19 standard setter/getter functions:
20
21 1) _Examples_: a list of examples which have been classified
22
23 2) _BadExamples_: a list of examples which have been misclassified
24
25 3) _TrainingExamples_: the list of examples used to train the tree
26
27 4) _TestExamples_: the list of examples used to test the tree
28
29 """
31 apply(Tree.TreeNode.__init__,(self,)+args,kwargs)
32 self.examples = []
33 self.badExamples = []
34 self.trainingExamples = []
35 self.testExamples = []
37 """ Recursively classify an example by running it through the tree
38
39 **Arguments**
40
41 - example: the example to be classified
42
43 - appendExamples: if this is nonzero then this node (and all children)
44 will store the example
45
46 **Returns**
47
48 the classification of _example_
49
50 **NOTE:**
51 In the interest of speed, I don't use accessor functions
52 here. So if you subclass DecTreeNode for your own trees, you'll
53 have to either include ClassifyExample or avoid changing the names
54 of the instance variables this needs.
55
56 """
57 if appendExamples:
58 self.examples.append(example)
59 if self.terminalNode:
60 return self.label
61 else:
62 val = example[self.label]
63 return self.children[val].ClassifyExample(example,appendExamples)
64
65 - def AddChild(self,name,label=None,data=None,isTerminal=0):
66 """ Constructs and adds a child with the specified data to our list
67
68 **Arguments**
69
70 - name: the name of the new node
71
72 - label: the label of the new node (should be an integer)
73
74 - data: the data to be stored in the new node
75
76 - isTerminal: a toggle to indicate whether or not the new node is
77 a terminal (leaf) node.
78
79 **Returns*
80
81 the _DecTreeNode_ which is constructed
82
83 """
84 child = DecTreeNode(self,name,label,data,level=self.level+1,isTerminal=isTerminal)
85 self.children.append(child)
86 return child
87
91 self.examples = examples
92
94 return self.badExamples
96 self.badExamples = examples
97
99 return self.trainingExamples
101 self.trainingExamples = examples
102
104 return self.testExamples
106 self.testExamples = examples
107
109 self.examples = []
110 self.badExamples = []
111 self.trainingExamples = []
112 self.testExamples = []
113 for child in self.GetChildren():
114 child.ClearExamples()
115