-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathknnWithKFCV.py
408 lines (292 loc) · 10.3 KB
/
knnWithKFCV.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
#!/usr/bin/env python
# coding: utf-8
# ## Classification using kNN
# **Import the required libraries**
# In[1]:
import numpy as np
import pandas as pd
import operator
from random import randrange
from sklearn import preprocessing
import warnings
warnings.filterwarnings('ignore')
# **The following cell contains a class of methods to calculate distance between two points using various techniques**
# **Formula to calculate Eucledian distance:**
#
# <math>\begin{align}D(x, y) = \sqrt{ \sum_i (x_i - y_i) ^ 2 }\end{align}</math>
# **Formula to calculate Manhattan Distance:**
#
# <math>\begin{align}D(x, y) = \sum_i |x_i - y_i|\end{align}</math>
# **Formula to calculate Hamming Distance:**
#
# <math>\begin{align}D(x, y) = \frac{1}{N} \sum_i \delta_{x_i, y_i}\end{align}</math>
# In[2]:
class distanceMetrics:
'''
Description:
This class contains methods to calculate various distance metrics
'''
def __init__(self):
'''
Description:
Initialization/Constructor function
'''
pass
def euclideanDistance(self, vector1, vector2):
'''
Description:
Function to calculate Euclidean Distance
Inputs:
vector1, vector2: input vectors for which the distance is to be calculated
Output:
Calculated euclidean distance of two vectors
'''
self.vectorA, self.vectorB = vector1, vector2
if len(self.vectorA) != len(self.vectorB):
raise ValueError("Undefined for sequences of unequal length.")
distance = 0.0
for i in range(len(self.vectorA)-1):
distance += (self.vectorA[i] - self.vectorB[i])**2
return (distance)**0.5
def manhattanDistance(self, vector1, vector2):
"""
Desription:
Takes 2 vectors a, b and returns the manhattan distance
Inputs:
vector1, vector2: two vectors for which the distance is to be calculated
Output:
Manhattan Distance of two input vectors
"""
self.vectorA, self.vectorB = vector1, vector2
if len(self.vectorA) != len(self.vectorB):
raise ValueError("Undefined for sequences of unequal length.")
return np.abs(np.array(self.vectorA) - np.array(self.vectorB)).sum()
def hammingDistance(self, vector1, vector2):
"""
Desription:
Takes 2 vectors a, b and returns the hamming distance
Hamming distance is meant for discrete-valued vectors, though it is a
valid metric for real-valued vectors.
Inputs:
vector1, vector2: two vectors for which the distance is to be calculated
Output:
Hamming Distance of two input vectors
"""
self.vectorA, self.vectorB = vector1, vector2
if len(self.vectorA) != len(self.vectorB):
raise ValueError("Undefined for sequences of unequal length.")
return sum(el1 != el2 for el1, el2 in zip(self.vectorA, self.vectorB))
# In[3]:
class kNNClassifier:
'''
Description:
This class contains the functions to calculate distances
'''
def __init__(self,k = 3, distanceMetric = 'euclidean'):
'''
Description:
KNearestNeighbors constructor
Input
k: total of neighbors. Defaulted to 3
distanceMetric: type of distance metric to be used. Defaulted to euclidean distance.
'''
pass
def fit(self, xTrain, yTrain):
'''
Description:
Train kNN model with x data
Input:
xTrain: training data with coordinates
yTrain: labels of training data set
Output:
None
'''
assert len(xTrain) == len(yTrain)
self.trainData = xTrain
self.trainLabels = yTrain
def getNeighbors(self, testRow):
'''
Description:
Train kNN model with x data
Input:
testRow: testing data with coordinates
Output:
k-nearest neighbors to the test data
'''
calcDM = distanceMetrics()
distances = []
for i, trainRow in enumerate(self.trainData):
if self.distanceMetric == 'euclidean':
distances.append([trainRow, calcDM.euclideanDistance(testRow, trainRow), self.trainLabels[i]])
elif self.distanceMetric == 'manhattan':
distances.append([trainRow, calcDM.manhattanDistance(testRow, trainRow), self.trainLabels[i]])
elif self.distanceMetric == 'hamming':
distances.append([trainRow, calcDM.hammingDistance(testRow, trainRow), self.trainLabels[i]])
distances.sort(key=operator.itemgetter(1))
neighbors = []
for index in range(self.k):
neighbors.append(distances[index])
return neighbors
def predict(self, xTest, k, distanceMetric):
'''
Description:
Apply kNN model on test data
Input:
xTest: testing data with coordinates
k: number of neighbors
distanceMetric: technique to calculate distance metric
Output:
predicted label
'''
self.testData = xTest
self.k = k
self.distanceMetric = distanceMetric
predictions = []
for i, testCase in enumerate(self.testData):
neighbors = self.getNeighbors(testCase)
output= [row[-1] for row in neighbors]
prediction = max(set(output), key=output.count)
predictions.append(prediction)
return predictions
# In[4]:
def printMetrics(actual, predictions):
'''
Description:
This method calculates the accuracy of predictions
'''
assert len(actual) == len(predictions)
correct = 0
for i in range(len(actual)):
if actual[i] == predictions[i]:
correct += 1
return (correct / float(len(actual)) * 100.0)
# In[5]:
class kFoldCV:
'''
This class is to perform k-Fold Cross validation on a given dataset
'''
def __init__(self):
pass
def crossValSplit(self, dataset, numFolds):
'''
Description:
Function to split the data into number of folds specified
Input:
dataset: data that is to be split
numFolds: integer - number of folds into which the data is to be split
Output:
split data
'''
dataSplit = list()
dataCopy = list(dataset)
foldSize = int(len(dataset) / numFolds)
for _ in range(numFolds):
fold = list()
while len(fold) < foldSize:
index = randrange(len(dataCopy))
fold.append(dataCopy.pop(index))
dataSplit.append(fold)
return dataSplit
def kFCVEvaluate(self, dataset, numFolds, *args):
'''
Description:
Driver function for k-Fold cross validation
'''
knn = kNNClassifier()
folds = self.crossValSplit(dataset, numFolds)
print("\nDistance Metric: ",*args[-1])
print('\n')
scores = list()
for fold in folds:
trainSet = list(folds)
trainSet.remove(fold)
trainSet = sum(trainSet, [])
testSet = list()
for row in fold:
rowCopy = list(row)
testSet.append(rowCopy)
trainLabels = [row[-1] for row in trainSet]
trainSet = [train[:-1] for train in trainSet]
knn.fit(trainSet,trainLabels)
actual = [row[-1] for row in testSet]
testSet = [test[:-1] for test in testSet]
predicted = knn.predict(testSet, *args)
accuracy = printMetrics(actual, predicted)
scores.append(accuracy)
print('*'*20)
print('Scores: %s' % scores)
print('*'*20)
print('\nMaximum Accuracy: %3f%%' % max(scores))
print('\nMean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))
# In[6]:
def readData(fileName):
'''
Description:
This method is to read the data from a given file
'''
data = []
labels = []
with open(fileName, "r") as file:
lines = file.readlines()
for line in lines:
splitline = line.strip().split(',')
data.append(splitline)
labels.append(splitline[-1])
return data, labels
# ### Hayes-Roth Data
# In[7]:
trainFile = 'Datasets/HayesRoth/hayes-roth.data'
trainData, trainLabel = readData(trainFile)
trainFeatures = []
for row in trainData:
index = row[1:]
temp = [int(item) for item in index]
trainFeatures.append(temp)
trainLabels = [int(label) for label in trainLabel]
# **Create an object for k-Fold cross validation class**
# In[8]:
kfcv = kFoldCV()
# **Call the Evaluation function of kFCV class**
#
# *kfcv.kFCVEvaluate(data, foldCount, neighborCount, distanceMetric)*
# In[9]:
print('*'*20)
print('Hayes Roth Data')
kfcv.kFCVEvaluate(trainFeatures, 10, 3, 'euclidean')
# In[10]:
kfcv.kFCVEvaluate(trainFeatures, 10, 3, 'manhattan')
# In[11]:
kfcv.kFCVEvaluate(trainFeatures, 10, 3, 'hamming')
# ### Car Evaluation Data
# In[12]:
carFile = 'Datasets/CarEvaluation/car.data'
carData, carLabel = readData(carFile)
df = pd.DataFrame(carData)
df = df.apply(preprocessing.LabelEncoder().fit_transform)
carFeatures = df.values.tolist()
carLabels = [car[-1] for car in carFeatures]
# In[13]:
print('*'*20)
print('Car Evaluation Data')
kfcv.kFCVEvaluate(carFeatures, 10, 3, 'euclidean')
# In[14]:
kfcv.kFCVEvaluate(carFeatures, 10, 3, 'manhattan')
# In[15]:
kfcv.kFCVEvaluate(carFeatures, 10, 3, 'hamming')
# ### Breast Cancer Data
# In[16]:
print('*'*20)
print('Breast Cancer Data')
cancerFile = 'Datasets/BreastCancer/breast-cancer.data'
cancerData, cancerLabel = readData(cancerFile)
cdf = pd.DataFrame(cancerData)
cdf = cdf.apply(preprocessing.LabelEncoder().fit_transform)
cancerFeatures = cdf.values.tolist()
cancerLabels = [cancer[-1] for cancer in cancerFeatures]
# In[17]:
kfcv.kFCVEvaluate(cancerFeatures, 10, 3, 'euclidean')
# In[18]:
kfcv.kFCVEvaluate(cancerFeatures, 10, 3, 'manhattan')
# In[19]:
kfcv.kFCVEvaluate(cancerFeatures, 10, 3, 'hamming')
# In[ ]: