MCPcopy Create free account
hub / github.com/AssemblyAI-Community/Machine-Learning-From-Scratch / KNN

Class KNN

01 KNN/KNN.py:8–30  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6 return distance
7
8class KNN:
9 def __init__(self, k=3):
10 self.k = k
11
12 def fit(self, X, y):
13 self.X_train = X
14 self.y_train = y
15
16 def predict(self, X):
17 predictions = [self._predict(x) for x in X]
18 return predictions
19
20 def _predict(self, x):
21 # compute the distance
22 distances = [euclidean_distance(x, x_train) for x_train in self.X_train]
23
24 # get the closest k
25 k_indices = np.argsort(distances)[:self.k]
26 k_nearest_labels = [self.y_train[i] for i in k_indices]
27
28 # majority voye
29 most_common = Counter(k_nearest_labels).most_common()
30 return most_common[0][0]

Callers 1

train.pyFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected