-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecisionTree.py
482 lines (245 loc) · 13.3 KB
/
DecisionTree.py
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import csv
import sys
import ast
from collections import Counter
import copy
import random
from math import log
#--------------------------------------------- Defined class for tree nodes ------------------------------------------------
class decisionnode:
def __init__(self, col = -1, value = None, results = None, tb = None, fb = None):
self.col = col
self.value = value
self.results = results
self.tb = tb
self.fb = fb
#------------------------------------------- function to calculate the variance impurity of data set ---------------------------
def varianceImpurity(rows):
if len(rows) == 0: return 0
result = countClass(rows)
total_samples = len(rows)
variance_impurity = (result['0'] * result['1']) / (total_samples ** 2)
return variance_impurity
#--------------------------------------------- function to calculate entropy of data set ----------------------------------------
def entropy(rows):
log_base_2 = lambda x: log(x) / log(2)
results = countClass(rows)
Entropy = 0.0
for r in results.keys():
p = float(results[r]) / len(rows)
Entropy = Entropy - p * log_base_2(p)
return Entropy
#--------- function used to split data set based on entropy(default) or variance impurity after calculating gain -------------
def generateTree(rows, heuristicToUse=entropy):
if len(rows) == 0: return decisionnode()
class_entropy = heuristicToUse(rows) # class column's entropy/InformtionGain
best_gain = 0.0
best_criteria = None
best_sets = None
column_count = len(rows[0]) - 1
for col in range(0, column_count):
global column_values
column_values = {}
for row in rows:
column_values[row[col]] = 1
for value in column_values.keys():
(set1, set2) = divideDataSet(rows, col, value)
p = float(len(set1)) / len(rows)
gain = class_entropy - p * heuristicToUse(set1) - (1 - p) * heuristicToUse(set2)
if gain > best_gain and len(set1) > 0 and len(set2) > 0:
best_gain = gain
best_criteria = (col, value)
best_sets = (set1, set2)
if best_gain > 0:
trueBranch = generateTree(best_sets[0])
falseBranch = generateTree(best_sets[1])
return decisionnode(col=best_criteria[0], value=best_criteria[1], tb=trueBranch, fb=falseBranch)
else:
return decisionnode(results = countClass(rows))
#--------------------------------------- function for splitting dataset based on an attribute --------------------------------------
def divideDataSet(rows, column, value):
split_data = None
split_data = lambda row: row[column] == value
set1 = []
set2 = []
for row in rows:
if split_data(row):
set1.append(row)
for row in rows:
if not split_data(row):
set2.append(row)
return (set1, set2)
#---------------------- count number of values based on class attribute (last column) and return a dictionary --------------------
def countClass(rows):
results = {}
for row in rows:
r = row[len(row) - 1]
if r not in results: results[r] = 0
results[r] += 1
return results
#-------------------------------------------------- print tree in required format -------------------------------------------
def displayTree(tree, header_data, indent):
if tree.results != None:
for key in tree.results:
print(str(key))
else:
print("")
print(indent + str(header_data[tree.col]) + ' = ' + str(tree.value) + ' : ', end="")
displayTree(tree.tb, header_data, indent + ' |')
print(indent + str(header_data[tree.col]) + ' = ' + str(int(tree.value) ^ 1) + ' : ', end="")
displayTree(tree.fb, header_data, indent + ' |')
#--------------------------------------------------- function to calculate the accuracy -----------------------------------
def calculateTreeAccuracy(rows, tree):
count_Of_correct_predictions = 0
for row in rows:
classified_value = classify(row, tree)
if row[-1] == classified_value:
count_Of_correct_predictions += 1
accuracy = 100 * count_Of_correct_predictions / len(rows)
return accuracy
#------------------------------------------ function to classify input data based on a learned tree ----------------------------
def classify(observation, tree):
if tree.results != None:
for key in tree.results:
predicted_value = key
return predicted_value
else:
v = observation[tree.col]
if v == tree.value:
branch = tree.tb
else:
branch = tree.fb
predicted_value = classify(observation, branch)
return predicted_value
#------------------------ function to count total number of non leaf nodes and label them according to number ------------------
def listNodes(nodes, tree, count):
if tree.results != None:
return nodes, count
count += 1
nodes[count] = tree
(nodes, count) = listNodes(nodes, tree.tb, count)
(nodes, count) = listNodes(nodes, tree.fb, count)
return nodes, count
#------------------------------------- function to count number of target class -------------------------------------
def countOfClass(tree, class_occurence):
if tree.results != None:
for key in tree.results:
class_occurence[key] += tree.results[key]
return class_occurence
left_branch_occurence = countOfClass(tree.fb, class_occurence)
right_branch_occurence = countOfClass(tree.tb, left_branch_occurence)
return right_branch_occurence
#--------------------------------------- replace subtree according to the pruning algorithm ----------------------------------
def findAndReplaceSubtree(tree_copy, subtree_to_replace, subtree_to_replace_with):
if (tree_copy.results != None):
return tree_copy
if (tree_copy == subtree_to_replace):
tree_copy = subtree_to_replace_with
return tree_copy
tree_copy.fb = findAndReplaceSubtree(tree_copy.fb, subtree_to_replace, subtree_to_replace_with)
tree_copy.tb = findAndReplaceSubtree(tree_copy.tb, subtree_to_replace, subtree_to_replace_with)
return tree_copy
#--------------------------------------------------- function to prune tree ---------------------------------------------
def pruneTree(tree, l, k, data):
tree_best = tree
best_accuracy = calculateTreeAccuracy(data, tree)
tree_copy = None
for i in range(1, l):
m = random.randint(1, k)
tree_copy = copy.deepcopy(tree)
for j in range(1, m):
(nodes, initial_count) = listNodes({}, tree_copy, 0)
if (initial_count > 0):
p = random.randint(1, initial_count)
subtree_p = nodes[p]
class_occurence = {'0': 0, '1': 0}
count = countOfClass(subtree_p, class_occurence)
if count['0'] > count['1']:
count['0'] = count['0'] + count['1']
count.pop('1')
subtree_p = decisionnode(results=count)
else:
count['1'] = count['0'] + count['1']
count.pop('0')
subtree_p = decisionnode(results=count)
tree_copy = findAndReplaceSubtree(tree_copy, nodes[p], subtree_p)
curr_accuracy = calculateTreeAccuracy(data, tree_copy)
if (curr_accuracy > best_accuracy):
best_accuracy = curr_accuracy
tree_best = tree_copy
return tree_best, best_accuracy
# ------------------------------------------------- Main function: Program starts here ---------------------------------------------
if __name__ == "__main__":
args = str(sys.argv)
args = ast.literal_eval(args)
# ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
if (len(args) < 6):
print ("Input arguments should be 6. Please refer the Readme file regarding input format.")
elif (args[3][-4:] != ".csv" or args[4][-4:] != ".csv" or args[5][-4:] != ".csv"):
print(args[2])
print ("Your training, validation and test file must be a .csv!")
else:
l = int(args[1])
k = int(args[2])
training_set = str(args[3])
validation_set = str(args[4])
test_set = str(args[5])
to_print = str(args[6])
with open(training_set, newline='', encoding='utf_8') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',', quotechar='|')
header_data = next(csvReader)
train_training_data = list(csvReader)
with open(validation_set, newline='', encoding='utf_8') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',', quotechar='|')
validation_training_data = list(csvReader)
with open(test_set, newline='', encoding='utf_8') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',', quotechar='|')
test_training_data = list(csvReader)
l_array = [60, 15, 20, 25, 30, 35, 40, 45, 50, 55]
k_array = [15, 20, 25, 30, 35, 40, 45, 50, 55, 60]
# ------------------------------ build tree using information gain heuristic -------------------------------------------
generated_tree_IG = generateTree(train_training_data, heuristicToUse=entropy)
print("Using Information Gain as a heuristic : \n")
if(to_print.lower() == "yes"):
print("\n Printing the learned tree : \n")
displayTree(generated_tree_IG, header_data, '')
train_accuracy = calculateTreeAccuracy(train_training_data, generated_tree_IG)
print(" Training data accuracy : ", train_accuracy)
validation_accuracy = calculateTreeAccuracy(validation_training_data, generated_tree_IG)
print("\n Validation data accuracy : ", validation_accuracy)
test_accuracy = calculateTreeAccuracy(test_training_data, generated_tree_IG)
print("\n Test data accuracy : ", test_accuracy)
(pruned_best_tree_validation, pruned_best_accuracy_validation) = pruneTree(generated_tree_IG, l, k,validation_training_data)
print("\n Validation data accuracy after pruning : ", pruned_best_accuracy_validation)
(pruned_best_tree_test, pruned_best_accuracy_test) = pruneTree(generated_tree_IG, l, k, test_training_data)
if (to_print.lower() == "yes"):
print("\n Printing the pruned tree using test data : ")
displayTree(pruned_best_tree_test, header_data, '')
print("\n Test data accuracy after pruning : ", pruned_best_accuracy_test)
print("\n Calculating accuracy of test data with 10 combinations of l and k :")
for l, k in zip(l_array, k_array):
(pruned_best_tree_test, pruned_best_accuracy_test) = pruneTree(generated_tree_IG, l, k,test_training_data)
print("\n Test data accuracy after pruning with l = ", l," and k = " , k," : ", pruned_best_accuracy_test)
# --------------------------------------- build tree using variance impurity heuristic --------------------------------
generated_tree_VI = generateTree(train_training_data, heuristicToUse = varianceImpurity)
print("\nUsing Variance Impurity as a heuristic :\n")
if (to_print.lower() == "yes"):
print("\n Printing the learned tree : ")
displayTree(generated_tree_VI, header_data, '')
train_accuracy_VI = calculateTreeAccuracy(train_training_data, generated_tree_VI)
print("\n Training data accuracy : ", train_accuracy_VI)
validation_accuracy_VI = calculateTreeAccuracy(validation_training_data, generated_tree_VI)
print("\n Validation data accuracy : ", validation_accuracy_VI)
test_accuracy_VI = calculateTreeAccuracy(test_training_data, generated_tree_VI)
print("\n Test data accuracy : ", test_accuracy_VI)
(pruned_best_tree_validation_VI, pruned_best_accuracy_validation_VI) = pruneTree(generated_tree_VI, l, k, validation_training_data)
print("\n Validation data accuracy after pruning: ", pruned_best_accuracy_validation_VI)
(pruned_best_tree_test_VI, pruned_best_accuracy_test_VI) = pruneTree(generated_tree_VI, l, k, test_training_data)
if (to_print.lower() == "yes"):
print("\n Printing the pruned tree using on test data : ")
displayTree(pruned_best_tree_test_VI, header_data, '')
print("\n Test data accuracy after pruning : ", pruned_best_accuracy_test_VI)
print("\n Calculating accuracies of test data with 10 combinations of l and k :")
for l, k in zip(l_array, k_array):
(pruned_best_tree_test_VI, pruned_best_accuracy_test_VI) = pruneTree(generated_tree_VI, l, k,test_training_data)
print("\n Test data accuracy after pruning with l = ", l, " and k = ", k ," : ", pruned_best_accuracy_test_VI)