Skip to content

Instantly share code, notes, and snippets.

@VladimirYugay
Created May 3, 2022 21:43
Show Gist options
  • Save VladimirYugay/3bdb97be7d5d8c5e3b11af4add96cd07 to your computer and use it in GitHub Desktop.
Save VladimirYugay/3bdb97be7d5d8c5e3b11af4add96cd07 to your computer and use it in GitHub Desktop.
KNN classifier in pure numpy
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