Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 28

K-Nearest Neighbors

Classify a new point by the majority label among the closest training rows, with no learned equation. One example is on this page.

Intermediate12 min
K-Nearest Neighbors MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

K-nearest neighbors stores the training rows. To classify a new row it measures distance to every stored row, keeps the k closest, and votes. There is no weight vector. The prediction changes only when the neighbors change.

Example

python
import numpy as np
from sklearn.neighbors import KNeighborsClassifier

X = np.array([[1, 1], [1.2, 1], [5, 5], [5.2, 4.8]])
y = np.array([0, 0, 1, 1])
label = KNeighborsClassifier(n_neighbors=3).fit(X, y).predict([[1.1, 1.2]])[0]
print(f"label: {int(label)}")

Output:

text
label: 0

When to use it

  • Use it when similar rows should get the same label and the table is not huge.
  • Scale inputs first. A column with a larger range would own the distance.
  • Odd k avoids a tie between two classes.

Loading playground…