Rana Maninder Singh
Lesson 5 of 7ML Fundamentals

K-Nearest Neighbors (KNN) — Distance, K & Use Cases

Lesson opener

In one line: How KNN classifies by voting among nearest neighbors.

Why it matters: Simple, intuitive, works well on small datasets with clear local structure.

Before this lesson: Logistic regression / Pandas basics

Before you start

ResourceLink
PreviousLogistic regression
NextDecision trees
PrerequisitesLogistic regression, Pandas basics
Time~45 minutes

What you will learn

  • How KNN classifies by voting among nearest neighbors
  • Choosing K — bias vs variance tradeoff
  • Distance metrics: Euclidean, Manhattan, and when each matters
  • Use cases where KNN shines — and where it fails

What is KNN?

The problem it solves: A Chennai ed-tech startup wants to recommend courses. For a new student with scores in math and reading, KNN finds the K most similar past students and predicts based on what those neighbors chose.

No equation to learn. No tree to draw. KNN stores training data and compares distances at prediction time.

WHY Simple, intuitive, works well on small datasets with clear local structure.

WHEN Similarity-based problems — recommendations, anomaly detection, small tabular sets.


How KNN works

  1. Store all training points with labels
  2. For a new point, compute distance to every training point
  3. Pick the K closest neighbors
  4. Classification: majority vote among neighbor labels
  5. Regression: average neighbor values
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("data/customers.csv")
X = df[["tenure_months", "monthly_spend", "support_tickets"]]
y = df["churned"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Scale features — KNN uses distances!
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)

model = KNeighborsClassifier(n_neighbors=5, metric="euclidean")
model.fit(X_train_s, y_train)

pred = model.predict(X_test_s)
print("Accuracy:", accuracy_score(y_test, pred))
print(classification_report(y_test, pred))

Always scale numeric features for KNN. monthly_spend in thousands dominates support_tickets in single digits without scaling.


Choosing K

K valueBehaviour
K = 1Very flexible — memorises noise (overfits)
K = 5–15Common starting range
K = largeSmooth boundaries — may underfit
for k in [1, 3, 5, 11, 21]:
    m = KNeighborsClassifier(n_neighbors=k)
    m.fit(X_train_s, y_train)
    train_acc = accuracy_score(y_train, m.predict(X_train_s))
    test_acc = accuracy_score(y_test, m.predict(X_test_s))
    print(f"K={k:2d}  train={train_acc:.2f}  test={test_acc:.2f}")

Pick K where test accuracy is strong without train >> test (overfitting).


Distance metrics

MetricFormula ideaWhen to use
EuclideanStraight-line distanceDefault; continuous features
ManhattanSum of absolute differencesGrid-like data, high dimensions
MinkowskiGeneralises both (p=2 → Euclidean)sklearn default
KNeighborsClassifier(n_neighbors=5, metric="manhattan")

WHY metric matters: Two customers "close" in Euclidean space may be far in business terms if one axis dominates.


KNN use cases

Good fitPoor fit
Small–medium tabular dataMillions of rows (slow prediction)
Recommendation by similarityHigh-dimensional sparse text (use TF-IDF + other models)
Anomaly detection (K=1, far neighbors)Need interpretable rules for regulators
Baseline before complex modelsFeatures on wildly different scales (without scaling)

Indian workplace example: Pharmacy chain flags unusual prescription patterns — if a customer's purchase vector is far from all neighbors, flag for review.


KNN vs logistic regression vs trees

KNNLogistic regressionDecision trees
InterpretabilityLowHigh (coefficients)High (rules)
Training speedFast (just store data)FastFast
Prediction speedSlow (scan all points)FastFast
Scaling requiredYesHelpfulNo

Practice

  1. Train KNN with K=1, 5, 15 on customers.csv; compare train vs test accuracy.
  2. Retry without StandardScaler — note accuracy drop.
  3. Try metric="manhattan" vs default — any difference?

Checklist

  • [ ] Can you explain KNN in one sentence?
  • [ ] Do you know why scaling is mandatory?
  • [ ] Can you tune K using train vs test accuracy?
  • [ ] Can you name two distance metrics?

What's next

Decision trees — when you need human-readable rules instead of neighbor votes.