Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 3 of 9

K-Nearest Neighbors (KNN): Distance Metrics, Dimensionality & Spatial Indexing

K-Nearest Neighbors (KNN) is an instance-based, non-parametric 'lazy learner'. It does not learn explicit parameters during training; instead, it stores the training dataset in spatial search trees (KD-Tree, Ball-Tree). At inference time, it computes distance between the query vector and all training points, assigning the majority class among the k closest neighbors. KNN's effectiveness depends entirely on feature scaling, metric choice (Euclidean, Manhattan, Cosine), and avoiding the Curse of Dimensionality.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Spatial Search Engines & Distance Metric Benchmark

Spatial Search Engines & Distance Metric Benchmark
import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.datasets import make_classification

# Generate classification dataset with 6 features
X, y = make_classification(n_samples=1000, n_features=6, n_informative=4, random_state=42)

# KNN Pipeline with Parameter Search: k, metric (p=1 Manhattan, p=2 Euclidean), and weights
pipe_knn = Pipeline([
    ('scaler', StandardScaler()), # MANDATORY FOR KNN
    ('knn', KNeighborsClassifier(algorithm='auto')) # Automatically picks Brute-force, KD-Tree, or Ball-Tree
])

param_grid = {
    'knn__n_neighbors': [3, 5, 9, 15, 25],
    'knn__weights': ['uniform', 'distance'], # 'distance' weights votes inversely by 1/d
    'knn__p': [1, 2] # p=1 Manhattan (L1), p=2 Euclidean (L2)
}

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
grid = GridSearchCV(pipe_knn, param_grid, cv=cv, scoring='roc_auc')
grid.fit(X, y)

print("=== OPTIMAL KNN HYPERPARAMETERS ===")
print(f"Best ROC-AUC Score : {grid.best_score_:.4f}")
print(f"Optimal Parameters : {grid.best_params_}")

# Notice: Distance-weighted voting (weights='distance') prevents ties and boosts precision!

Pro Tip: Distance Metrics for High-Dimensional Sparse Vectors

In high-dimensional spaces (e.g. text TF-IDF vectors or image embeddings with 512+ dimensions), Euclidean distance suffers from the Curse of Dimensionality (all pairwise distances converge to the same value). Use Cosine distance (`metric='cosine'`), which measures angular similarity regardless of vector magnitude.

Diagram
Loading diagram…

MlKNNAlgorithm Visual Representation

Hands-On Challenge: Demonstrate the Curse of Dimensionality

Generate random uniform points in D dimensions. Calculate the ratio between the minimum and maximum pairwise Euclidean distances as D increases from 2 to 200. Observe how `min_dist / max_dist` approaches 1.0, rendering distance-based neighborhood queries meaningless.

Quick Quiz & Key Concept Checks

Common Pitfall: Even-Numbered k in Binary Classification

Using an even value of k (e.g. `n_neighbors=4`) in binary classification creates frequent 2-to-2 voting ties. Scikit-Learn resolves ties by picking the first class encountered in memory, introducing arbitrary non-deterministic bias. Always use odd values of k (3, 5, 7, 9) for binary targets.

Topics in This Module

0/9 done