K-Nearest Neighbors
easy· Machine Learningruns: 0Implement the K-Nearest Neighbors classifier from scratch. Given training features and labels, predict the label of each query point by majority vote among its k closest neighbors using Euclidean distance.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 510
import numpy as np
from collections import Counter
class KNN:
def __init__(self, k: int = 3):
self.k = k
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
return np.array([self._predict_one(x) for x in X])
def _predict_one(self, x):
distances = np.linalg.norm(self.X_train - x, axis=1)
k_idx = np.argsort(distances)[: self.k]
labels = self.y_train[k_idx]
return Counter(labels).most_common(1)[0][0]
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.