forked from pepesan/machine-learning-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04_02_02_knnv2.py
196 lines (154 loc) · 5.77 KB
/
04_02_02_knnv2.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
import csv
import random
import math
import operator
from time import time
def loadDataset(filename, divFactor, trainData=[], testData=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for i in range(len(dataset) - 1):
for j in range(len(dataset[0])):
dataset[i][j] = float(dataset[i][j])
if random.random() < divFactor:
trainData.append(dataset[i])
else:
testData.append(dataset[i])
def Distance(instance1, instance2, length):
distance = 0
for i in range(length):
distance += pow((instance1[i] - instance2[i]), 2)
return math.sqrt(distance)
def kNearestNeighbors(trainData, test, k):
distances = []
length = len(test) - 1
for i in range(len(trainData)):
currentDistance = Distance(test, trainData[i], length)
distances.append((trainData[i], currentDistance))
distances.sort(key=operator.itemgetter(1))
kNeighbors = []
for i in range(k):
kNeighbors.append(distances[i][0])
return kNeighbors
def Classify(neighbors):
classVotesDict = {}
for i in range(len(neighbors)):
someClass = neighbors[i][-1]
if someClass in classVotesDict:
classVotesDict[someClass] += 1
else:
classVotesDict[someClass] = 1
sortedCVDict = sorted(classVotesDict.items(), key=operator.itemgetter(1), reverse=True)
return sortedCVDict[0][0]
def Accuracy(testData, predictions):
hits = 0
for i in range(len(testData)):
if testData[i][-1] == predictions[i]:
hits += 1
return (hits / float(len(testData))) * 100.0
def feature_normalize(X):
mean = 0.0
std = 0.0
total = 0.0
columnlist = []
for col in range(0, len(X[0]) - 1):
for row in range(0, len(X)):
total += X[row][col]
columnlist.append(X[row][col])
mean = total / len(X)
# std = 0.0000000000001 + max(columnlist) - min(columnlist)
std = 0.001 + max(columnlist) - min(columnlist)
for row in range(0, len(X)):
X[row][col] = (X[row][col] - mean) / std
columnlist[:] = []
mean = 0.0
std = 0.0
total = 0.0
def feature_normalize2(X):
std = 0.0
columnlist = []
for col in range(0, len(X[0]) - 1):
for row in range(0, len(X)):
columnlist.append(X[row][col])
# std = 0.0000000000001 + max(columnlist) - min(columnlist)
std = 0.0000001 + max(columnlist) - min(columnlist)
for row in range(0, len(X)):
X[row][col] = (X[row][col] - min(columnlist)) / std
columnlist[:] = []
std = 0.0
trainData = []
testData = []
K = range(1, 27, 2)
divFactor = 0.8
averageAccuracy = 0
numberOfTests = 100
accuracies = []
averageAccuracies = []
predictions = []
times = []
KsForPlot = []
AccuraciesForPlot = []
for x in range(len(K)):
for n in range(100):
loadDataset('./csv/knn.csv', divFactor, trainData, testData)
# feature_normalize2(trainData)
# feature_normalize2(testData)
t0 = time()
for i in range(len(testData)):
kNeighbors = kNearestNeighbors(trainData, testData[i], K[x])
predict = Classify(kNeighbors)
predictions.append(predict)
times.append(round(time() - t0, 3))
accuracy = Accuracy(testData, predictions)
accuracies.append(accuracy)
KsForPlot.append(K[x])
AccuraciesForPlot.append(accuracy)
del trainData[:]
del testData[:]
del predictions[:]
averageTime = sum(times) / float(len(times))
averageAccuracy = sum(accuracies) / float(len(accuracies))
print('Average Time for K=' + repr(K[x]) + " after " + repr(
numberOfTests) + " tests with different data split: " + repr(round(averageTime, 6)) + ' sec')
print('Average accuracy for K=' + repr(K[x]) + " after " + repr(
numberOfTests) + " tests with different data split: " + repr(averageAccuracy) + ' %')
print("")
# print 'Accuracies for each of the ', repr(numberOfTests), " tests with K =",K[x], ":", accuracies
# print("#####################################################################################################################")
del accuracies[:]
del times[:]
print("")
print('Checking predictions with K = 3:')
K = 3
loadDataset('./csv/knn.csv', divFactor, trainData, testData)
# feature_normalize2(trainData)
# feature_normalize2(testData)
for i in range(len(testData)):
kNeighbors = kNearestNeighbors(trainData, testData[i], K)
predict = Classify(kNeighbors)
predictions.append(predict)
print('Predicted class: ' + repr(predict) + ', Real class: ' + repr(testData[i][-1]))
accuracy = Accuracy(testData, predictions)
print('Accuracy: ' + repr(accuracy) + '%')
############################################################################################################
# Visualization part:
############################################################################################################
import matplotlib.pyplot as plt
import numpy as np
left, width = .35, 0.5
bottom, height = .27, .7
right = left + width
top = bottom + height
Ks = np.array(KsForPlot)
Accs = np.array(AccuraciesForPlot)
# Data and prediction line
fig, ax = plt.subplots(figsize=(15, 10))
# ax.plot(Ks, Accs, 'b', label='Prediction')
ax.scatter(Ks, Accs, label='Traning Data', color='r')
# ax.scatter(Ks, Accs, color='r')
ax.legend(loc=3)
ax.set_xlabel('K (from 1 to 25)')
ax.set_ylabel('Accuracy')
ax.set_title('Accuracies against K used. For each K 100 accuracies plotted')
# ax.text(right, top, 'Accuracies against K used. For each K 100 accuracies plotted', size=18,horizontalalignment='right', verticalalignment='top', transform=ax.transAxes)
plt.show()