Classify a point by majority vote among its **K nearest training examples** — the simplest non-parametric classifier.
1. Compute Euclidean distance from query to all training points
2. Select the K nearest neighbors
3. Return the label with the most votes
train = [[0,0],[1,0],[0,1],[1,1]] labels = [0, 0, 1, 1] knn(train, labels, query=[0.4,0.4], k=3) → 0
Similar Problems
Test Cases (2 visible · 1 hidden)
Case 1: Nearest to class 0
Input: knn([[0,0],[1,0],[0,1],[1,1]],[0,0,1,1],[0.4,0.4],3)
Expected: 0
Case 2: Nearest to class 1
Input: knn([[0,0],[1,0],[0,1],[1,1]],[0,0,1,1],[0.6,0.6],3)
Expected: 1
⌘↵ Run · ⌘⇧↵ Submit