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
| Resource | Link |
|---|---|
| Previous | Logistic regression |
| Next | Decision trees |
| Prerequisites | Logistic 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
- Store all training points with labels
- For a new point, compute distance to every training point
- Pick the K closest neighbors
- Classification: majority vote among neighbor labels
- 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_spendin thousands dominatessupport_ticketsin single digits without scaling.
Choosing K
| K value | Behaviour |
|---|---|
| K = 1 | Very flexible — memorises noise (overfits) |
| K = 5–15 | Common starting range |
| K = large | Smooth 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
| Metric | Formula idea | When to use |
|---|---|---|
| Euclidean | Straight-line distance | Default; continuous features |
| Manhattan | Sum of absolute differences | Grid-like data, high dimensions |
| Minkowski | Generalises 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 fit | Poor fit |
|---|---|
| Small–medium tabular data | Millions of rows (slow prediction) |
| Recommendation by similarity | High-dimensional sparse text (use TF-IDF + other models) |
| Anomaly detection (K=1, far neighbors) | Need interpretable rules for regulators |
| Baseline before complex models | Features 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
| KNN | Logistic regression | Decision trees | |
|---|---|---|---|
| Interpretability | Low | High (coefficients) | High (rules) |
| Training speed | Fast (just store data) | Fast | Fast |
| Prediction speed | Slow (scan all points) | Fast | Fast |
| Scaling required | Yes | Helpful | No |
Practice
- Train KNN with K=1, 5, 15 on
customers.csv; compare train vs test accuracy. - Retry without
StandardScaler— note accuracy drop. - 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.