Skip to main content
All Questions

Implement a k-nearest neighbors algorithm.

Easy
Unlock detailed company stats for this questionUpgrade

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.
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

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.