-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKNN.py
More file actions
145 lines (111 loc) · 4.19 KB
/
KNN.py
File metadata and controls
145 lines (111 loc) · 4.19 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
# %%
import csv
import random
import time
import pandas as pd
from sklearn.metrics import confusion_matrix
def handleDataset(filename, split, trainingSet, testSet):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)):
for y in range(8):
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
import math
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
import operator
def getKNeighbors(trainingSet, testInstance, k):
distances = []
length = len(testInstance)-1 # Total rows of testSet
for x in range(len(trainingSet)): # For each row in trainingSet, calculate the distance from each of the training set.
dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1)) # Sort by distance ------ > i.e lowest distances will be placed first
neighbors = []
for x in range(k): # --------- > picks 3 smallest distances ------ > 3 nearest Neighbours ----- > First 3 rows
neighbors.append(distances[x][0])
return neighbors # ----------- > Here neighbours contains the whole row.
import operator
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][-1]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)
return sortedVotes[0][0]
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct/float(len(testSet))) * 100.0
def main():
start = time.time()
trainingSet=[]
testSet=[]
split = 0.7
handleDataset('pulsar_stars -KNN.csv', split, trainingSet, testSet)
predictions=[]
k = 3
for x in range(len(testSet)):
neighbors = getKNeighbors(trainingSet, testSet[x], k)
result = getResponse(neighbors) # --------- > M/B
predictions.append(result)
accuracy = getAccuracy(testSet, predictions)
testSet_confusion_matrix = pd.DataFrame(testSet)
testSet_confusion_matrix = testSet_confusion_matrix.iloc[:,-1]
cm = confusion_matrix(testSet_confusion_matrix, predictions)
end = time.time()
TP = cm[0][0]
FP = cm[0][1]
FN = cm[1][0]
TN = cm[1][1]
Sensitivity = TP / (TP + FN)
Specificity = TN / (TN + FP)
Precision = TP / (TP+FP)
Recall = TP / (TP+FN)
print('-------------------------------------------------------------')
print('KNN ----- >')
print('-------------------------------------------------------------')
print('Confusion Matrix \n')
print(cm)
print('Accuracy: ' + repr(accuracy) + '%' + '\n')
print(f'Sensitivity obtained for kNN : {Sensitivity} \n')
print(f'Specificity obtained for kNN : {Specificity} \n')
print(f'Precision : {Precision}')
print(f'Recall : {Recall} \n')
print(f'Total time taken to build KNN algorithm ------ > {end-start}s')
main()
# %%
import pandas as pd
import csv
import random
import time
import pandas as pd
from sklearn.metrics import confusion_matrix
def handleDataset(filename, split, trainingSet, testSet):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)):
for y in range(8):
dataset[x-1][y-1] = float(dataset[x-1][y-1])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
trainingSet=[]
testSet=[]
split = 0.7
handleDataset('pulsar_stars -KNN.csv', split, trainingSet, testSet)