-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestNeighbourClassifer.py
More file actions
376 lines (286 loc) · 10.3 KB
/
Copy pathNearestNeighbourClassifer.py
File metadata and controls
376 lines (286 loc) · 10.3 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
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
import numpy as np
import matplotlib.pyplot as plt
#from PIL import Image
from random import randint
import math
np.set_printoptions(threshold=np.nan)
trainingImage = []
trainingLabel = []
trainingImageGroups = []
trainingLabelGroups = []
fold = None
knn = None
bestModel = None
bestModelIndex = None
predictLabel = None
trainingAccuracy = None
trainingImage = None
trainingLabel = None
def NearestNeighbour(trainImage, trainLabel, computeGroup = False):
global trainingImage
global trainingLabel
global trainingImageGroups
global trainingLabelGroups
global fold
global knn
global bestModel
global bestModelIndex
global predictLabel
global trainingAccuracy
global trainingImage
global trainingLabel
global fold
trainingImage = []
trainingLabel = []
if(computeGroup):
trainingImageGroups = []
trainingLabelGroups = []
fold = 5
knn = [1, 3, 5, 7, 9]
bestModel = None
bestModelIndex = None
predictLabel = None
trainingAccuracy = None
trainingImage = trainImage
trainingLabel = trainLabel
if(computeGroup):
totalCount = len(trainLabel)
itemPerGroup = totalCount/float(fold)
k = 0
for i in range(fold):
tempImageGroup = []
tempLabelGroup = []
for j in range(int(itemPerGroup)):
tempImageGroup.append(trainImage[k])
tempLabelGroup.append(trainLabel[k])
k = k+1
trainingImageGroups.append(tempImageGroup)
trainingLabelGroups.append(tempLabelGroup)
#identify best model
def best_model(predtictionMatrix):
global knn
global bestModelIndex
global bestModel
global trainingAccuracy
knnCount = []
maxKnn = 0
maxIndx = 0
for i in range(len(knn)-1):
tempCount = 0
for j in range(len(predtictionMatrix)):
if(predtictionMatrix[j][i] == predtictionMatrix[j][-1]):
tempCount = tempCount+1
knnCount.append(tempCount)
for i in range(len(knnCount)):
if knnCount[i] >= maxKnn:
maxKnn = knnCount[i]
maxIndx = i
bestModelIndex = maxIndx
bestModel = knn[maxIndx]
trainingAccuracy = float(maxKnn*100)/len(predtictionMatrix)
return trainingAccuracy
#find max occurance of element in sortes list
def max_occurance(sortedLst):
tempElem = sortedLst[0][1]
maxElem = sortedLst[0][1]
maxCount = 1
tempCount = 1
for val in sortedLst[1:]:
if(val[1]==tempElem):
tempCount=tempCount+1
else:
if tempCount>=maxCount:
maxCount = tempCount
maxElem = tempElem
tempElem = val[1]
tempCount = 1
if tempCount>=maxCount:
maxCount = tempCount
maxElem = tempElem
return maxElem
#predict image on basis of best model
def predictTestDigit(testImage):
global predictDigit
global bestModelIndex
classifications = predictDigit(testImage)
return classifications[bestModelIndex]
#predic image for all models
def predictDigit(testImage):
global trainingLabel
global trainingImage
global knn
global max_occurance
nearestNeighbourClassification = []
eucledianMatrix = [[0 for x in range(2)] for y in range(len(trainingLabel))]
k = 0
for i in range(len(trainingLabel)):
tempDistance = 0
for j in range(28*28):
tempDistance = tempDistance+((int(trainingImage[i][j]) - int(testImage[j]))**2)
eucledianMatrix[k][0] = math.sqrt(tempDistance)
eucledianMatrix[k][1] = trainingLabel[i]
k = k+1
eucledianMatrix.sort()
for k in knn:
nearestNeighbourClassification.append(max_occurance(eucledianMatrix[:k]))
return nearestNeighbourClassification
#perform cross validation for each group
def performCrossValidation(trainingImage, trainingLabel):
#initialise class data
global trainingImageGroups
global trainingLabelGroups
global fold
NearestNeighbour(trainingImage, trainingLabel, True)
predictedKnnMatrix = []
for k in range(fold):
j = 0
trainingGroupImage = []
trainingGroupLabel = []
testGroupImage = []
testGroupLabel = []
for i in range(fold):
if(j!=i):
trainingGroupImage = trainingGroupImage+trainingImageGroups[i]
trainingGroupLabel = trainingGroupLabel+trainingLabelGroups[i]
else:
testGroupImage = testGroupImage+trainingImageGroups[i]
testGroupLabel = testGroupLabel+trainingLabelGroups[i]
j = j+1
#test for one fold
trainingGroupImage = np.array(trainingGroupImage)
trainingGroupLabel = np.array(trainingGroupLabel)
testGroupImage = np.array(testGroupImage)
testGroupLabel = np.array(testGroupLabel)
NearestNeighbour(trainingGroupImage, trainingGroupLabel)
for i in range(len(testGroupLabel)):
tempKnn = predictDigit(testGroupImage[i])
tempKnn.append(testGroupLabel[i])
predictedKnnMatrix.append(tempKnn)
return predictedKnnMatrix
#fetch all images from file
def fetchImage(fileName):
training_images_file = open(fileName,'rb')
training_images = training_images_file.read()
training_images_file.close()
training_images = bytearray(training_images)
training_images = training_images[16:]
image_array = np.array(training_images)
image_array = np.reshape(image_array, (-1, 28*28))
return image_array
#fetch all labels from file
def fetchLabel(fileName):
training_label_file = open(fileName,'rb')
training_label = training_label_file.read()
training_label_file.close()
training_label = bytearray(training_label)
training_label = training_label[8:]
label_array = np.array(training_label)
return label_array
#fetch required number of class
def fetchClass(trainingLabel, requiredCount, classVal):
listData = []
count = 0
while (count < requiredCount):
indx = randint(0, 60000-1)
if trainingLabel[indx] == classVal:
listData.append(indx)
count = count+1
return listData
def extractTrainingData(trainingImage, trainingLabel, indexList):
totalImages = len(indexList)
imageList = [[-1 for x in range(28*28)] for y in range(totalImages)]
labelList = [-1]*totalImages
for indx in indexList:
insertIndex = 0
while labelList[insertIndex] != -1:
insertIndex = randint(0, totalImages-1)
imageList[insertIndex] = trainingImage[indx]
labelList[insertIndex] = trainingLabel[indx]
imageList = np.array(imageList)
labelList = np.array(labelList)
return imageList, labelList
def accuracy(predtictionMatrix):
tempCount = 0
for j in range(len(predtictionMatrix)):
if(predtictionMatrix[j][0] == predtictionMatrix[j][1]):
tempCount = tempCount+1
predtictionMatrix[j].append(1)
else:
predtictionMatrix[j].append(0)
trainingAccuracy = float(tempCount*100)/len(predtictionMatrix)
return trainingAccuracy
def calculateConfusion(testKNN, classVal):
tp = 0
fp = 0
tn = 0
fn = 0
totalOccurance = 0
for i in range(len(testKNN)):
if (testKNN[i][1] == classVal):
if (testKNN[i][3] == False):
tp = tp +1
else:
fn = fn + 1
else:
if (testKNN[i][3] == False):
fp = fp + 1
else:
tn = tn+1
tpr = tp/float(tp+fn)
fpr = fp/float(fp+tn)
return tpr, fpr
trainingImageMaster = fetchImage('train-images.idx3-ubyte')
trainingLabelMaster = fetchLabel('train-labels.idx1-ubyte')
classOne = fetchClass(trainingLabelMaster, 200, 1)
classTwo = fetchClass(trainingLabelMaster, 200, 2)
classSeven = fetchClass(trainingLabelMaster, 200, 7)
applicableList = classOne+classTwo+classSeven
trainingImage, trainingLabel = extractTrainingData(trainingImageMaster, trainingLabelMaster, applicableList)
predictedKnnMatrix = performCrossValidation(trainingImage, trainingLabel)
NearestNeighbour(trainingImage, trainingLabel)
best_model(predictedKnnMatrix)
print "Best Model is:",bestModel,"-NN"
print "Accuracy while training is:", trainingAccuracy
testImage = []
testLabel = []
for i in range(50):
indx = randint(0, 199)
testImage.append(trainingImageMaster[classOne[indx]])
testLabel.append(trainingLabelMaster[classOne[indx]])
for i in range(50):
indx = randint(0, 199)
testImage.append(trainingImageMaster[classTwo[indx]])
testLabel.append(trainingLabelMaster[classTwo[indx]])
for i in range(50):
indx = randint(0, 199)
testImage.append(trainingImageMaster[classSeven[indx]])
testLabel.append(trainingLabelMaster[classSeven[indx]])
predictedKnnMatrix = []
for i in range(len(testLabel)):
tempKnn = []
tempKnn.append(predictTestDigit(testImage[i]))
tempKnn.append(testLabel[i])
tempKnn.append(i)
predictedKnnMatrix.append(tempKnn)
#predictedKnnMatrix contain [predicted, correct, index, correct/incorrect]
print "Accuracy while testing is:", accuracy(predictedKnnMatrix)
objects = ('1 TPR', '1 FPR', '2 TPR', '2 FPR', '7 TPR', '7 FPR')
y_pos = np.arange(len(objects))
truePositiveRate, falsePositiveRate = calculateConfusion(predictedKnnMatrix, 1)
print "TP for Class 1:", truePositiveRate
print "FP for Class 1:", falsePositiveRate
performance = [truePositiveRate, falsePositiveRate]
truePositiveRate, falsePositiveRate = calculateConfusion(predictedKnnMatrix, 2)
print "TP for Class 2:", truePositiveRate
print "FP for Class 2:", falsePositiveRate
performance.append(truePositiveRate)
performance.append(falsePositiveRate)
truePositiveRate, falsePositiveRate = calculateConfusion(predictedKnnMatrix, 7)
print "TP for Class 7:", truePositiveRate
print "FP for Class 7:", falsePositiveRate
performance.append(truePositiveRate)
performance.append(falsePositiveRate)
plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Value in Percentage')
plt.title('FP/FN on basis of class')