-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkNearestNeighbor.py
More file actions
40 lines (28 loc) · 1008 Bytes
/
Copy pathkNearestNeighbor.py
File metadata and controls
40 lines (28 loc) · 1008 Bytes
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
from collections import Counter
import numpy as np
def predict(X_train, y_train, x_test, k):
# create list for distances and targets
distances = []
targets = []
for i in range(len(X_train)):
# first we compute the euclidean distance
distance = np.sqrt(np.sum(np.square(x_test - X_train[i, :])))
# add it to list of distances
distances.append([distance, i])
# sort the list
distances = sorted(distances)
# make a list of the k neighbors' targets
for i in range(k):
index = distances[i][1]
targets.append(y_train[index])
# return most common target
return Counter(targets).most_common(1)[0][0]
def kNearestNeighbor(X_train, y_train, X_test, predictions, k):
# train on the input data
train(X_train, y_train)
# loop over all observations
for i in range(len(X_test)):
predictions.append(predict(X_train, y_train, X_test[i, :], k))
def train(X_train, y_train):
# do nothing
return