K-Nearest Neighbors
Hard
machine-learning
Netflix
Spotify
Implement a simple K-Nearest Neighbors classifier from scratch.
Given training data as a list of (features, label) tuples, a query
point, and k, return the most common label among the k nearest
training points using Euclidean distance.
If there is a tie, return the label that appears first among the nearest neighbors (by distance, then by insertion order).
Example:
train = [([0, 0], "A"), ([1, 1], "A"), ([5, 5], "B"), ([6, 6], "B")]
knn_classify(train, [1, 0], k=3) → "A"
Test Cases
Python Editor
Output
Click "Run" to see results...