Skip to content

Instantly share code, notes, and snippets.

@zhenghaoz
Created November 19, 2017 06:41
Show Gist options
  • Save zhenghaoz/22ac6f4a03e520fab76268761e4290f2 to your computer and use it in GitHub Desktop.
Save zhenghaoz/22ac6f4a03e520fab76268761e4290f2 to your computer and use it in GitHub Desktop.
import numpy as np
class KNearest:
X = np.array([])
y = np.array([])
k = 0
def __init__(self, k, X, y):
self.k = k
self.X = X
self.y = y
def predict(self, x):
return self.__most__(self.y[np.argsort(np.linalg.norm(self.X - x, axis=1))][0:self.k])
@staticmethod
def __most__(arr):
(values, counts) = np.unique(arr, return_counts=True)
ind = np.argmax(counts)
return values[ind]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment