Unit 3: Classification & Instance-Based Learning
Course - Machine Learning Algorithms (21CSC555J)
Assessment - Continuous Test 2 (CT-2)
Unit - Unit 3: Naïve Bayes & K-Nearest Neighbors
Total Weightage - 40 Marks (Question 1.a: 15 Marks; Question 1.b: 5 Marks; Question 2: 20 Marks)
Question 1.a: Naïve Bayes Spam Filtering (15 Marks)
Question Statement
An email filtering system uses Naïve Bayes to classify messages as Spam or Not Spam. Given the training dataset:
Training Dataset for Spam Classification
| Contains 'Offer' | Contains 'Win' | Spam | |
|---|---|---|---|
| E1 | Yes | Yes | Yes |
| E2 | No | Yes | Yes |
| E3 | Yes | No | No |
| E4 | No | No | No |
- i) Calculate the conditional probabilities (5 marks)
, , , . - ii) For a new email with "Offer = Yes, Win = Yes", compute (5 marks)
and - iii) Predict the class and briefly explain the independence assumption. (5 marks)
Solution 1.a
📝 Exam-Ready Answer (Structured for 15 Marks)
(i) Calculate Conditional Probabilities (5 Marks)
-
Step 1: Dataset Partitioning & Class Totals (1 Mark)
- Total number of training samples:
- Total Spam emails (): (Emails: E1, E2)
- Total Not Spam emails (): (Emails: E3, E4)
-
Step 2: General Formula for Maximum Likelihood Conditional Probability (1 Mark)
-
Step 3: Evaluate Conditional Probabilities for Spam Class (1.5 Marks)
- For feature 'Offer' = Yes: (Email E1 has Offer=Yes; E2 has Offer=No)
- For feature 'Win' = Yes: (Both emails E1 and E2 have Win=Yes)
-
Step 4: Evaluate Conditional Probabilities for Not Spam Class (1.5 Marks)
- For feature 'Offer' = Yes: (Email E3 has Offer=Yes; E4 has Offer=No)
- For feature 'Win' = Yes: (Neither E3 nor E4 has Win=Yes)
Conditional Probability Summary Table
| Feature () | Value | ||
|---|---|---|---|
| Contains 'Offer' | Yes | ||
| Contains 'Win' | Yes |
(ii) Compute Probabilities for New Email: (5 Marks)
-
Step 1: Compute Prior Class Probabilities (1 Mark)
-
Step 2: State Bayes' Posterior Formula with Conditional Independence (1 Mark)
-
Step 3: Calculate Unnormalized Joint Likelihoods (1.5 Marks)
-
For class Spam:
-
For class Not Spam:
-
-
Step 4: Compute Evidence (Marginal Probability ) (0.5 Marks)
-
Step 5: Normalize to Obtain Final Posterior Probabilities (1 Mark)
(iii) Class Prediction & Explanation of Independence Assumption (5 Marks)
-
Step 1: Class Prediction by Maximum A Posteriori (MAP) Rule (2 Marks)
- Conclusion: The new email is classified as Spam.
-
Step 2: Formal Statement of Class-Conditional Independence Assumption (1.5 Marks)
- The Naïve Bayes classifier assumes that all features are mutually conditionally independent given the class label :
- In this problem context, it assumes that the presence of the word 'Offer' is completely independent of the presence of the word 'Win', once we know whether the email is Spam or Not Spam.
-
Step 3: Real-World Validity & Trade-offs (1.5 Marks)
- Why it is "Naïve": In natural language, promotional keywords are strongly correlated (e.g., an email containing "Offer" is far more likely to also contain "Win"). Treating them as conditionally independent is mathematically unrealistic.
- Why it is preferred in practice: Despite this violated assumption, the classifier performs remarkably well because it only needs the correct probability ranking (), not perfectly calibrated probabilities. It reduces computational complexity from parameters to parameters, preventing overfitting on small training corpuses.
Question 1.b: Comparative Analysis of Classifiers on Medical Data (5 Marks)
Question Statement
A data scientist is working on three models for classifying medical test results:
- KNN ()
- Gaussian Naïve Bayes
- SVM with RBF kernel
Assume given is a small dataset with numeric features:
- a. Which algorithm handles non-linear boundaries best and why? (2 Marks)
- b. Which algorithm is most sensitive to irrelevant features? (1.5 Marks)
- c. Which algorithm performs better when data is small and has missing values? (1.5 Marks)
Solution 1.b
📝 Exam-Ready Answer (Structured for 5 Marks)
(a) Best Algorithm for Non-Linear Decision Boundaries (2 Marks)
- Selected Algorithm: Support Vector Machine (SVM) with RBF (Radial Basis Function) Kernel.
- Technical Justification:
- Kernel Trick: The RBF (Gaussian) kernel mathematically computes inner products in an infinite-dimensional Hilbert feature space:
- Linear Hyperplane Non-linear Boundary: A linear separating hyperplane constructed in this infinite-dimensional space maps back to smooth, arbitrarily complex, non-linear decision contours in the original input space.
- Superiority over KNN & Gaussian NB: While KNN can form piecewise non-linear boundaries, it suffers from noise and irregular boundary jaggedness. Gaussian Naïve Bayes can only construct linear or quadratic (ellipsoidal) boundaries under normal distributions. SVM with RBF provides the optimal margin and continuous non-linear separation.
(b) Algorithm Most Sensitive to Irrelevant Features (1.5 Marks)
- Selected Algorithm: K-Nearest Neighbors (KNN, ).
- Technical Justification:
- Uniform Distance Computation: KNN computes spatial proximity (e.g., Euclidean distance) across all feature dimensions uniformly:
- Curse of Dimensionality: Irrelevant or noisy features contribute random variance to the distance sum equally with relevant features. As irrelevant dimensions increase, all pairwise distances converge to the same value (), completely destroying the neighborhood structure.
- Comparison: SVM learns small or zero weights () for non-informative dimensions, and Naïve Bayes only computes feature-wise marginal products without distance coupling.
(c) Algorithm Performing Better with Small Datasets and Missing Values (1.5 Marks)
- Selected Algorithm: Gaussian Naïve Bayes.
- Technical Justification:
- Small Dataset Robustness (High Bias, Low Variance): With few samples, high-capacity models (SVM with RBF) are prone to severe overfitting, and KNN () suffers from sparse sample density. Gaussian Naïve Bayes requires estimating only two parameters per feature (mean and variance ), converging to its asymptotic error much faster with small sample sizes .
- Native Missing Value Handling (Marginalization): Naïve Bayes naturally handles missing feature values during inference by simply omitting the missing attribute from the conditional probability product:
In contrast, standard SVM and KNN cannot evaluate dot products or distance vectors when attributes contain
NaNwithout requiring synthetic imputation.
Comparative Summary Matrix
| Evaluation Criterion | KNN () | Gaussian Naïve Bayes | SVM (RBF Kernel) | Winner |
|---|---|---|---|---|
| Non-Linear Boundary | Piecewise, noisy | Quadratic / Ellipsoidal | Infinite-dimensional projection | SVM (RBF) |
| Irrelevant Features | Highly vulnerable (distance noise) | Moderate | Robust (max-margin regularization) | KNN (Most Sensitive) |
| Small + Missing Data | Fails distance computation | Optimal (rapid convergence + native omission) | Fails kernel computation | Gaussian NB |
Question 2: K-Nearest Neighbors Customer Spending Classification (20 Marks)
Question Statement
A company wants to classify new customers as "High Spender" or "Low Spender" based on their income and average monthly spending.
Training data:
| Customer | Income (₹1000s) | Spending (₹1000s) | Class |
|---|---|---|---|
| C1 | 20 | 5 | Low |
| C2 | 25 | 7 | Low |
| C3 | 50 | 20 | High |
| C4 | 55 | 22 | High |
| C5 | 30 | 10 | Low |
- (a) For a new customer with and , calculate the Euclidean distance from each training point. (5 Marks)
- (b) Predict the class when . Show all steps clearly. (5 Marks)
- (c) Recalculate distances using the Manhattan distance metric and compare the result. (5 Marks)
- (d) Explain: How feature scaling/normalization affects KNN results, and what happens when is too small or too large. (3 Marks)
- (e) Mention one real-world application where KNN is used and why it is preferred there. (2 Marks)
Solution 2
📝 Exam-Ready Answer (Structured for 20 Marks)
Let the query point for the new customer be: where represents Income (in ₹1000s) and represents Spending (in ₹1000s).
(a) Euclidean Distance Calculation (5 Marks)
-
Step 1: Formula Definition (1 Mark) The Euclidean distance ( norm) between and training point is:
-
Step 2: Individual Distance Computations (3 Marks)
-
For Customer C1 :
-
For Customer C2 :
-
For Customer C3 :
-
For Customer C4 :
-
For Customer C5 :
-
-
Step 3: Distance Summary Table (1 Mark)
| Customer | Income () | Spending () | Class | Sum of Squares | Euclidean Distance () | ||
|---|---|---|---|---|---|---|---|
| C1 | 20 | 5 | Low | 400 | 100 | 500 | |
| C2 | 25 | 7 | Low | 225 | 64 | 289 | |
| C3 | 50 | 20 | High | 100 | 25 | 125 | |
| C4 | 55 | 22 | High | 225 | 49 | 274 | |
| C5 | 30 | 10 | Low | 100 | 25 | 125 |
(b) Predict Class When (5 Marks)
- Step 1: Rank Distances in Ascending Order (1.5 Marks)
| Rank | Customer | Euclidean Distance () | Class Label | Included in ? |
|---|---|---|---|---|
| 1 | C3 | High | Yes | |
| 2 | C5 | Low | Yes | |
| 3 | C4 | High | Yes | |
| 4 | C2 | Low | No | |
| 5 | C1 | Low | No |
-
Step 2: Identify the Nearest Neighbors (1.5 Marks)
- Nearest Neighbor 1: C3 with Class = High
- Nearest Neighbor 2: C5 with Class = Low
- Nearest Neighbor 3: C4 with Class = High
-
Step 3: Majority Voting & Posterior Probability (1 Mark)
- Vote count for Class High: (from C3, C4)
- Vote count for Class Low: (from C5)
- Empirical class probability:
-
Step 4: Final Prediction Statement (1 Mark)
- By majority voting rule (), the new customer with and is predicted as:
(c) Recalculate Distances Using Manhattan Metric & Compare (5 Marks)
-
Step 1: Formula Definition (1 Mark) The Manhattan distance ( norm / Taxicab distance) is:
-
Step 2: Individual Computations (2 Marks)
- For C1 :
- For C2 :
- For C3 :
- For C4 :
- For C5 :
-
Step 3: Metric Comparison Table (1 Mark)
| Customer | Class | Euclidean Distance () | Euclidean Rank | Manhattan Distance () | Manhattan Rank |
|---|---|---|---|---|---|
| C3 | High | 1 (Tie) | 1 (Tie) | ||
| C5 | Low | 1 (Tie) | 1 (Tie) | ||
| C4 | High | 3 | 3 | ||
| C2 | Low | 4 | 4 | ||
| C1 | Low | 5 | 5 |
- Step 4: Analytical Comparison & Conclusion (1 Mark)
- Set Invariance: The set of nearest neighbors under Manhattan distance is identical: .
- Tally & Outcome: The majority vote remains vs .
- Conclusion: The prediction remains unchanged as High Spender. This demonstrates that the local neighborhood around query point is topologically stable across both and geometric norms.
(d) Theoretical Analysis: Feature Scaling & Choice of K (3 Marks)
-
Impact of Feature Scaling / Normalization (1.5 Marks)
- Problem of Dominance: Distance metrics (Euclidean and Manhattan) assume all feature axes are isotropic (equal weight per numeric unit). If one feature has a vastly larger scale (e.g., Annual Income in raw rupees: ₹40,000 to ₹55,000) compared to monthly spending (₹5 to ₹22), the difference in income will mathematically dominate the distance sum: This effectively reduces the 2D feature space to a 1D space, ignoring the spending feature.
- Remedy: Standardizing features using Min-Max Normalization () or Z-Score Standardization () ensures every feature contributes proportionally to the distance calculation.
-
Effects of Parameter Selection (1.5 Marks)
| Parameter Setting | Model Complexity | Bias vs Variance | Risk / Behavior |
|---|---|---|---|
| is too small () | Overly complex, jagged decision boundaries | Low Bias, High Variance | Highly vulnerable to training noise and outliers; easily leads to Overfitting. |
| is too large () | Overly smooth, rigid boundaries | High Bias, Low Variance | Ignores local spatial structure; degenerates into predicting the global majority class (Underfitting). |
- Rule of Thumb: Choose an odd value for in binary classification to prevent ties, commonly setting and tuning via cross-validation.
(e) Real-World Application of KNN (2 Marks)
-
Application Domain (1 Mark):
- E-Commerce & Streaming Collaborative Filtering Recommender Systems (e.g., Amazon product suggestions, Spotify playlist recommendations, or Netflix movie matching).
-
Why KNN is Preferred There (1 Mark):
- Instance-Based Simplicity (Lazy Learning): It requires no expensive training phase. New users and items can be ingested dynamically in real time without retraining a global model.
- Natural Neighborhood Intuition: Recommending items liked by users with similar consumption profiles (nearest neighbors in feature embedding space) is highly interpretable, intuitive, and effective without requiring complex parametric assumptions.