-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecisionTree.py
More file actions
217 lines (140 loc) · 4.99 KB
/
DecisionTree.py
File metadata and controls
217 lines (140 loc) · 4.99 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
import pandas as pd
import numpy as np
#Filenames
Training_File = '/Users/Vishthefish73/Desktop/DecisionTreePy/optdigits_train.txt'
Valid_File = '/Users/Vishthefish73/Desktop/DecisionTreePy/optdigits_valid.txt'
Test_File = '/Users/Vishthefish73/Desktop/DecisionTreePy/optdigits_test.txt'
#Node used to construct tree
class Node:
def __init__(self):
feature = None
left = None
right = None
clas = None
#Function to read csv data line by line
def ReadData(trn_file,val_file,tst_file):
#lat column is y_pred values
df_trn = pd.read_csv(trn_file,header=None)
df_val = pd.read_csv(val_file,header=None)
df_tst = pd.read_csv(tst_file,header=None)
return [df_trn.iloc[:,0:-1],df_trn.iloc[:,-1], df_val.iloc[:,0:-1],df_val.iloc[:,-1], df_tst.iloc[:,0:-1],df_tst.iloc[:,-1], ]
#Calculate Node entropy
def NodeEntropy(y):
if(len(y) == 0):
return 0
unique, cnt = np.unique(y, return_counts=True)
n = len(unique)
sm = 0
for x in range(0,n):
if(cnt[x] > 0):
sm = sm + (-1 * ((cnt[x]/len(y))* np.log2(cnt[x]/len(y))));
return sm
#Calculates entropy by feature
def SplitEntropy(y0,y1):
l0 = len(y0)
l1 = len(y1)
if(l1+l0) == 0:
return float("inf")
N0 = NodeEntropy(y0)
N1 = NodeEntropy(y1)
return ( (l0/(l1+l0)) * N0) + ((l1/(l1+l0)) * N1)
#Return best feature to split on
def SplitAttribute(X,y):
minimum = float("inf")
rows, dim = X.shape
best = 0
for i in range(0,dim):
#print(i)
ind0 = X.index[X.iloc[:,i] == 0]
ind1 = X.index[X.iloc[:,i] == 1]
y0 = y[ind0].reset_index(drop=True)
y1 = y[ind1].reset_index(drop=True)
e = SplitEntropy(y0,y1)
if (e < minimum):
minimum = e
best = i
#print(minimum)
return best
#Generate a BiVvariate Decision Tree
def GenerateTree(X,y,theta,node):
if(NodeEntropy(y) < theta):
if(len(y) == 0):
print("error")
else:
node.clas = y.mode()[0]
return node
else:
i = SplitAttribute(X,y)
node.clas = -1
node.feature = i
ind0 = X.index[X.iloc[:,i] == 0]
ind1 = X.index[X.iloc[:,i] == 1]
X0 = X.iloc[ind0,:].reset_index(drop=True)
X1 = X.iloc[ind1,:].reset_index(drop=True)
y0 = y[ind0].reset_index(drop=True)
y1 = y[ind1].reset_index(drop=True)
node.left = (GenerateTree(X0,y0,theta,Node()))
node.right = (GenerateTree(X1,y1,theta,Node()))
return node
#Using generated tree, makes predictions
def Predict_with_Tree(root,X):
node = root
while(node.clas == -1):
atrib = node.feature
if (X.iloc[atrib] == 0):
node = node.left
else:
node = node.right
return node.clas
#main
def main():
#Read in Data
data = ReadData(Training_File,Valid_File,Test_File)
X_trn = data[0]
y_trn = data[1]
X_val = data[2]
y_val = data[3]
X_tst = data[4]
y_tst = data[5]
#Calculate number of rows per dataset
Trn_rows = X_trn.shape[0]
Val_rows = X_val.shape[0]
Tst_rows = X_tst.shape[0]
#Theta parameter for decision tree
thetas = [0.01,0.2,0.3,0.4,0.5,1.0,2.0]
val_errors = []
for theta in thetas:
#Generate a tree with current predictions on Training set
root = Node()
GenerateTree(X_trn,y_trn,theta,root)
error_rate = 0
for r in range(0,Trn_rows):
row_vector = X_trn.iloc[r,:]
y_pred = Predict_with_Tree(root,row_vector)
if(y_pred != y_trn.iloc[r]):
error_rate+=1
error_rate = error_rate / Trn_rows
print("The error on the training set for " + str(theta) + " is " + str(round(error_rate,6)))
#Predict labels on Validation set
error_rate = 0
for r in range(0,Val_rows):
row_vector = X_val.iloc[r,:]
y_pred = Predict_with_Tree(root,row_vector)
if(y_pred != y_val.iloc[r]):
error_rate+=1
error_rate = error_rate / Val_rows
val_errors.append(error_rate)
print("The error on the validation set for theta = " + str(theta) + " is " + str(round(error_rate,6)))
#Test set Prediction
BestTheta = thetas[np.argmin(val_errors)]
root = Node()
GenerateTree(X_trn,y_trn,BestTheta,root)
error_rate = 0
for r in range(0,Tst_rows):
row_vector = X_tst.iloc[r,:]
y_pred = Predict_with_Tree(root,row_vector)
if(y_pred != y_tst.iloc[r]):
error_rate+=1
error_rate = error_rate / Tst_rows
print("The error on the test set for " + str(BestTheta) + " is " + str(round(error_rate,6)))
main()