ML Study Hub
← Back to Study Hub
Module 03 · Bayes & KNN
← Hub
Intuition Bayes Math KNN Distances K-Tradeoff Traps Past Papers Calculator Quiz Checklist
Module 03 · Generative & Instance-Based Learning

Naïve Bayes & K-Nearest Neighbors (KNN)

High-yield numerical guarantees. Complete step-by-step verified solutions for the 10-row Car Theft problem, 4-row Email Spam filtering with Laplace smoothing, KNN distance metrics ($L_1$ vs $L_2$), and the bias-variance trade-off of $K$.

Jan 2025 (Q4 20M, Q5 20M) CT-2 (Q1.a 15M, Q2 20M) Car Theft 10-Row Spam Filtering Euclidean vs Manhattan

01. Intuition & Concept Contrast

Two fundamental paradigms: Naïve Bayes models how data is generated per class ($P(\mathbf{x} \mid C)$), while KNN defers all computation until query time by finding geometric neighbors.

Learning Strategy

Generative vs Lazy Instance-Based

Naïve Bayes (Generative Model): Learns the joint probability $P(\mathbf{x}, C) = P(C)P(\mathbf{x} \mid C)$ via Bayes' theorem. Compact parameter footprint ($O(d)$); exceptionally fast inference.

KNN (Lazy Instance-Based Learner): Zero training time ($O(1)$). Stores entire dataset and scans all $N$ observations during query inference ($O(N \cdot d)$ time).

Geometry vs Independence

Metric Space vs Conditional Independence

Naïve Bayes Assumption: Assumes all attributes $X_1, \dots, X_d$ are mutually independent given class label $C$. Robust in high-dimensional text.

KNN Metric Assumption: Assumes points close in Euclidean/Manhattan space share the same class label. Requires feature standardization to prevent scale dominance.

02. Naïve Bayes Mathematical Formulation

Applying Bayes' Rule with the Conditional Independence Assumption.

The Master Naïve Bayes Equation
$$P(C = c \mid \mathbf{x}) = \frac{P(C = c) \prod_{j=1}^d P(x_j \mid C = c)}{P(\mathbf{x})}$$ Where $P(\mathbf{x}) = \sum_{k} P(C_k) \prod_{j=1}^d P(x_j \mid C_k)$ is the normalising evidence.

1. The Conditional Independence Assumption

In full Bayesian modeling, calculating $P(x_1, x_2, \dots, x_d \mid C)$ requires joint probability tables of size $O(2^d)$, which is intractable. Naïve Bayes assumes:

$$P(x_1, x_2, \dots, x_d \mid C) = P(x_1 \mid C) \cdot P(x_2 \mid C) \cdots P(x_d \mid C) = \prod_{j=1}^d P(x_j \mid C)$$

This collapses parameter estimation from exponential $O(2^d)$ to linear $O(d)$.

2. Maximum A Posteriori (MAP) Decision Rule

Because evidence $P(\mathbf{x})$ is constant across all candidate classes, the classification decision is determined solely by the unnormalized joint score:

$$\hat{y} = \arg\max_{c} \left[ P(C = c) \prod_{j=1}^d P(x_j \mid C = c) \right]$$

3. Laplace Smoothing (Add-1 Smoothing for Zero Frequencies)

If a feature value $x_j$ never appeared with class $c$ in training, $P(x_j \mid C = c) = 0$. In a multiplicative product, this single zero wipes out all other evidence: $\prod P = 0$.

Laplace Smoothing Formula:
$$P(x_j \mid C = c) = \frac{\operatorname{Count}(x_j \text{ and } c) + \alpha}{\operatorname{Count}(c) + \alpha \cdot K}$$ Where $\alpha = 1$ is the pseudo-count, and $K$ is the number of distinct values attribute $X_j$ can take.

03. K-Nearest Neighbors Distance Metrics

KNN relies on geometric distance between a query vector $\mathbf{q} = [q_1, \dots, q_d]^T$ and stored vectors $\mathbf{x}_i = [x_{i1}, \dots, x_{id}]^T$.

Metric Formula Geometric Meaning When Preferred in Exams
Euclidean Distance ($L_2$ Norm) $d_E(\mathbf{q}, \mathbf{x}_i) = \sqrt{\sum_{j=1}^d (q_j - x_{ij})^2}$ Straight-line "as the crow flies" physical distance Default metric for isotropic physical features
Manhattan Distance ($L_1$ Norm) $d_M(\mathbf{q}, \mathbf{x}_i) = \sum_{j=1}^d |q_j - x_{ij}|$ Grid-based "taxicab" street navigation distance City layouts (food delivery), high dimensions, robust to outliers
Minkowski Distance ($L_p$ Norm) $d_p(\mathbf{q}, \mathbf{x}_i) = \left(\sum_{j=1}^d |q_j - x_{ij}|^p\right)^{1/p}$ Generalized distance metric parameterised by $p$ $p=1 \implies L_1$ (Manhattan), $p=2 \implies L_2$ (Euclidean)
Mandatory Preprocessing: Why Feature Scaling is Essential in KNN!
Suppose $x_1 = \text{Income in ₹} \in [20000, 60000]$ and $x_2 = \text{Years Experience} \in [1, 10]$.
In Euclidean distance: $(\Delta x_1)^2 = (20,000)^2 = 400,000,000$, whereas $(\Delta x_2)^2 = (5)^2 = 25$.
The income feature completely dominates the distance metric by a factor of 16 million, making experience irrelevant. Z-Score Standardization ($z = \frac{x - \mu}{\sigma}$) or Min-Max Scaling ($[0, 1]$) is strictly mandatory before KNN.

04. The Bias-Variance Trade-off of Parameter $K$

Jan 2025 (Q4) & CT-2 (Q2) Core Theory Question (5 Marks).

Small K ($K=1$)

Overfitting (High Variance, Low Bias)

  • Model fits every individual training point perfectly ($0\%$ training error).
  • Decision boundaries are complex, jagged, and fragmented into tiny islands.
  • Severe Failure: A single mislabeled noise outlier will create an entire false classification zone around itself.
Large K ($K \to N$)

Underfitting (High Bias, Low Variance)

  • Neighborhood includes almost the entire dataset.
  • Decision boundaries become overly smooth and rigid.
  • Severe Failure: Collapses into global majority voting. Every query point is assigned to whichever class has more samples in the training set.
Golden Rule for Selecting $K$:
1. Set $K \approx \sqrt{N}$ (e.g., if $N = 100$, start around $K = 9$ or $11$).
2. Always choose an odd integer for binary classification to guarantee no tied votes.
3. Optimize $K$ via Stratified K-Fold Cross-Validation on validation error.

05. Notation Decoding Matrix

Symbol Formal Name Plain-English Meaning Applied Exam Example
$P(C)$ Class Prior Probability Baseline proportion of class in historical data $P(\text{Stolen}=\text{Yes}) = 5/10 = 0.5$
$P(x_j \mid C)$ Conditional Likelihood Probability of observing feature $x_j$ given class $C$ $P(\text{Color}=\text{Red} \mid \text{Yes}) = 3/5 = 0.6$
$P(C \mid \mathbf{x})$ Posterior Probability Updated belief of class after observing features $P(\text{Stolen}=\text{Yes} \mid \text{Red SUV}) = 0.25$
$\mathbf{q}$ Query Point Unseen test instance to be classified $\mathbf{q} = (\text{Income}=40, \text{Spending}=15)$
$\mathcal{N}_K(\mathbf{q})$ K-Neighborhood Set of $K$ training samples with smallest distance to $\mathbf{q}$ $\{C_3, C_5, C_4\}$ when $K=3$

06. Repeatable Step-by-Step Solving Protocol

Step 1: Compute Class Priors $P(C_k)$ $$P(C_k) = \frac{\text{Count}(C_k)}{N}$$
Step 2: Construct Conditional Frequency Tables

