Logistic Regression, Metrics & Validation
Master the transformation from unbounded linear regression to bounded probabilities via the Sigmoid function, multi-class architectures, full confusion matrix derivations, the 99.5% Accuracy Paradox, PR-AUC vs ROC-AUC, and Stratified K-Fold CV.
01. Intuition & Concept Contrast
Why can't we use linear regression for classification? Linear regression predicts unbounded real numbers $z \in (-\infty, +\infty)$. Probabilities must strictly obey the Kolmogorov axioms: $P(Y=1 \mid \mathbf{x}) \in [0, 1]$.
Linear Output vs Probability Sigmoid
Linear Output ($z = \mathbf{w}^T\mathbf{x} + b$): Can predict $-4.2$ or $+15.8$. Meaningless as a probability; sensitive to extreme outliers that skew the decision boundary.
Sigmoid Function ($\sigma(z) = \frac{1}{1 + e^{-z}}$): Smooth S-shaped squashing curve that asymptotically maps $(-\infty, +\infty)$ strictly into $[0, 1]$. Thresholded at $0.5$ ($z=0$) to classify binary decisions.
Accuracy vs Precision/Recall
Accuracy ($\frac{TP+TN}{N}$): Misleading under class imbalance. In a $0.5\%$ fraud dataset, predicting 100% legitimate gives $99.5\%$ accuracy while missing every fraud case.
Precision & Recall: Precision ($\frac{TP}{TP+FP}$) measures alarm trustworthiness; Recall ($\frac{TP}{TP+FN}$) measures event coverage. Harmonic balance via $F_1$ or recall-weighted $F_2$.
ROC-AUC vs PR-AUC
ROC-AUC ($\text{TPR}$ vs $\text{FPR}$): The $\text{FPR} = \frac{FP}{TN + FP}$ denominator contains the enormous majority class ($TN$). A flood of false positives barely moves $\text{FPR}$, artificially inflating ROC-AUC.
PR-AUC (Precision vs Recall): Focuses exclusively on the positive minority class ($TP, FP, FN$). Excludes $TN$ entirely, exposing poor models on rare events.
Random K-Fold vs Stratified K-Fold
Standard Random K-Fold: Can produce validation folds containing zero positive churn/fraud instances due to random sampling.
Stratified K-Fold: Strictly preserves class proportion across every training and validation fold (e.g., exactly $15\%$ churners in each fold).
02. Derivation of Logistic Regression from Linear Regression
Guaranteed University Question (8-10 Marks). Deriving the Sigmoid formula step-by-step from the linear log-odds (logit).
Step-by-Step Derivation Protocol:
Step 1: The Probability Dilemma
Let $p = P(Y = 1 \mid \mathbf{x})$ denote the posterior probability of class 1. A linear equation $z = \mathbf{w}^T\mathbf{x} + b$ produces outputs $z \in (-\infty, +\infty)$, whereas probabilities must be bounded $p \in [0, 1]$.
Step 2: Odds Ratio Formulation
Define the Odds of an event as the ratio of probability of occurrence to probability of non-occurrence:
Step 3: The Log-Odds (Logit Transformation)
Taking the natural logarithm of the odds maps the range to the full real line $(-\infty, +\infty)$, matching the linear regression hypothesis:
Step 4: Algebraic Inversion to Recover Probability ($p$)
Exponentiate both sides:
Divide numerator and denominator by $e^z$:
$$\mathbf{p = \sigma(z) = \frac{1}{1 + e^{-z}}} \quad \text{Q.E.D.}$$$$\mathcal{L}(\mathbf{w}, b) = -\frac{1}{n}\sum_{i=1}^n \left[ y_i \ln(\hat{p}_i) + (1 - y_i)\ln(1 - \hat{p}_i) \right]$$ Unlike MSE which is non-convex when combined with sigmoid, Cross-Entropy ensures a smooth, convex bowl with a guaranteed global minimum.
03. Adapting to Multi-Class Classification (OvR vs Softmax)
Exam questions often ask how to classify customers into 3 categories: "low", "moderate", and "high spender".
1. One-vs-Rest (OvR / One-vs-All)
- Trains $K$ independent binary logistic classifiers for $K$ classes.
- Classifier 1: High Spender vs. [Low + Moderate]
- Classifier 2: Moderate Spender vs. [Low + High]
- Classifier 3: Low Spender vs. [Moderate + High]
- Inference Rule: Assign sample to class with highest posterior: $$\hat{y} = \arg\max_{k \in \{1, \dots, K\}} \sigma(\mathbf{w}_k^T\mathbf{x} + b_k)$$
2. Softmax Regression (Multinomial Logistic)
- Directly models joint categorical distribution across all $K$ classes simultaneously.
- Computes linear score $z_k = \mathbf{w}_k^T\mathbf{x} + b_k$ for each class, then normalizes using the Softmax operator: $$P(Y = k \mid \mathbf{x}) = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}$$
- Guarantees all probabilities are positive and strictly sum to $1.0$: $\sum_{k=1}^K P(Y=k \mid \mathbf{x}) = 1$.
04. Complete Confusion Matrix Metrics Suite
Essential formulas and definitions required for the 15-mark numericals on rare-event detection.
| Metric | Formula | Plain-English Interpretation | Exam Context (Rare Events) |
|---|---|---|---|
| True Positives (TP) | Correctly flagged positives | Model predicts positive, actual is positive | Correctly identified defective components ($7$) |
| False Positives (FP) | Type I Error ($\alpha$) | Model predicts positive, actual is negative | False alarms: normal parts flagged defective ($25$) |
| False Negatives (FN) | Type II Error ($\beta$) | Model predicts negative, actual is positive | Defect escapes: missed defective components ($3$) |
| True Negatives (TN) | Correctly cleared negatives | Model predicts negative, actual is negative | Correctly cleared benign parts ($965$) |
| Accuracy | $\frac{TP + TN}{TP + TN + FP + FN}$ | Overall fraction of correct predictions | Severely skewed by majority class ($97.2\%$) |
| Precision (PPV) | $\frac{TP}{TP + FP}$ | When model flags positive, how often is it right? | $\frac{7}{7+25} = 21.875\%$ |
| Recall (Sensitivity) | $\frac{TP}{TP + FN}$ | What fraction of actual positive events did we find? | $\frac{7}{7+3} = 70.0\%$ (Critical for defect prevention) |
| $F_1$-Score | $2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}$ | Harmonic mean giving equal weight to Precision and Recall | $33.33\%$ (Exposes poor precision) |
| $F_2$-Score | $\frac{5 \times \text{Precision} \times \text{Recall}}{4\text{Precision} + \text{Recall}}$ | Recall-weighted harmonic mean (Recall is $2\times$ more important) | $48.61\%$ (Optimal metric for safety/defects) |
05. The Accuracy Paradox & Extreme Imbalance Remediation
Jan 2025 & Nov 2025 Recurring Question (20 Marks). Why $99.5\%$ accuracy fails and how to engineer robust solutions.
Suppose a network dataset has $N = 10,000$ packets where only $0.5\%$ ($50$ packets) are malicious intrusions, and $9,950$ are benign.
A dumb Null Model that classifies every single packet as benign ($\hat{Y} = 0$) achieves: $$TP = 0, \quad FN = 50, \quad FP = 0, \quad TN = 9,950$$ $$\text{Accuracy} = \frac{0 + 9,950}{10,000} = \mathbf{99.50\%}, \qquad \text{Recall} = \frac{0}{0 + 50} = \mathbf{0.00\%}$$ Conclusion: The model has $99.5\%$ accuracy while missing $100\%$ of security attacks. Accuracy is completely useless here.
Cost-Sensitive Balanced Class Weights
Modify the binary cross-entropy loss to weight minority errors inversely proportional to frequency:
$$\mathcal{L} = -\sum_{i=1}^n \left[ w_1 y_i \ln \hat{p}_i + w_0 (1 - y_i)\ln(1 - \hat{p}_i) \right]$$ $$w_1 = \frac{N}{2 \times N_1} = \frac{10,000}{2 \times 50} = \mathbf{100}, \quad w_0 = \frac{10,000}{2 \times 9,950} \approx \mathbf{0.5025}$$Missing a single intrusion is penalized $200\times$ more heavily than a false alarm.
SMOTE Combined with Tomek Links
SMOTE (Synthetic Minority Over-sampling): Generates synthetic minority examples along feature-space line segments connecting $k$-nearest minority neighbors: $$\mathbf{x}_{\text{synthetic}} = \mathbf{x}_i + \lambda (\mathbf{x}_{zi} - \mathbf{x}_i), \quad \lambda \sim \mathcal{U}(0, 1)$$
Tomek Links: Identifies mutually nearest pairs from opposite classes and cleans borderline majority points, creating crisp decision separation.
06. Notation Decoding Matrix
| Symbol | Formal Name | Plain-English Meaning | Exam Context |
|---|---|---|---|
| $p = P(Y=1 \mid \mathbf{x})$ | Posterior Probability | Estimated likelihood of event occurring | Probability customer is a High Spender |
| $z = \mathbf{w}^T\mathbf{x} + b$ | Logit / Log-Odds | Unbounded linear score before sigmoid | $z > 0 \implies p > 0.5 \implies \text{Class 1}$ |
| $\sigma(z)$ | Sigmoid Function | Logistic activation squashing $\mathbb{R} \to [0, 1]$ | $\sigma(0) = 0.5$, $\sigma(\infty) = 1$, $\sigma(-\infty) = 0$ |
| $F_\beta$ | General $F$-Score | Weighted harmonic mean of Precision and Recall | $\beta=1$ (balanced), $\beta=2$ (recall weighted) |
| $K$ | Class Count / Folds | Number of classes or number of CV folds | $K=3$ spending tiers; $K=5$ or $10$ folds |
07. Repeatable Step-by-Step Solving Protocol
Execute this 5-step protocol for confusion matrix numerical problems:
Identify Total Instances ($N$), Total Actual Positives ($P$), and Total Actual Negatives ($N_0 = N - P$).
Explain why Recall / $F_2$ is preferred over Accuracy (cost of missed defects $FN$ exceeds cost of false alarms $FP$).
08. 6 Deadly Exam Traps & Common Student Mistakes
Confusing Type I Error with Type II Error
$\text{False Positive} = \text{Type I}$ (False alarm: healthy called sick). $\text{False Negative} = \text{Type II}$ (Dangerous miss: sick called healthy). Swapping these ruins both Precision and Recall.
Writing $\sigma(z) = \frac{1}{1 - e^{-z}}$
The denominator MUST have a plus sign: $\frac{1}{1 + e^{-z}}$. Writing a minus sign causes division by zero at $z=0$ ($\frac{1}{1-1}$) and completely invalidates the derivation.
Ignoring FPR Denominator Dilution
Students recommend ROC-AUC for fraud/intrusion. Examiners deduct marks! You must state that ROC-AUC is artificially inflated by large $TN$ in the FPR denominator, and PR-AUC is mandatory.
Putting Total $N$ in Precision Denominator
Precision denominator is $(TP + FP)$ (all positive predictions). Recall denominator is $(TP + FN)$ (all actual ground-truth positives). Never divide Precision by $N$.
Scaling Data Before Splitting into Folds
If you compute mean and standard deviation on the entire dataset before $K$-fold split, test fold statistics leak into training. Preprocessing must be fitted ONLY inside the training folds.
Assuming OvR Output Sums to 1.0
One-vs-Rest trains independent binary classifiers; their sigmoid outputs do not sum to $1.0$. Only Softmax regression enforces $\sum P(Y=k) = 1.0$.
09. Complete University Question Bank (All Past PYQs Solved)
Nov 2025 · Question 2 Manufacturing Rare Event Metric Calculations (20 Marks)
A company predicts a rare event in manufacturing with a test set of $1,000$ points where only $10$ are positive events. Model correctly identifies $7$ of the $10$ positive events, and incorrectly flags $25$ negative events as positive.
1. Calculate $TP, TN, FP, FN$ (15 Marks)
2. Calculate Accuracy, Precision, Recall, F1-score.
3. Analyze which metric is most suitable and explain why. (5 Marks)
Solution:
1. Derivation of Confusion Matrix Parameters (15 Marks)
- Total Test Instances ($N$): $1,000$
- Actual Positives ($P$): $10$
- Actual Negatives ($N_0$): $1000 - 10 = 990$
- True Positives ($TP$): $7$ (correctly identified positive events)
- False Negatives ($FN$): $P - TP = 10 - 7 = \mathbf{3}$ (missed positive events)
- False Positives ($FP$): $\mathbf{25}$ (negative events incorrectly flagged as positive)
- True Negatives ($TN$): $N_0 - FP = 990 - 25 = \mathbf{965}$ (correctly cleared negative events)
Metric Calculations:
$$\begin{aligned} \text{Accuracy} &= \frac{TP + TN}{N} = \frac{7 + 965}{1,000} = \frac{972}{1,000} = \mathbf{97.20\%} \\[8pt] \text{Precision} &= \frac{TP}{TP + FP} = \frac{7}{7 + 25} = \frac{7}{32} = \mathbf{0.21875 \quad (21.88\%)} \\[8pt] \text{Recall} &= \frac{TP}{TP + FN} = \frac{7}{7 + 3} = \frac{7}{10} = \mathbf{0.7000 \quad (70.00\%)} \\[8pt] F_1\text{-score} &= 2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} = 2 \times \frac{0.21875 \times 0.70}{0.21875 + 0.70} \\[4pt] &= 2 \times \frac{0.153125}{0.91875} = \frac{0.30625}{0.91875} = \mathbf{0.3333 \quad (33.33\%)} \end{aligned}$$2. Metric Suitability Analysis (5 Marks)
Accuracy ($97.20\%$) is completely misleading because a useless null model predicting all parts as negative would achieve $99.0\%$ accuracy while catching zero defects.
Most Suitable Metric: Recall (or $F_2$-Score)
- In manufacturing, a **False Negative** means releasing a defective component to customers, causing warranty recalls, safety hazards, and massive brand damage.
- A **False Positive** merely triggers secondary manual reinspection of a good part, incurring minor operational labor cost.
- Therefore, **Recall ($70.0\%$)** or the **$F_2$-score ($48.61\%$)** (which places twice the emphasis on Recall over Precision) is the optimal metric.
Jan 2025 · Question 2 Customer Spending Tiers via Logistic & Multi-Class Softmax (20 Marks)
A retail analytics company classifies customers into 3 categories: "low spender", "moderate spender", "high spender" using monthly income, purchases, average purchase value. Explain how Logistic Regression estimates probability of "high spender". Describe converting linear equation into sigmoid and interpreting probability. Explain adapting for multi-class via OvR and Softmax Regression. (20 Marks)
Solution:
1. High Spender Estimation & Linear to Sigmoid Conversion (10 Marks)
Let $\mathbf{x} = [x_{\text{income}}, x_{\text{purchases}}, x_{\text{value}}]^T$. Formulate binary target $Y = 1$ if High Spender, $0$ otherwise.
Compute linear combination $z = w_1 x_{\text{income}} + w_2 x_{\text{purchases}} + w_3 x_{\text{value}} + b$.
Apply Sigmoid mapping:
$$P(Y=1 \mid \mathbf{x}) = \sigma(z) = \frac{1}{1 + e^{-z}}$$Interpretation: If $\sigma(z) = 0.85$, the model predicts an $85\%$ chance of being a High Spender. At standard decision threshold $\tau = 0.5$, any customer with $z > 0$ is classified as High Spender.
2. Multi-Class Adaptation: OvR vs Softmax (10 Marks)
A. One-vs-Rest (OvR): Train 3 independent binary models:
- $P(\text{High} \mid \mathbf{x}) = \sigma(\mathbf{w}_{\text{high}}^T\mathbf{x} + b_{\text{high}})$
- $P(\text{Moderate} \mid \mathbf{x}) = \sigma(\mathbf{w}_{\text{mod}}^T\mathbf{x} + b_{\text{mod}})$
- $P(\text{Low} \mid \mathbf{x}) = \sigma(\mathbf{w}_{\text{low}}^T\mathbf{x} + b_{\text{low}})$
Assign customer to category with highest probability: $\hat{y} = \arg\max_{k} P(C_k \mid \mathbf{x})$.
B. Softmax Regression (Multinomial): Preferred approach. Directly normalizes scores so that probabilities sum to $1.0$:
$$P(Y = k \mid \mathbf{x}) = \frac{e^{\mathbf{w}_k^T\mathbf{x} + b_k}}{\sum_{j \in \{\text{low}, \text{mod}, \text{high}\}} e^{\mathbf{w}_j^T\mathbf{x} + b_j}}$$Softmax accounts for mutual exclusivity among customer tiers and prevents uncalibrated probability drift.
Nov 2025 · Question 6 Network Intrusion 99.5% Accuracy Paradox & SMOTE (20 Marks)
A cybersecurity model has 99.5% accuracy but misses nearly all 0.5% intrusion events.
i) Evaluate misleading nature of accuracy. (6 Marks)
ii) Recommend two alternative metrics and justify. (6 Marks)
iii) Suggest two strategies to handle class imbalance. (8 Marks)
Solution:
(i) Misleading Nature of Accuracy (6 Marks)
The Accuracy Paradox occurs because the majority benign class ($99.5\%$) swamps the metric. A trivial classifier predicting zero intrusions scores $99.5\%$ accuracy while achieving zero security value.
(ii) Two Recommended Alternative Metrics (6 Marks)
- PR-AUC (Precision-Recall AUC): Excludes True Negatives from the calculation entirely, evaluating performance strictly on True Positives and False Alarms. ROC-AUC is misleading due to $TN$ dilution in $\text{FPR} = \frac{FP}{TN + FP}$.
- $F_2$-Score: Penalizes missed intrusions twice as heavily as false alarms via $\beta = 2$, ensuring high sensitivity to attacks.
(iii) Two Strategies to Handle Imbalance (8 Marks)
- Cost-Sensitive Balanced Weights: Weight cross-entropy loss by inverse class frequencies ($w_{\text{intrusion}} = \frac{10000}{2 \times 50} = 100$). A missed attack is penalized $200\times$ more than a false alarm.
- SMOTE with Tomek Links: Synthesize new minority intrusions in feature space via neighbor interpolation, then remove ambiguous boundary points using Tomek links.
Jan 2025 · Question 3 Cross-Validation Architecture & Generalization in Churn (20 Marks)
A telecom company builds a model to predict churn. Explain how cross-validation assesses performance, prevents overfitting, and improves model generalization to unseen data. (20 Marks)
Solution:
1. Purpose of Cross-Validation (6 Marks)
Standard holdout splits suffer from high estimator variance (metrics depend on which specific samples fall into test set). CV rotates data systematically across $K$ folds, ensuring every sample serves as a test instance exactly once, yielding an unbiased estimate of generalization error.
2. Stratified K-Fold CV Protocol (8 Marks)
In customer churn (e.g., $15\%$ churn, $85\%$ retain), standard random $K$-fold can produce test folds with zero churners. Stratified K-Fold enforces identical $15:85$ proportions in every single fold.
3. Preventing Data Leakage in Preprocessing (6 Marks)
All feature normalization, imputation, and encoding must be fit strictly on the $K-1$ training folds and only applied to the $k$-th validation fold. Fitting scalers on the entire dataset before splitting causes data leakage, providing overly optimistic validation scores.
10. Interactive Offline Confusion Matrix & Metrics Calculator
Input test set parameters to calculate all performance metrics, $F_1$, $F_2$, and test for the Accuracy Paradox.
11. Active Recall Self-Test Quiz
12. Exam Hall Answer Sheet Presentation Checklist
Always draw the grid labeled with Actual Pos/Neg on rows and Predicted Pos/Neg on columns with numerical counts inside.
Write $\text{Acc} = \frac{TP+TN}{N}$, $\text{Prec} = \frac{TP}{TP+FP}$, $\text{Rec} = \frac{TP}{TP+FN}$, $F_1 = \frac{2PR}{P+R}$.
Write: $\text{Precision} = \frac{7}{32} = 0.21875 = 21.88\%$. Examiners look for the unreduced fraction.
Always cite the term "Accuracy Paradox" and compare the model's accuracy against the baseline "Null Model" ($99.0\%$).
Start with linear $z = \mathbf{w}^T\mathbf{x} + b$, write odds $\frac{p}{1-p}$, write log-odds $\ln(\frac{p}{1-p}) = z$, and show the algebraic steps isolating $p$.
Provide the Softmax equation $\frac{e^{z_k}}{\sum e^{z_j}}$ and state that $\sum P_k = 1.0$, whereas OvR outputs do not sum to 1.