CT-2
Exam - Cycle Test - II
Date - 24/10/26
Question 1 (20 Marks)
Question Statement
- i. Apply the K-Nearest Neighbor (KNN) algorithm to a given dataset of your choice (you may assume a small dataset). Demonstrate how the classification is performed for a new test sample when k = 5. Show all distance calculations, neighbour selection, and final class prediction. (10 Marks)
- ii. Analyze the differences among Gaussian, Multinomial, and Bernoulli Naïve Bayes classifiers. Using a real-world scenario (e.g., email classification, sensor data, or text classification), justify which Naïve Bayes variant is most suitable and why. (10 Marks)
Solution 1 (20 Marks)
i. K-Nearest Neighbor (KNN) Algorithm Classification with (10 Marks)
1. Problem Formulation & Training Dataset
Let the training dataset represent a credit risk assessment problem with two normalized features: Age Ratio () and Income Ratio (), predicting credit default risk ():
| Sample ID () | Feature | Feature | True Class () |
|---|---|---|---|
| 1.0 | 2.0 | Low Risk (0) | |
| 2.0 | 1.0 | Low Risk (0) | |
| 2.0 | 3.0 | Low Risk (0) | |
| 3.0 | 2.0 | Low Risk (0) | |
| 3.0 | 4.0 | Low Risk (0) | |
| 5.0 | 5.0 | High Risk (1) | |
| 5.0 | 7.0 | High Risk (1) | |
| 6.0 | 4.0 | High Risk (1) | |
| 6.0 | 6.0 | High Risk (1) | |
| 7.0 | 5.0 | High Risk (1) |
2. New Test Query Sample
Let the unlabelled query point be:
3. Step 1: Distance Calculation
Compute the Euclidean distance for all 10 training instances:
4. Step 2: Neighbor Ranking and Selection for
Sort training instances in ascending order of distance:
| Rank | Training Point | Coordinates | Euclidean Distance | Class Label () | Selected in ? |
|---|---|---|---|---|---|
| 1 | Low Risk (0) | Yes | |||
| 2 | Low Risk (0) | Yes | |||
| 3 | Low Risk (0) | Yes | |||
| 4 | High Risk (1) | Yes | |||
| 5 | High Risk (1) | Yes | |||
| 6 | Low Risk (0) | No | |||
| 7 | Low Risk (0) | No | |||
| 8 | High Risk (1) | No | |||
| 9 | High Risk (1) | No | |||
| 10 | High Risk (1) | No |
5. Step 3: Majority Voting & Final Class Prediction
Among the nearest neighbors :
- Votes for Low Risk (0):
- Votes for High Risk (1):
Applying the standard majority vote rule:
ii. Comparison of Naïve Bayes Variants and Real-World Application (10 Marks)
1. Comparative Analysis Matrix
| Feature Dimension | Gaussian Naïve Bayes | Multinomial Naïve Bayes | Bernoulli Naïve Bayes |
|---|---|---|---|
| Input Data Type | Continuous / Real-valued features () | Discrete count data / Term Frequencies () | Binary indicator flags () |
| Likelihood Model | Normal distribution: | Multinomial distribution: | Multivariate Bernoulli: |
| Feature Representation | Mean and Variance | Token counts / Word frequencies (Bag-of-Words) | Word presence (1) or absence (0) |
| Penalty for Absence | Not applicable | Ignores zero-count terms (frequency ) | Explicitly penalizes absent non-occurring words |
| Smoothing Requirement | Variance smoothing (epsilon added to ) | Laplace / Lidstone smoothing () | Laplace smoothing () |
2. Real-World Scenario: Email Spam Classification
- The Problem: Classifying incoming emails as Spam () or Ham ().
- Candidate Comparison:
- Gaussian NB: Poor fit because vocabulary features are sparse count tokens, not normally distributed continuous variables.
- Bernoulli NB: Only tracks whether a keyword (e.g., "lottery", "urgent") appears or not. It cannot differentiate an email containing the word "offer" once from an aggressive spam email repeating "offer" 25 times.
- Multinomial NB (Selected Winner):
- Models the exact integer frequency of each token in the document using Bag-of-Words (or TF-IDF).
- Heavily penalizes repetitive spam keyword stuffing.
- Scales robustly to large vocabularies () via Laplace smoothing:
- Justification: Multinomial Naïve Bayes is the most suitable variant for full-text document classification because word occurrence frequency directly correlates with semantic intent and spam probability.
Examiner's Note
In part (i), state the Euclidean distance formula, rank all 10 distances in ascending order, identify the top 5 neighbors, and show the vote tally. In part (ii), write out the three likelihood formulas and justify Multinomial NB for full-length text versus Bernoulli NB for short snippets.
Question 2 (20 Marks)
Question Statement
Explain the concept of decision tree classifier and Construct Decision tree for the given dataset using Information gain and Entropy. How decision tree handles the overfitting? (20 marks)
| Day | Outlook | Temperature | Humidity | Wind | Play Golf |
|---|---|---|---|---|---|
| D1 | Sunny | Hot | High | Weak | No |
| D2 | Sunny | Hot | High | Strong | No |
| D3 | Overcast | Hot | High | Weak | Yes |
| D4 | Rain | Mild | High | Weak | Yes |
| D5 | Rain | Cool | Normal | Weak | Yes |
| D6 | Rain | Cool | Normal | Strong | No |
| D7 | Overcast | Cool | Normal | Strong | Yes |
| D8 | Sunny | Mild | High | Weak | No |
| D9 | Sunny | Cool | Normal | Weak | Yes |
| D10 | Rain | Mild | Normal | Weak | Yes |
Solution 2 (20 Marks)
1. Concept of Decision Tree Classifier (4 Marks)
A Decision Tree is a non-parametric supervised learning algorithm that recursively partitions the feature space into axis-aligned rectangular regions using a greedy top-down heuristic (such as ID3 or C4.5).
- Root & Internal Nodes: Test conditions on specific input attributes.
- Branches: Outcomes of the test conditions.
- Leaf Nodes: Terminal class predictions (assigned via majority vote of instances reaching that node).
2. Decision Tree Construction Using Entropy and Information Gain (10 Marks)
Mathematical Governing Formulas:
- Shannon Entropy ():
- Information Gain ():
Step 1: Total Dataset Entropy ()
Total records : (D3, D4, D5, D7, D9, D10) and (D1, D2, D6, D8).
Step 2: Information Gain for All Candidate Attributes at Root Node
1. Attribute: Outlook (Values: Sunny, Overcast, Rain)
- Overcast ( samples: D3, D7): (Completely pure)
- Sunny ( samples: D1, D2, D8, D9):
- Rain ( samples: D4, D5, D6, D10):
- Expected Entropy:
- Information Gain:
2. Attribute: Humidity (Values: High, Normal)
- High ( samples: D1, D2, D3, D4, D8):
- Normal ( samples: D5, D6, D7, D9, D10):
- Expected Entropy:
- Information Gain:
3. Attribute: Temperature (Values: Hot, Mild, Cool)
- Hot ( samples: D1, D2, D3):
- Mild ( samples: D4, D8, D10):
- Cool ( samples: D5, D6, D7, D9):
- Expected Entropy:
- Information Gain:
4. Attribute: Wind (Values: Weak, Strong)
- Weak ( samples: D1, D3, D4, D5, D8, D9, D10):
- Strong ( samples: D2, D6, D7):
- Expected Entropy:
- Information Gain:
Summary of Root Node Gains:
| Attribute | Remainder Entropy | Information Gain | Decision |
|---|---|---|---|
Outlook | bits | bits | Selected as Root (Maximum Gain) |
Humidity | bits | bits | Rejected |
Temperature | bits | bits | Rejected |
Wind | bits | bits | Rejected |
Step 3: Expanding the Branches
- Branch 1:
Outlook = Overcast(D3, D7): Both samples are Pure Leaf Node: Play Golf = Yes. - Branch 2:
Outlook = Sunny(D1, D2, D8, D9): EvaluateHumidityon this subset:- (D1, D2, D8): all are Pure Leaf Node: Play Golf = No.
- (D9): sample is Pure Leaf Node: Play Golf = Yes.
- (Complete separation).
- Branch 3:
Outlook = Rain(D4, D5, D6, D10): EvaluateWindon this subset:- (D4, D5, D10): all are Pure Leaf Node: Play Golf = Yes.
- (D6): sample is Pure Leaf Node: Play Golf = No.
- (Complete separation).
Constructed Decision Tree Architecture:
3. How Decision Trees Handle Overfitting (6 Marks)
Unconstrained decision trees grow until every leaf node is pure, capturing sample-specific noise and outliers (high variance / overfitting). Decision trees mitigate overfitting via two primary mechanisms:
1. Pre-Pruning (Early Stopping Constraints)
Halts tree growth during construction if specific threshold criteria are violated:
max_depth: Limits tree depth to prevent deep, isolated decision paths.min_samples_split: Enforces a minimum number of samples required to consider splitting an internal node (e.g., ).min_samples_leaf: Mandates that leaf nodes contain at least instances (e.g., ).min_impurity_decrease: Rejects splits that yield an Information Gain below a threshold .
2. Post-Pruning (Cost-Complexity Pruning / Minimal Error Pruning)
Allows the tree to grow to full depth, then prunes non-essential subtrees bottom-up using a complexity penalty: where is the misclassification error, is the number of terminal leaf nodes, and is the regularization parameter (tuned via cross-validation). If removing a subtree causes an increase in error smaller than , the branch is collapsed into a single leaf.
Examiner's Note
Calculate exact base entropy bits for the 10 samples (). Notice that Outlook achieves maximum gain ( bits). For the second half, explicitly contrast Pre-Pruning (early stopping hyperparameters) with Post-Pruning (Cost-Complexity Pruning ).
Question 3 (20 Marks)
Question Statement
- i. Differentiate Bagging and Boosting techniques in the machine learning model. Discuss briefly the Adaboost algorithm with suitable example (10 Marks)
- ii. Describe the random forest algorithm with example and justify the hyper parameter importance? (10 Marks)
Solution 3 (20 Marks)
i. Bagging vs. Boosting and the AdaBoost Algorithm (10 Marks)
1. Comparative Analysis: Bagging vs. Boosting
| Dimension | Bagging (Bootstrap Aggregating) | Boosting (Sequential Ensemble) |
|---|---|---|
| Model Generation | Parallel & Independent: Base estimators are trained concurrently on bootstrap samples. | Sequential & Dependent: Base learners are trained iteratively; each model corrects preceding errors. |
| Primary Goal | Variance Reduction (stabilizes high-variance models like deep decision trees). | Bias Reduction (converts weak learners like shallow decision stumps into a strong ensemble). |
| Sample Weighting | Equal probability weighting () for all training instances. | Adaptive sample weights: Misclassified instances receive higher weights in subsequent iterations. |
| Aggregation Rule | Simple uniform voting (classification) or uniform averaging (regression). | Weighted voting: Estimators with lower training error receive higher voting weight (). |
| Noise Sensitivity | Robust to noisy instances and outliers. | Highly sensitive to outliers (aggressively overfits mislabelled noise). |
2. The AdaBoost (Adaptive Boosting) Algorithm
AdaBoost combines an ensemble of weak base classifiers (typically single-split decision stumps, ) into a weighted voting sum:
Algorithmic Steps:
- Initialize Weights: Assign uniform sample weights to observations:
- Iterative Model Fitting (for to ):
- Fit base classifier using sample weights .
- Compute weighted training error rate :
- Compute estimator voting weight : (If ; as error approaches 0, ).
- Update Sample Weights for Next Iteration: (Misclassified samples have multiplied by , scaling their importance up).
- Renormalize weights so .
Concrete Numerical Example:
For samples with initial weights , let stump misclassify 2 samples (): The 2 misclassified samples have weights multiplied by , while the 8 correctly classified samples have weights multiplied by , forcing the next stump to focus on the 2 difficult samples.
ii. Random Forest Algorithm and Hyperparameter Importance (10 Marks)
1. Algorithmic Overview
Random Forest is a bagging-based ensemble that introduces a second layer of stochasticity—Random Feature Subspacing—to decorrelate individual trees:
Two Layers of Randomness:
- Bootstrap Resampling: Each tree is trained on an independent sample of size drawn with replacement ( unique instances, leaving Out-of-Bag (OOB) samples for unbiased validation).
- Random Feature Subspacing: At every internal node split, only a random subset of features (out of total ) is considered.
Ensemble Variance Equation:
The variance of an ensemble of trees with pairwise correlation is:
As , the second term approaches , leaving . Random feature subspacing reduces (tree correlation), driving overall ensemble variance down without inflating bias.
2. Key Hyperparameters and Their Technical Significance
n_estimators(Number of Trees, ):- Role: Controls ensemble stability. Unlike boosting or deep nets, increasing in Random Forest never causes overfitting; it monotonically reduces variance until out-of-bag error plateaus (typically ).
max_features():- Role: Size of the random feature subset evaluated at each split.
- Impact: Smaller reduces tree correlation (lowering variance) but increases individual tree bias. Standard default: for classification and for regression.
max_depth&min_samples_split:- Role: Regulates individual tree growth. Allowing deep trees provides low bias, while the ensemble voting layer eliminates the variance.
bootstrap(Boolean) &oob_score:- Role: Enables Out-of-Bag validation, providing a free cross-validation estimate without needing a separate validation holdout split.
Examiner's Note
Write the ensemble variance formula to explain why Random Forest decorrelates trees via max_features = sqrt(p). For AdaBoost, state the weight update equation and voting weight .