Count occurrences of each attribute value for each class: $P(x_j \mid C_k) = \frac{\text{Count}(x_j \text{ and } C_k)}{\text{Count}(C_k)}$. Check for zeros (apply Laplace if needed).

Step 3: Calculate Unnormalized Joint Scores $$\mathcal{L}(C_k) = P(C_k) \times \prod_{j=1}^d P(x_j \mid C_k)$$
Step 4: Compute Evidence & Normalized Posteriors $$P(\mathbf{x}) = \sum_k \mathcal{L}(C_k), \qquad P(C_k \mid \mathbf{x}) = \frac{\mathcal{L}(C_k)}{P(\mathbf{x})}$$
Step 5: Apply MAP Decision Rule & Interpret

Select $\hat{y} = \arg\max_k P(C_k \mid \mathbf{x})$. State which features contributed most to the decision.

07. 6 Deadly Exam Traps & Common Student Mistakes

Trap 01: Forgetting Class Prior

Multiplying Only Likelihoods

Students compute $\prod P(x_j \mid C)$ but forget to multiply by prior $P(C)$. If class proportions are unequal (e.g. $90\%$ benign vs $10\%$ spam), omitting $P(C)$ ruins the prediction.

Trap 02: Laplace Denominator Mistake

Adding $+1$ Instead of $+K$ in Denominator

In Laplace smoothing, students write $\frac{\text{count}+1}{\text{total}+1}$. The denominator MUST add $+K$ (number of distinct levels of feature): $\frac{\text{count}+1}{\text{total}+K}$, otherwise probabilities won't sum to 1.

Trap 03: Skipping Feature Scaling in KNN

Computing Raw Distances on Mixed Units

Distance metrics without normalization mean features with big numbers (like Annual Income) dwarf features with small numbers (like Age). Examiners deduct marks if scaling is not mentioned.

Trap 04: Even $K$ in Binary KNN

Choosing $K=2$ or $K=4$

Even $K$ values allow tied votes (1 High vs 1 Low). In exam questions, always explicitly specify that $K$ should be odd to break ties.

Trap 05: Unnormalized Posterior Scores

Reporting $\mathcal{L}(C)$ as Final Probability

Writing "Probability of Stolen is $0.024$" is incorrect. $0.024$ is the unnormalized joint likelihood. The posterior probability is $\frac{0.024}{0.024 + 0.072} = \mathbf{0.25 \ (25\%)}$.

Trap 06: Independent vs Conditionally Independent

Confusing $P(A, B) = P(A)P(B)$ with $P(A, B \mid C) = P(A \mid C)P(B \mid C)$

Naïve Bayes features are NOT unconditionally independent. They are only independent conditional upon the class label $C$.

08. Complete University Question Bank (All Past PYQs Solved)

Jan 2025 · Question 5 The 10-Row Car Theft Naïve Bayes Classification (20 Marks)
Question Statement:
Consider a 10-row dataset with attributes Color (Red, Yellow), Type (Sports, SUV), Origin (Domestic, Imported), and target Stolen (Yes, No).
Assume no pair of features are dependent, and each feature has equal influence.
Predict whether a car with [Color = Red, Type = SUV, Origin = Domestic] is stolen or not. Explain prediction and interpret result. (20 Marks)
No.ColorTypeOriginStolen?
1RedSportsDomesticYes
2RedSportsDomesticNo
3RedSportsDomesticYes
4YellowSportsDomesticNo
5YellowSportsImportedYes
6YellowSUVImportedNo
7YellowSUVImportedYes
8YellowSUVDomesticNo
9RedSUVImportedNo
10RedSportsImportedYes

Solution:

1. Priors and Frequency Tables ($N = 10$):

Total Stolen = Yes: $5 \implies P(\text{Yes}) = \frac{5}{10} = 0.5$

Total Stolen = No: $5 \implies P(\text{No}) = \frac{5}{10} = 0.5$

AttributeValue$P(\text{Feature} \mid \text{Yes})$$P(\text{Feature} \mid \text{No})$
ColorRed$3/5 = \mathbf{0.6}$$2/5 = \mathbf{0.4}$
Yellow$2/5 = \mathbf{0.4}$$3/5 = \mathbf{0.6}$
TypeSports$4/5 = \mathbf{0.8}$$2/5 = \mathbf{0.4}$
SUV$1/5 = \mathbf{0.2}$$3/5 = \mathbf{0.6}$
OriginDomestic$2/5 = \mathbf{0.4}$$3/5 = \mathbf{0.6}$
Imported$3/5 = \mathbf{0.6}$$2/5 = \mathbf{0.4}$
2. Calculate Unnormalized Likelihoods for Test Car:
$$\begin{aligned} \mathcal{L}(\text{Yes}) &= P(\text{Yes}) \cdot P(\text{Red}\mid\text{Yes}) \cdot P(\text{SUV}\mid\text{Yes}) \cdot P(\text{Domestic}\mid\text{Yes}) \\[4pt] &= 0.5 \times 0.6 \times 0.2 \times 0.4 = \mathbf{0.024} \\[8pt] \mathcal{L}(\text{No}) &= P(\text{No}) \cdot P(\text{Red}\mid\text{No}) \cdot P(\text{SUV}\mid\text{No}) \cdot P(\text{Domestic}\mid\text{No}) \\[4pt] &= 0.5 \times 0.4 \times 0.6 \times 0.6 = \mathbf{0.072} \end{aligned}$$
3. Evidence and Normalized Posteriors:
$$P(\mathbf{x}) = 0.024 + 0.072 = \mathbf{0.096}$$ $$P(\text{Yes} \mid \mathbf{x}) = \frac{0.024}{0.096} = \mathbf{0.25 \quad (25\%)}$$ $$P(\text{No} \mid \mathbf{x}) = \frac{0.072}{0.096} = \mathbf{0.75 \quad (75\%)}$$
4. Final Decision & Interpretation:

Decision: The test car is classified as NOT STOLEN ($\hat{y} = \text{No}$).

Interpretation: Even though Red cars are stolen more often ($60\%$ vs $40\%$), both the car being an SUV ($P=0.60$ for No vs $0.20$ for Yes) and being Domestic ($P=0.60$ for No vs $0.40$ for Yes) strongly tilt toward non-theft, outvoting color by a $3:1$ margin ($75\%$ to $25\%$).

CT-2 · Question 1.a Email Spam Filtering with Naïve Bayes (15 Marks)
Question Statement:
4 training emails with Offer (Yes/No), Win (Yes/No), and Spam (Yes/No).
E1: Offer=Yes, Win=Yes, Spam=Yes | E2: Offer=No, Win=Yes, Spam=Yes
E3: Offer=Yes, Win=No, Spam=No | E4: Offer=No, Win=No, Spam=No
i) Calculate conditional probabilities (5M)
ii) For new email "Offer = Yes, Win = Yes", compute posteriors (5M)
iii) Predict class and explain independence assumption (5M)

Solution:

(i) Conditional Probabilities (5 Marks)
  • $P(\text{Offer} = \text{Yes} \mid \text{Spam}) = 1/2 = \mathbf{0.5}$
  • $P(\text{Win} = \text{Yes} \mid \text{Spam}) = 2/2 = \mathbf{1.0}$
  • $P(\text{Offer} = \text{Yes} \mid \text{NotSpam}) = 1/2 = \mathbf{0.5}$
  • $P(\text{Win} = \text{Yes} \mid \text{NotSpam}) = 0/2 = \mathbf{0.0}$
