-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuildAndTestDecisionTree.java
More file actions
323 lines (294 loc) · 9.38 KB
/
BuildAndTestDecisionTree.java
File metadata and controls
323 lines (294 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class BuildAndTestDecisionTree
{
// "Main" reads in the names of the files we want to use, then reads
// in their examples.
public static void main(String[] args)
{
if (args.length != 2)
{
System.err.println("You must call BuildAndTestDecisionTree as " +
"follows:\n\njava BuildAndTestDecisionTree " +
"<trainsetFilename> <testsetFilename>\n");
System.exit(1);
}
// Read in the file names.
String trainset = args[0];
String testset = args[1];
// Read in the examples from the files.
ListOfExamples trainExamples = new ListOfExamples();
ListOfExamples testExamples = new ListOfExamples();
if (!trainExamples.ReadInExamplesFromFile(trainset) ||
!testExamples.ReadInExamplesFromFile(testset))
{
System.err.println("Something went wrong reading the datasets ... " +
"giving up.");
System.exit(1);
}
else
{
Tree root = buildTree(trainExamples);
System.out.println("The Decision Tree is : ");
printTree(root, 0);
ListOfExamples report = new ListOfExamples(testExamples);
testTree(root, testExamples, report);
System.out.println();
printResult(report, testExamples);
// trainExamples.DescribeDataset();
// testExamples.DescribeDataset();
// trainExamples.PrintThisExample(0); // Print out an example
//trainExamples.PrintAllExamples(); // Don't waste paper printing all
// of this out!
//testExamples.PrintAllExamples(); // Instead, just view it on the screen
}
Utilities.waitHere("Hit <enter> when ready to exit.");
}
private static Tree buildTree(ListOfExamples examples) {
if(examples.size() == 0) {
return new Leaf("");
}
String leafValue = isLeaf(examples);
if(leafValue.length() != 0) {
Tree newNode = new Leaf(leafValue);
return newNode;
}
ArrayList<Integer> validFeature = getAttributes(examples);
double remainder = 10000.0;
ListOfExamples[] subList = null;
String featureName = null;
int featureIndex = 0;
for(int i = 0; i<validFeature.size(); i++) {
int index = validFeature.get(i);
ListOfExamples[] newList = classify(examples, index);
int[] distribution1 = getDistribution(newList[0]);
int[] distribution2 = getDistribution(newList[1]);
double entropy1 = getEntropy(distribution1[0], distribution1[1]);
double entropy2 = getEntropy(distribution2[0], distribution2[1]);
double curr = getRemainder(newList[0].size(), newList[1].size(),
entropy1,entropy2);
if(curr < remainder) {
remainder = curr;
subList = newList;
featureName = examples.getFeatureName(index);
featureIndex = index;
}
}
String leftValue = subList[0].get(0).get(featureIndex);
String rightValue = subList[1].get(0).get(featureIndex);
Tree newNode = new TreeNode(featureName, featureIndex, leftValue, rightValue);
Tree left = buildTree(subList[0]);
Tree right = buildTree(subList[1]);
if(left instanceof Leaf && ((Leaf) left).label.length() == 0) {
setParentValue(examples, (Leaf)left);
}
if(right instanceof Leaf && ((Leaf) right).label.length() == 0) {
setParentValue(examples, (Leaf) right);
}
((TreeNode)newNode).left = left;
((TreeNode)newNode).right = right;
return newNode;
}
private static void printTree(Tree root, int depth) {
if(root == null || depth == 5) {
return;
}
if(root instanceof Leaf) {
System.out.println(((Leaf)root).label);
return;
}
TreeNode curr = (TreeNode) root;
for(int i = 0; i<depth; i++) {
System.out.print("**");
}
System.out.print(curr.feature + " " + curr.leftValue + ": ");
if(curr.left instanceof Leaf) {
System.out.println(((Leaf)curr.left).label);
}
else {
System.out.println();
int nextDepth = depth + 1;
printTree(curr.left, nextDepth);
}
for(int i = 0; i<depth; i++) {
System.out.print("**");
}
System.out.print(curr.feature + " " + curr.rightValue + ": ");
if(curr.right instanceof Leaf) {
System.out.println(((Leaf)curr.right).label);
}
else {
System.out.println();
int nextDepth = depth + 1;
printTree(curr.right, nextDepth);
}
}
private static void testTree(Tree root, ListOfExamples testSet, ListOfExamples report) {
for(int i = 0; i < testSet.size(); i++) {
Example curr = testSet.get(i);
Example result = testOneExample(root, curr);
if(result != null) {
report.add(result);
}
}
}
private static Example testOneExample(Tree root, Example curr) {
if(root instanceof Leaf) {
Leaf leaf = (Leaf) root;
if(leaf.label.equals(curr.getLabel())) {
return null;
}
else {
return curr;
}
}
TreeNode node = (TreeNode) root;
int index = node.index;
if(curr.get(index).equals(node.leftValue)) {
return testOneExample(node.left, curr);
}
else {
return testOneExample(node.right,curr);
}
}
private static void printResult(ListOfExamples report, ListOfExamples test) {
double accuracy = 1 - (report.size() * 1.0f)/test.size();
System.out.println("The accuracy for the testset is " +
new DecimalFormat("##.###").format(accuracy));
System.out.println("Incorrect predict examples are ");
for(Example tmp : report) {
System.out.println(tmp.getName());
}
}
private static ArrayList<Integer> getAttributes(ListOfExamples examples) {
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < examples.getNumberOfFeatures(); i++) {
boolean valid = false;
String value = examples.get(0).get(i);
for(int j =1; j<examples.size(); j++) {
String currValue = examples.get(j).get(i);
if(!currValue.equals(value)){
valid = true;
break;
}
}
if(valid) {
list.add(i);
}
}
return list;
}
private static double getRemainder(int numValue1, int numValue2, double Entropy1, double Entropy2) {
double percent1 = (numValue1 *1.0f) / (numValue1 + numValue2);
double percent2 = 1 - percent1;
double result = percent1 * Entropy1 + percent2 * Entropy2;
return result;
}
private static double getEntropy(int num1, int num2) {
if(num1 == 0 || num2 == 0) {
return 0;
}
double percent1 = (num1 *1.0f )/ (num1 + num2);
double percent2 = 1.0 - percent1;
double result = -(percent1 * Math.log(percent1)/Math.log(2)) - (percent2 * Math.log(percent2) / Math.log(2));
return result;
}
private static ListOfExamples[] classify(ListOfExamples examples, int index) {
ListOfExamples[] result = new ListOfExamples[2];
result[0] = new ListOfExamples(examples);
result[1] = new ListOfExamples(examples);
String value1 = (examples.getFeatureList())[index].getFirstValue();
for(int i = 0; i < examples.size(); i++) {
Example curr = examples.get(i);
if(curr.get(index).equals(value1)) {
result[0].add(curr);
}
else{
result[1].add(curr);
}
}
return result;
}
private static int[] getDistribution(ListOfExamples examples) {
int[] count = new int[2];
String value1 = examples.getLabelInfo().getFirstValue();
for(int i = 0; i < examples.size(); i++) {
if(examples.get(i).getLabel().equals(value1)) {
count[0] ++;
}
else {
count[1] ++;
}
}
return count;
}
private static String isLeaf(ListOfExamples ex) {
if(getAttributes(ex).size() == 0) {
String label_1 = ex.getLabelInfo().getFirstValue();
String label_2 = ex.getLabelInfo().getSecondValue();
int count_1 = 0, count_2 = 0;
for(int i = 0; i<ex.size(); i++) {
if(label_1.equals(ex.get(i).getLabel())) {
count_1 ++;
}
else {
count_2 ++;
}
}
return (count_1 > count_2) ? label_1 : label_2;
}
String str = "";
String label = ex.get(0).getLabel();
for(int i = 0; i<ex.size(); i++) {
if(!label.equals(ex.get(i).getLabel())) {
return str;
}
}
return ex.get(0).getLabel();
}
private static void setParentValue(ListOfExamples ex, Leaf leaf) {
int[] distri = getDistribution(ex);
int greater = (distri[0] > distri[1]) ? 0 : 1;
String majority;
if(greater == 0) {
majority = ex.getLabelInfo().getFirstValue();
}
else {
majority = ex.getLabelInfo().getSecondValue();
}
((Leaf) leaf).label = majority;
}
}
/**
* Represents a single binary feature with two String values.
*/
class BinaryFeature {
private String name;
private String firstValue;
private String secondValue;
public BinaryFeature(String name, String first, String second) {
this.name = name;
firstValue = first;
secondValue = second;
}
public String getName() {
return name;
}
public String getFirstValue() {
return firstValue;
}
public String getSecondValue() {
return secondValue;
}
}
class Utilities
{
// This method can be used to wait until you're ready to proceed.
public static void waitHere(String msg)
{
System.out.print("\n" + msg);
try { System.in.read(); }
catch(Exception e) {} // Ignore any errors while reading.
}
}