Created
May 3, 2022 21:43
-
-
Save VladimirYugay/3bdb97be7d5d8c5e3b11af4add96cd07 to your computer and use it in GitHub Desktop.
KNN classifier in pure numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
class KNNClassifier(object): | |
def __init__(self, data, labels, k): | |
self.data = data | |
self.labels = labels | |
self.k = k | |
def predict(sample: np.ndarray): | |
""" Predicts the label of the sample based on k nearest neighbors | |
Args: | |
sample: sample to classify | |
""" | |
dist = np.linalg.norm(self.data - sample[None, ], axis=1) | |
idx = np.argpartition(dist, self.k)[:self.k] | |
counts = np.bincount(self.labels[idx]) | |
return np.argmax(counts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment