Skip to main content

Implement the KNN Algorithm

EasyPremium

Implement the K-nearest neighbors (KNN) algorithm. The knn function will have four inputs:

  1. X_train: a NumPy array of points that are already on the map.
  2. Y_train: a NumPy array of labels for each point on the map, either 1 or 0.
  3. X_new: a NumPy array for the new point you're adding to the map and want to classify.
  4. k: an integer that tells you how many of the closest points to X_new you should look at to decide its label.

The K-nearest neighbors (KNN) algorithm classifies a new data point based on the most common category among its k closest neighbors in the dataset. It calculates the distance between points to determine "closeness."

Visit our Model & Algorithm Fundamentals module to master everything you need to know about KNN for interviews.

Python
# Example X_train = np.array([[1, 2], [2, 3], [3, 4], [6, 7], [7, 8], [8, 9]]) y_train = np.array([0, 0, 0, 1, 1, 1]) X_new = np.array([2, 2]) # The new point we want to classify k = 3 # We'll look at the 3 closest points knn(X_train, y_train, X_new, k) # should return 0