-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknn.py
37 lines (27 loc) · 1.06 KB
/
knn.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
from collections import Counter
from sklearn.base import BaseEstimator
class KNN(BaseEstimator):
def __init__(self, K, distFunc):
self.data = []
self.K = K
self.distFunc = distFunc
def fit(self, data, ids):
self.data = []
self.data.extend(zip(data, ids))
def predict(self, predData):
result = []
for query in predData:
allDstQuer, closerIds = [], Counter()
# find distance from every other point
for vec in self.data:
dst = self.distFunc(vec[0], query)
allDstQuer.append((dst, vec[1]))
# sort distances so as to find K smallest
allDstQuer.sort()
for i in range(self.K):
vecId = allDstQuer[i][1]
closerIds[vecId] += 1.0
#closerIds[vecId] += 1.0 / float(allDstQuer[i][1] + 0.01)
predId = closerIds.most_common(1)[0][0]
result.append(predId)
return result