(ii) New Email Posteriors: $\mathbf{X}_{\text{new}} = (\text{Offer} = \text{Yes}, \text{Win} = \text{Yes})$ (5 Marks)
$$\begin{aligned} P(\text{Spam}) &= 2/4 = 0.5, \qquad P(\text{NotSpam}) = 2/4 = 0.5 \\[4pt] \mathcal{L}(\text{Spam}) &= 0.5 \times 0.5 \times 1.0 = \mathbf{0.25} \\[4pt] \mathcal{L}(\text{NotSpam}) &= 0.5 \times 0.5 \times 0.0 = \mathbf{0.0} \\[4pt] P(\text{Spam} \mid \text{Email}) &= \frac{0.25}{0.25 + 0.0} = \mathbf{1.0 \quad (100\%)} \\[4pt] P(\text{NotSpam} \mid \text{Email}) &= \frac{0.0}{0.25 + 0.0} = \mathbf{0.0 \quad (0\%)} \end{aligned}$$
(iii) Decision & Independence (5 Marks)

Prediction: Classified as Spam.

Independence Assumption: Assumes the presence of the word "Offer" gives zero information about "Win" once class is known ($P(\text{Offer}, \text{Win} \mid C) = P(\text{Offer} \mid C)P(\text{Win} \mid C)$). In reality words co-occur, but Naïve Bayes provides optimal ranking.

CT-2 · Question 2 KNN Customer Spending (Euclidean vs Manhattan) (20 Marks)
Question Statement:
Given 5 training customers: C1(20,5,Low), C2(25,7,Low), C3(50,20,High), C4(55,22,High), C5(30,10,Low).
Query point: $\mathbf{X} = (40, 15)$.
(a) Compute Euclidean distances (5M)
(b) Predict class for $K=3$ (5M)
(c) Recalculate with Manhattan metric and compare (5M)
(d) Explain feature scaling and $K$ choice (3M)
(e) Real-world application of KNN (2M)

Solution:

(a) Euclidean Distance to Query $(40, 15)$ (5 Marks)
  • $d_E(C1) = \sqrt{(40-20)^2 + (15-5)^2} = \sqrt{400 + 100} = \sqrt{500} \approx \mathbf{22.36}$
  • $d_E(C2) = \sqrt{(40-25)^2 + (15-7)^2} = \sqrt{225 + 64} = \sqrt{289} = \mathbf{17.00}$
  • $d_E(C3) = \sqrt{(40-50)^2 + (15-20)^2} = \sqrt{100 + 25} = \sqrt{125} \approx \mathbf{11.18}$
  • $d_E(C4) = \sqrt{(40-55)^2 + (15-22)^2} = \sqrt{225 + 49} = \sqrt{274} \approx \mathbf{16.55}$
  • $d_E(C5) = \sqrt{(40-30)^2 + (15-10)^2} = \sqrt{100 + 25} = \sqrt{125} \approx \mathbf{11.18}$
(b) Predict Class for $K=3$ (5 Marks)

Ascending rank of Euclidean distances:

  1. C3: $d_E = 11.18 \implies \text{Class: High}$
  2. C5: $d_E = 11.18 \implies \text{Class: Low}$
  3. C4: $d_E = 16.55 \implies \text{Class: High}$

Vote Tally: $2 \text{ High}$ vs $1 \text{ Low} \implies$ Predicted Class: High Spender.

(c) Manhattan Distance Recalculation (5 Marks)
  • $d_M(C1) = |40-20| + |15-5| = 20 + 10 = \mathbf{30}$
  • $d_M(C2) = |40-25| + |15-7| = 15 + 8 = \mathbf{23}$
  • $d_M(C3) = |40-50| + |15-20| = 10 + 5 = \mathbf{15}$
  • $d_M(C4) = |40-55| + |15-22| = 15 + 7 = \mathbf{22}$
  • $d_M(C5) = |40-30| + |15-10| = 10 + 5 = \mathbf{15}$

Top 3 neighbors under Manhattan: $\{C3, C5, C4\}$. Vote tally is still $2 \text{ High}$ vs $1 \text{ Low}$. Prediction is invariant: High Spender.

Jan 2025 · Question 4 Restaurant Recommendation System via KNN (20 Marks)
Question Statement:
A food delivery app recommends restaurants using KNN based on cuisine, user ratings, cost, and proximity. Explain how KNN works, effect of K, compare Euclidean vs Manhattan distances, and suggest evaluation metrics. (20 Marks)

