K-Nearest Neighbors (KNN)

 

K-Nearest Neighbors (KNN)

K-Nearest Neighbors (KNN) is a simple, intuitive supervised learning algorithm used for:

  • Classification (e.g., spam vs not spam)
  • Regression (predicting continuous values)

It is a lazy learning algorithm, meaning:

It does not build an explicit model during training—it stores the data and makes decisions at prediction time.


๐Ÿง  Core Idea

“A data point is likely to have the same label as its nearest neighbors.”

When a new data point comes in:

  1. Find the K closest points in the training data
  2. Look at their labels
  3. Assign the majority label (for classification)

⚙️ How KNN Works (Step-by-Step)

Step 1: Choose K

  • Number of neighbors to consider
  • Example: K = 3, 5, 7

Step 2: Compute Distance

The most common distance metric is Euclidean distance:

d(x,y)=i=1n(xiyi)2d(x,y)=\sqrt{\sum_{i=1}^{n}(x_i - y_i)^2}

Other distance measures:

  • Manhattan distance
  • Minkowski distance
  • Cosine similarity (for text data)

Step 3: Find Nearest Neighbors

  • Compute distance from new point to all training points
  • Sort and select K smallest distances

Step 4: Make Prediction

For Classification:

  • Use majority voting

For Regression:

  • Take average of neighbors

๐Ÿ“Š Example (Simple Classification)

Dataset

Student    Study Hours    Result
A    2    Fail
B    4    Fail
C    6    Pass
D    8    Pass

Predict for New Student:

  • Study Hours = 5
  • Choose K = 3

Step 1: Compute Distance

Point    Distance from 5
2        3
4        1
6        1
8        3

Step 2: Pick 3 Nearest

→ (4, 6, 2)

Labels:

  • Fail, Pass, Fail

Step 3: Majority Vote

๐Ÿ‘‰ Fail = 2
๐Ÿ‘‰ Pass = 1

Prediction: FAIL


๐ŸŽฏ Choosing the Value of K

K ValueBehavior
Small K (e.g., 1)        Sensitive to noise (overfitting)
Large K        Smooth decision boundary (underfitting)

๐Ÿ‘‰ Common practice:

  • Use odd K for binary classification
  • Choose K using cross-validation

๐Ÿ“ Important Concept: Feature Scaling

KNN depends on distance → scale matters!

Example:

  • Salary (₹) vs Age (years)

๐Ÿ‘‰ Use:

  • Min-Max Scaling
  • Standardization

๐Ÿงฎ KNN Regression

For ordinary KNN regression, take the average:

๐Ÿ’ฐ Predicted price = ₹55 lakh


⚖️ Weighted KNN

In ordinary KNN, every neighbor gets equal importance.

In Weighted KNN, closer neighbors get more importance.

๐Ÿ“Œ A common weight is:

where di is the distance from the new observation.

Example

Suppose the three neighbors are:

NeighborDistancePriceWeight
A0.5₹50 lakh2.0
B1.0₹45 lakh1.0
C2.0₹30 lakh0.5

Notice:

๐Ÿ”ต Closer → higher weight
๐ŸŸ  Farther → lower weight

The weighted prediction is:

wi2+1+0.5 =160​/3.5=45.71

๐Ÿ’ฐ Weighted KNN prediction = ₹45.71 lakh


๐Ÿ”‘ KNN vs Weighted KNN

KNNWeighted KNN
๐Ÿ‘ฅ NeighborsK closestK closest
⚖️ ImportanceEqualBased on distance
๐Ÿ“Š RegressionSimple averageWeighted average
๐Ÿท️ ClassificationMajority voteWeighted vote
๐Ÿ“ Closest pointSame importanceMore important

⭐ Easy way to remember

KNN:

๐Ÿ‘ฅ All neighbors have an equal vote.

Weighted KNN:

๐Ÿ“ Closer neighbors have a stronger vote.


Ordinary KNN vs Weighted KNN

FeatureKNNWeighted KNN
Neighbor importanceEqualDepends on distance
Close neighborSame importanceHigher importance
Distant neighborSame importanceLower importance
RegressionAverage of neighborsWeighted average
ClassificationMajority voteWeighted vote

⚡ Advantages

  • ✅ Simple to understand and implement
  • ✅ No training phase
  • ✅ Works well with small datasets
  • ✅ Non-parametric (no assumptions about data distribution)

⚠️ Disadvantages

  • ❌ Slow for large datasets (computationally expensive)
  • ❌ Sensitive to irrelevant features
  • ❌ Requires proper scaling
  • ❌ Memory intensive (stores all data)

๐Ÿ“Œ Real-World Applications

  • ๐Ÿ“ง Spam detection
  • ๐Ÿฅ Medical diagnosis
  • ๐ŸŽฏ Recommendation systems
  • ๐Ÿ–ผ️ Image classification
  • ๐Ÿง Pattern recognition

๐Ÿงฉ KNN vs Naรฏve Bayes (Quick Contrast)

AspectKNNNaรฏve Bayes
Type    Instance-based        Probabilistic
Training    None        Required
Speed    Slow at prediction        Fast
Assumption    None        Feature independence

๐Ÿ“Œ Final Summary

  • KNN is a distance-based algorithm
  • It predicts using similarity
  • Works by majority voting of neighbors

Comments

Popular posts from this blog

Machine Learning PCCST503 Semester5 KTU CS 2024 Scheme - Dr Binu V P

Introduction to Machine Learning (ML)

Distinguishing Machine Learning from Traditional Programming