Skip to content
DeepForgeby svx
All problems
MediumML Fundamentalsml-004

K-Nearest Neighbors

Problem

Predict the class label of x_test by majority vote among its k nearest neighbors in X_train.

Distance is Euclidean. Ties in the vote are broken by choosing the smallest label.

Hint

Sort by distance, take top k, count labels, break ties by smallest label.

Test cases

case 1
in: [[[0,0],[0,1],[10,10],[10,11]],["a","a","b","b"],[1,0],2]
expected: "a"
case 2
in: [[[0,0],[0,1],[10,10],[10,11]],["a","a","b","b"],[9,10],2]
expected: "b"
case 3
in: [[[1],[2],[3],[10]],[0,0,0,1],[4],3]
expected: 0
Starter codePython
def knn_predict(X_train, y_train, x_test, k):
    # Your code here
    pass

3 test cases · run your code against them in the editor