January 2025
Exam - Semester Examination
Session - January 2025
Question 1 (20 Marks)
Question Statement
- i) Consider a dataset where the independent variable X represents the number of study hours, and the dependent variable Y represents exam scores: Explain the process of deriving the simple linear regression equation. Describe the mathematical steps to calculate the slope and intercept of the regression line. Interpret the regression line in the context of predicting exam scores based on study hours. (10 Marks)
- ii) Define the concepts of overfitting and underfitting in the context of predicting students' academic performance. Discuss how they can impact the reliability of the prediction model. (5 Marks)
- iii) Identify and explain commonly used evaluation metrics for regression models in the context of assessing prediction accuracy for student exam scores. Discuss why each metric is important for evaluating model performance. (5 Marks)
Solution 1 (20 Marks)
(i) Derivation and Interpretation of Simple Linear Regression (10 Marks)
1. Model Setup
Let denote the number of study hours (independent variable) and denote the exam score (dependent variable). Given observations , the simple linear regression model is:
The predicted exam score is:
where is the intercept and is the slope. The residual error is .
2. Mathematical Derivation via Ordinary Least Squares (OLS)
The OLS objective minimizes the Residual Sum of Squares (RSS), :
Step A: Partial Derivative with respect to Intercept ()
Set the first partial derivative to zero:
where and .
Step B: Partial Derivative with respect to Slope ()
Set the second partial derivative to zero:
Substitute Equation 1 () into Equation 2:
Solving for :
3. Contextual Interpretation
- Intercept (): The baseline expected exam score for a student who logs zero study hours (). It reflects prior knowledge or innate aptitude.
- Slope (): The expected change in exam score per additional hour of study. If , each additional study hour increases the predicted score by marks.
(ii) Overfitting and Underfitting in Student Performance Prediction (5 Marks)
- Underfitting (High Bias, Low Variance):
- Definition: The model is too simplistic to capture the true underlying pattern (e.g., fitting a horizontal line or linear line when study returns diminish).
- Characteristics: High training error and high test error.
- Impact on Reliability: The model fails to recognize legitimate gains from studying, producing uniform predictions that miss at-risk students.
- Overfitting (Low Bias, High Variance):
- Definition: The model is overly complex and memorizes noise/outliers in the training set (e.g., high-degree polynomial fitting a student who fell ill during the exam).
- Characteristics: Near-zero training error but high test error.
- Impact on Reliability: Unstable predictions that oscillate wildly on new student cohorts, making the model untrustworthy for academic advising.
(iii) Commonly Used Regression Evaluation Metrics (5 Marks)
- Mean Absolute Error (MAE): Importance: Directly measures average prediction error in original score units (marks). It treats all errors linearly and is robust to outliers.
- Mean Squared Error (MSE): Importance: Penalizes large errors quadratically (). Essential when a large prediction miss (e.g., predicting 80 for a student scoring 30) is unacceptable.
- Root Mean Squared Error (RMSE): Importance: Combines the outlier sensitivity of MSE with the interpretable scale of marks. If , large individual prediction errors are present.
- Coefficient of Determination (): Importance: Scale-independent metric indicating the proportion of variance in exam scores explained by study hours ().
Examiner's Note
In part (i), state the OLS loss function explicitly, set partial derivatives to zero, and solve the normal equations algebraically. In part (iii), contrast MAE (linear penalty, outlier robust) with RMSE (quadratic penalty, outlier sensitive).
Question 2 (20 Marks)
Question Statement
A retail analytics company is developing a machine learning model to predict customer purchasing behavior. The goal is to classify customers into three spending categories: "low spender," "moderate spender," and "high spender." The dataset includes features such as monthly income, number of purchases, and average purchase value. Explain how Logistic Regression could be applied to estimate the probability of a customer being a "high spender." Describe the process of converting the linear regression equation into a sigmoid function and interpreting the resulting probability values for classifying customers. Since there are three categories ("low spender," "moderate spender," and "high spender"), explain how Logistic Regression can be adapted for multi-class classification. Describe methods like One-vs-Rest (OvR) or Softmax Regression for handling multiple classes. (20 Marks)
Solution 2 (20 Marks)
1. Estimating "High Spender" Probability via Logistic Regression (4 Marks)
Let represent Monthly Income, Number of Purchases, and Average Purchase Value. Define the binary target:
A standard linear equation produces unbounded outputs , which violates probability constraints (). Logistic regression maps through a sigmoid function to produce calibrated probabilities:
2. Derivation of the Sigmoid Function from Odds and Logit (8 Marks)
To convert the unbounded linear combination into a bounded probability :
- Odds: The ratio of the probability of being a high spender to not being one:
- Log-Odds (Logit): Taking the natural logarithm maps odds to the full real line :
- Inversion to Sigmoid: Exponentiate and solve for :
Probability Interpretation:
- is the posterior probability that the customer is a high spender.
- Classification Rule: Using a decision threshold :
3. Multi-Class Adaptation: One-vs-Rest and Softmax Regression (8 Marks)
To classify customers into categories (), logistic regression is extended using two standard methods:
Method A: One-vs-Rest (OvR) / One-vs-All
- Architecture: Train independent binary logistic classifiers:
- Classifier 1 (): Low Spender vs. Rest ()
- Classifier 2 (): Moderate Spender vs. Rest ()
- Classifier 3 (): High Spender vs. Rest ()
- Prediction: Assign the input to the class with the highest probability score:
- Key Trait: Simple to implement and parallelize; probabilities require post-hoc normalization () to sum to 1.
Method B: Softmax Regression (Multinomial Logistic Regression)
- Architecture: Generates a linear score for each class simultaneously and applies the Softmax function:
- Key Traits:
- Inherently satisfies probability axioms: and .
- Directly models mutually exclusive classes using Categorical Cross-Entropy loss:
Examiner's Note
Show the three-step derivation of the sigmoid function: Odds Logit Sigmoid inversion. When comparing OvR and Softmax, highlight that Softmax models mutually exclusive categories jointly, whereas OvR trains independent binary hyperplanes.
Question 3 (20 Marks)
Question Statement
A telecommunications company is building a machine learning model to predict customer chum (whether a customer will switch to another service provider). The dataset includes customer demographics, usage patterns, and support interaction history. The team wants to ensure the model generalizes well to new data and avoids overfitting. Explain how cross-validation can be utilized to assess the performance of the chum prediction model and discuss the purpose of cross-validation and how it helps in improving the generalization of the model to unseen data. (20 Marks)
Solution 3 (20 Marks)
1. Purpose of Cross-Validation (5 Marks)
Cross-validation (CV) provides an unbiased empirical estimate of expected generalization error on unseen data.
- Why Holdout (Simple Train-Test Split) Fails: A single split yields high estimator variance depending on which samples fall into the test set by random chance, and it wastes valuable training data in small cohorts.
- Core Role: By systematically rotating data so that every sample is used for validation exactly once, CV ensures the model does not memorize training noise and provides a reliable measure of out-of-sample performance.
2. Utilizing Stratified K-Fold Cross-Validation in Telecom Churn (8 Marks)
A. Stratified -Fold Cross-Validation (Mandatory Architecture)
Telecom churn typically suffers from class imbalance (e.g., churners, retained). Standard random -fold can produce validation folds with very few or zero churn cases.
Stratified -Fold partitions the dataset into disjoint folds (typically or ) while strictly preserving the full dataset's class ratio in every fold:
Execution Steps:
- Divide data into stratified folds.
- For to :
- Train on folds.
- Validate on the held-out -th fold to compute metric .
- Compute aggregate generalization performance:
B. Data Leakage Prevention
Feature transformers (e.g., StandardScaler, imputation) must be fitted strictly inside the training folds and applied out-of-fold to the validation fold to avoid data leakage.
3. How Cross-Validation Improves Generalization & Prevents Overfitting (7 Marks)
- Detects High Variance (Overfitting): A large gap between training performance () and cross-validation score () flags overfitting, signaling the need for regularization (L2 penalty, tree pruning).
- Robust Hyperparameter Selection: Optimal hyperparameters (e.g., regularization parameter , tree depth) are chosen based on average out-of-fold performance across all folds rather than a single lucky split.
- Informs Early Stopping: Evaluates when model iterations begin overfitting validation folds without touching the test set.
- Aligns with Imbalanced Metrics: Allows tuning for ROC-AUC, PR-AUC, and -score rather than raw classification accuracy, which is misleading under class imbalance.
Examiner's Note
Explicitly name Stratified -Fold as the mandatory cross-validation strategy for customer churn due to class imbalance. Mentioning data leakage prevention (fitting scalers only on training folds) demonstrates strong practical rigor.
Question 4 (20 Marks)
Question Statement
A food delivery app is building a recommendation system to suggest restaurants to users based on preferences and location. The dataset includes features like cuisine type, user ratings, average cost, and proximity. The team decides to use the K-Nearest Neighbors (KNN) algorithm. Explain how the KNN algorithm works in this context and discuss how the choice of K affects model performance, including challenges with very small or large K values. Describe the role of distance metrics, comparing Euclidean and Manhattan distances, and recommend the most suitable metric for this scenario. Finally, suggest evaluation metrics to assess the model's effectiveness in recommending relevant restaurants, justifying their importance in this context. (20 Marks)
Solution 4 (20 Marks)
1. How KNN Works in Restaurant Recommendation (4 Marks)
K-Nearest Neighbors is a non-parametric, instance-based lazy learner. It does not train an explicit model; instead, it stores feature vectors and defers computation until inference:
- Feature Vector: Each restaurant is encoded as .
- Distance Calculation: For a user query , compute the pairwise distance to all restaurants.
- Neighbor Selection: Identify the smallest distances ().
- Aggregation & Ranking: Aggregate neighbor ratings via distance-weighted scoring () to rank and recommend the top restaurants.
2. Effect of the Choice of (Bias-Variance Trade-off) (5 Marks)
- Very Small ( or ):
- Profile: Low bias, high variance (Overfitting).
- Challenges: Extreme sensitivity to noise, anomalies, or a newly registered restaurant with a single fake 5-star review. Decision boundaries are jagged and unstable.
- Very Large ():
- Profile: High bias, low variance (Underfitting).
- Challenges: Neighborhood incorporates geographically distant or irrelevant restaurants. Recommendations collapse to the globally most frequent restaurant category (e.g., mass-market fast food), destroying personalization.
- Optimal : Typically set to and tuned via cross-validation using odd values to avoid voting ties.
3. Distance Metrics: Euclidean vs. Manhattan (6 Marks)
| Dimension | Euclidean Distance () | Manhattan Distance () |
|---|---|---|
| Formula | ||
| Geometry | Straight-line distance ("as the crow flies") | Grid-based path along orthogonal axes |
| Outlier Sensitivity | Squares differences; sensitive to large discrepancies | Linear penalty; significantly more robust |
Recommendation for this Scenario:
- Manhattan Distance () is recommended:
- In urban delivery, couriers travel along street grids rather than flying straight lines; approximates travel time more realistically.
- Its linear penalty prevents extreme values in cost from dominating ratings and proximity.
- Mandatory Preprocessing (Feature Scaling): Because proximity (km), rating (), and cost (currency) use completely different units, Min-Max scaling or Z-score standardization is mandatory before computing distances.
4. Recommendation Evaluation Metrics (5 Marks)
- Precision@K: Importance: Directly measures whether restaurants visible on the user's mobile screen are relevant.
- Recall@K: Importance: Measures coverage of the user's preferences across the local delivery zone.
- NDCG@K (Normalized Discounted Cumulative Gain): Importance: Evaluates ranking order, heavily rewarding placing the most relevant restaurants at rank 1-3.
- Click-Through Rate (CTR) & Order Conversion Rate: Business metrics assessing whether users actually click and place orders from recommendations.
Examiner's Note
Highlight the bias-variance trade-off for ( overfitting, noise sensitive; underfitting, majority class collapse). Emphasize that feature normalization is strictly required before running KNN on heterogeneous features.
Question 5 (20 Marks)
Question Statement
Consider the car theft prediction problem with the following attributes: Color (Categorical: Red, Blue, Black, etc.), Type (Categorical: SUV, Sedan, Truck, etc.), Origin (Categorical: Domestic, Imported), and the target variable Stolen (Binary: Yes, No). Assume that no pair of features are dependent, and each feature has equal influence on the classification. For this task, describe the necessary preprocessing steps you would take before applying a classification algorithm to this dataset, including how you would handle categorical data and which encoding methods you would use. Then, suggest a suitable classification algorithm, justifying your choice based on the nature of the features and the target variable. After selecting an algorithm, implement the classification model and evaluate its performance using appropriate metrics. Finally, after training the model, predict whether a car with the following attributes (Color = Red, Type = SUV, Origin = Domestic) is stolen or not, and explain how the prediction is made and interpret the result. (20 Marks)
| Example No. | Color | Type | Origin | Stolen? |
|---|---|---|---|---|
| 1 | Red | Sports | Domestic | Yes |
| 2 | Red | Sports | Domestic | No |
| 3 | Red | Sports | Domestic | Yes |
| 4 | Yellow | Sports | Domestic | No |
| 5 | Yellow | Sports | Imported | Yes |
| 6 | Yellow | SUV | Imported | No |
| 7 | Yellow | SUV | Imported | Yes |
| 8 | Yellow | SUV | Domestic | No |
| 9 | Red | SUV | Imported | No |
| 10 | Red | Sports | Imported | Yes |
Solution 5 (20 Marks)
1. Preprocessing Steps and Categorical Encoding (4 Marks)
- Data Structure: 10 records with three categorical predictors (Color, Type, Origin) and a binary target (Stolen ).
- Handling Categorical Data:
- One-Hot Encoding: Generates binary indicator vectors for linear/distance models to avoid imposing artificial ordinal relationships.
- Categorical Frequency Tables (Chosen): For probabilistic models like Naive Bayes, direct frequency tables capture probability distributions without expanding feature dimensions.
2. Algorithm Selection and Justification (3 Marks)
The most suitable algorithm is the Naive Bayes Classifier (Categorical Naive Bayes):
- "Assume that no pair of features are dependent": Directly satisfies the defining Conditional Independence Assumption:
- "Each feature has equal influence": Matches Naive Bayes' unweighted multiplicative likelihood formulation.
- Small Sample Size (): Decoupled parameter estimation prevents overfitting on small datasets.
3. Model Implementation (Frequency & Probability Estimation) (4 Marks)
Class Priors ():
Conditional Likelihoods:
| Attribute | Level | Stolen = Yes () | Stolen = No () | ||
|---|---|---|---|---|---|
| Color | Red | 3 | 2 | ||
| Yellow | 2 | 3 | |||
| Type | Sports | 4 | 2 | ||
| SUV | 1 | 3 | |||
| Origin | Domestic | 2 | 3 | ||
| Imported | 3 | 2 |
4. Model Evaluation on Training Data (4 Marks)
Confusion Matrix:
| Predicted Yes | Predicted No | Total | |
|---|---|---|---|
| Actual Yes | |||
| Actual No |
- Accuracy:
- Precision:
- Recall:
- -Score:
5. Prediction for Test Car: (5 Marks)
Step A: Compute Unnormalized Joint Probabilities
- For Stolen = Yes:
- For Stolen = No:
Step B: Evidence & Posterior Probabilities
- Evidence:
- Posterior Probabilities:
Final Decision and Interpretation:
- Prediction: The car is classified as NOT STOLEN ().
- Interpretation: Although the color Red correlates with theft (), both SUV ( vs. ) and Domestic ( vs. ) strongly indicate safety. Under the equal-influence independence assumption, the combined safety evidence outweighs the color evidence by a ratio ( vs. ).
Examiner's Note
Explicitly link the question statement ("no pair of features are dependent" and "equal influence") to Naive Bayes. Always show both unnormalized scores ( and ) and the normalized posteriors ( and ).
Question 6 (20 Marks)
Question Statement
A sports club wants to predict whether they should hold outdoor events based on weather conditions to improve turnout and satisfaction. They have historical data on past events, including details like outlook, temperature, humidity, wind, and whether the event was successful ("Yes" or "No"). Using this data, construct a decision tree model to help the sports club decide whether or not to hold an outdoor event. Describe the steps for selecting attributes, determining splitting criteria, and building the tree to reach a decision on whether they should "play" or "not play" under specific weather conditions. (20 Marks)
| Day | outlook | temperature | humidity | wind | Decision |
|---|---|---|---|---|---|
| 1 | sunny | hot | high | weak | No |
| 2 | sunny | hot | high | strong | No |
| 3 | overcast | hot | high | weak | Yes |
| 4 | rainfall | mild | high | weak | Yes |
| 5 | rainfall | cool | normal | weak | Yes |
| 6 | rainfall | cool | normal | strong | No |
| 7 | overcast | cool | normal | strong | Yes |
| 8 | sunny | mild | high | weak | No |
| 9 | sunny | cool | normal | weak | Yes |
| 10 | rainfall | mild | normal | weak | Yes |
| 11 | sunny | mild | normal | strong | Yes |
| 12 | overcast | mild | high | strong | Yes |
| 13 | overcast | hot | normal | weak | Yes |
| 14 | rainfall | mild | high | strong | No |
Solution 6 (20 Marks)
1. Splitting Criteria (Quinlan's ID3) (4 Marks)
- Entropy: Measures impurity:
- Information Gain: Measures reduction in entropy after splitting on attribute :
- Criterion: Select the attribute with the highest Information Gain at each node.
2. Root Node Selection (: ) (6 Marks)
Total dataset entropy:
Information Gain for Each Candidate Attribute:
outlook:- ( samples: ):
- ( samples: ):
- ( samples: ):
humidity:- ( samples: ):
- ( samples: ):
wind:- ( samples: ): ; ( samples: ):
temperature:
Decision: outlook has the highest Information Gain ( bits) and is selected as the Root Node.
3. Expanding the Tree Branches (6 Marks)
Branch 1: outlook = overcast
- Samples (Days 3, 7, 12, 13): .
- Entropy is Pure Leaf Node: Play = Yes.
Branch 2: outlook = sunny
- Samples (Days 1, 2, 8, 9, 11): ().
- Evaluate remaining attributes:
- (Maximum possible).
humidity = high(Days 1, 2, 8): Leaf Node: Play = No.humidity = normal(Days 9, 11): Leaf Node: Play = Yes.
Branch 3: outlook = rainfall
- Samples (Days 4, 5, 6, 10, 14): ().
- Evaluate remaining attributes:
- (Maximum possible).
wind = weak(Days 4, 5, 10): Leaf Node: Play = Yes.wind = strong(Days 6, 14): Leaf Node: Play = No.
4. Final Decision Tree Architecture and Rules (4 Marks)
Operational Decision Rules:
Examiner's Note
Note that temperature is completely pruned from the tree because its Information Gain () is strictly dominated by outlook, humidity, and wind.
Question 7 (20 Marks)
Question Statement
Consider a dataset with two features: height (in cm) and weight (in kg) of individuals. You decide to use the K-means clustering algorithm to segment the dataset into two groups based on these features. What steps would you take before applying the algorithm, and how would you determine the optimal number of clusters (k) for this dataset? Discuss at least two methods to choose the value of k. After applying K-means, you find that Cluster 1 has a mean height of 160 cm and a mean weight of 55 kg, while Cluster 2 has a mean height of 180 cm and a mean weight of 75 kg. What can you infer about the individuals in each cluster? (20 Marks)
Solution 7 (20 Marks)
1. Preprocessing Steps Prior to K-Means (5 Marks)
- Feature Standardization (Z-score / Min-Max):
- Why: Height () and Weight () use different units and scales. Because K-Means relies on Euclidean distance (), unscaled features with larger numeric variance arbitrarily dominate cluster assignments.
- Remedy: Standardize to zero mean and unit variance ().
- Outlier Detection and Removal:
- K-Means updates centroids using the arithmetic mean (), which is sensitive to extreme values. Outliers should be removed via IQR or Z-score filtering.
- Smart Centroid Initialization (K-Means++):
- Initialize centroids probabilistically proportional to squared distance () to prevent poor local minima.
2. Determining the Optimal Number of Clusters () (8 Marks)
Method 1: The Elbow Method (Within-Cluster Sum of Squares - WCSS)
- Formula:
- Procedure:
- Run K-Means across a range of .
- Plot vs. . WCSS decreases monotonically as increases.
- Identify the elbow point—the value of where the rate of decrease abruptly slows (diminishing marginal returns).
Method 2: The Silhouette Analysis
- Formula: For each point : where is the mean intra-cluster distance and is the mean distance to the nearest neighboring cluster.
- Procedure:
- Compute the average silhouette score .
- Select the value of that maximizes with minimal negative scores.
3. Inference from the Resulting Clusters (7 Marks)
- Cluster 1 Centroid: Height = (), Weight =
- Cluster 2 Centroid: Height = (), Weight =
Key Demographic and Biometric Inferences:
- Both Clusters Represent Normal, Healthy Weights: Both BMIs ( and ) fall within the standard healthy range ().
- Segmentation by Physical Stature, Not Adiposity: The algorithm has separated individuals along the primary axis of overall physical height and skeletal frame size rather than body fat or metabolic condition.
- Demographic Profiles:
- Cluster 1: Shorter, lighter cohort (typically corresponds to adult females, adolescents, or individuals of petite stature).
- Cluster 2: Taller, heavier cohort (typically corresponds to adult males or individuals of large skeletal build).
Examiner's Note
Calculating the BMI for both centroids ( and ) provides quantitative proof that the clusters partition individuals by physical stature rather than body fat percentage.