Solution:

1. How KNN Operates in Recommendation (4 Marks)

KNN represents each restaurant as an encoded feature vector $\mathbf{x} = [x_{\text{cuisine}}, x_{\text{rating}}, x_{\text{cost}}, x_{\text{distance}}]^T$. Given user preference query $\mathbf{q}$, it calculates pairwise distance to all restaurants, selects $K$ nearest neighbors, and ranks by distance-weighted ratings: $w_i = \frac{1}{d(\mathbf{q}, \mathbf{x}_i) + \epsilon}$.

2. Choice of $K$ (5 Marks)
  • Small $K$ ($K=1$): Highly volatile recommendations; can suggest a terrible restaurant just because one idiosyncratic user rated it 5 stars.
  • Large $K$ ($K \to N$): Recommends generic popular fast-food chains to all users, ignoring individual niche taste.
3. Euclidean vs Manhattan Distance in Food Delivery (5 Marks)

Manhattan Distance ($L_1$) is superior: Delivery routes follow city street grid networks (taxicab geometry), not straight-line flight paths. Furthermore, $L_1$ is less distorted by luxury restaurants with outlier cost values.

4. Evaluation Metrics for Recommendations (6 Marks)
  1. Precision@K: Proportion of top-$K$ recommended restaurants that the user actually clicked or ordered from.
  2. Mean Reciprocal Rank (MRR): Evaluates where the first relevant restaurant appears in the list ($1/\text{rank}$).
  3. Normalized Discounted Cumulative Gain (NDCG@K): Weights highly relevant recommendations higher up in the list.

09. Interactive Offline KNN & Distance Calculator

Compute distances between a query point and training points to verify neighborhood ranking under Euclidean and Manhattan norms.

Click button to run KNN classification on training dataset.

10. Active Recall Self-Test Quiz

Answer the questions below to evaluate progress (0/4 answered).
1. What does the "Naïve" in Naïve Bayes refer to?
Correct: (b) It assumes $P(\mathbf{x} \mid C) = \prod P(x_j \mid C)$, which is rarely true in nature but drastically simplifies parameter estimation.
2. Why is Laplace smoothing used in Naïve Bayes text classification?
Correct: (c) Adding pseudo-counts ($\frac{\text{count}+1}{\text{total}+K}$) eliminates catastrophic zero-probability multipliers.
3. What happens to a KNN classifier when $K=1$?
Correct: (a) $K=1$ forms Voronoi cells around every training sample, creating jagged boundaries vulnerable to outliers.
4. Why is Manhattan distance preferred over Euclidean distance in urban food delivery apps?
Correct: (b) Manhattan ($L_1$) measures orthogonal grid traversal $|x_1 - x_2| + |y_1 - y_2|$, matching actual street travel.

11. Exam Hall Answer Sheet Presentation Checklist

1. State Bayes' Formula & Class Priors Explicitly

Write $P(C_k \mid \mathbf{x}) \propto P(C_k)\prod P(x_j \mid C_k)$. Write $P(\text{Yes}) = 5/10$, $P(\text{No}) = 5/10$.

2. Draw Complete Conditional Likelihood Table

Draw the table showing counts and fractions for every attribute value before multiplying.

3. Show Both Joint Likelihood and Normalized Posterior

Do not stop at $0.024$ and $0.072$. Always calculate evidence $P(\mathbf{x}) = 0.096$ and state final posteriors: $25\%$ vs $75\%$.

4. Provide Real-World Intuition for the Decision

Explain WHY the car was predicted Not Stolen: SUV and Domestic outweighed Red by 3 to 1.

5. For KNN, Show Square Roots and Sorted Rank Table

Write $\sqrt{500} \approx 22.36$, $\sqrt{125} \approx 11.18$. Draw an explicit table sorting neighbors from Rank 1 to Rank 5.

6. Call Out Bias-Variance for Choice of $K$

Mention that $K=1 \implies$ High Variance (Overfitting) and $K \to N \implies$ High Bias (Underfitting).