ML Unit2 Notes
ML Unit2 Notes
Regression Predict a continuous value Real number Linear Reg, Multiple Reg, Ridge, Lasso
Classification Assign input to a category Discrete label Logistic Reg, KNN, Naive Bayes, SVM,
DT, RF
1. Collect labelled data -> 2. Pre-process -> 3. Train model -> 4. Evaluate -> 5. Predict on new data
Train/Test Split: Typically 80:20 or 70:30. Use cross-validation to reduce variance in evaluation.
Y = b0 + b1*X + e
Where: Y = predicted output | X = input feature | b0 = intercept | b1 = slope | e = error term
OLS Formulas
b0 = Y_mean - b1 * X_mean
Independence Observations are independent of each other Check for autocorrelation (Durbin-Watson)
Homoscedasticity Constant variance of residuals (errors) Log transform the target variable
Normality Residuals are normally distributed Check Q-Q plot; use robust regression
No Multicollinearity Features are not highly correlated with each Remove/combine correlated features; use
other PCA
MAE (Mean Absolute Mean(|Yi - Y_pred|) Average absolute error; robust to outliers
Error)
MSE (Mean Squared Mean((Yi - Y_pred)^2) Penalizes large errors more; sensitive to outliers
Error)
RMSE (Root MSE) sqrt(MSE) Same unit as Y; easier to interpret than MSE
EXAM TIPS
Ridge (L2) lambda * Sum(bi^2) Shrinks coefficients; none Many small/medium features
become exactly zero
Lasso (L1) lambda * Sum(|bi|) Drives some coefficients to Sparse feature space
exactly zero (feature selection)
Elastic Net Mix of L1 + L2 Balances feature selection and When both needed
coefficient shrinkage
Multicollinearity Problem
Problem: When two or more independent variables are highly correlated, coefficients become unstable and
unreliable.
Detection: VIF (Variance Inflation Factor). VIF > 10 indicates serious multicollinearity.
Fix: Remove one of the correlated features, combine them, or use Ridge/PCA.
P(Y=1 | X) = 1 / (1 + e^(-z))
where z = b0 + b1*X1 + b2*X2 + ... + bn*Xn (the linear combination)
Output: always between 0 and 1. If P >= 0.5 -> Class 1; if P < 0.5 -> Class 0 (default threshold)
F1-Score 2 * Precision * Recall / (P+R) Harmonic mean; balances Precision and Recall
AUC-ROC Area under ROC curve Discriminative power across all thresholds (1.0 = perfect)
Confusion Matrix
EXAM TIPS
* Precision vs Recall tradeoff -- when do you prefer one over the other?
* Linear vs Logistic regression -- key difference is the output type and sigmoid
Step 2 Calculate distance from new point to all training points Euclidean, Manhattan, or Minkowski distance
Step 3 Sort distances and select K nearest neighbours Pick the K points with smallest distances
Step 4 Vote (Classification) or Average (Regression) Majority class wins for classification
Distance Metrics
Distance Formula Use Case
Small K (e.g. K=1) Very flexible decision boundary; fits training High variance; overfitting; sensitive to noise
data closely
Large K (e.g. K=N) Very smooth boundary; averages over many High bias; underfitting; ignores local patterns
points
Optimal K Balance of flexibility and smoothness Found using cross-validation (try odd values; use
elbow method)
Pros: Simple, no training phase, naturally handles multi-class, non-parametric (no assumption about data
distribution).
Cons: Slow prediction O(n*d) for large datasets; sensitive to irrelevant features; needs feature scaling
(normalize data!); high memory usage.
Important: Always apply Min-Max or Z-score normalization before KNN -- otherwise features with large scales
dominate distance.
EXAM TIPS
* KNN is lazy learner -- no model built during training; all computation at prediction time
* Why feature scaling is mandatory for KNN -- large-scale features dominate Euclidean distance
Bayes' Theorem
P(X) = Evidence: probability of observing X (same for all classes; ignored in comparison)
Gaussian NB Features follow Normal distribution Continuous features (e.g. height, weight)
Problem: If a feature value never appears with a class in training, P(xi|C) = 0, making the entire product 0.
Pros: Very fast (O(n*d) training); works well with small data; excellent for text classification; handles multi-class
naturally.
Cons: Naive independence assumption rarely holds in real data; poor probability estimates (but classification is
still good); struggles with feature correlations.
EXAM TIPS
Key Terminology
Term Definition
Root Node The topmost node; represents the best splitting feature for the whole dataset
Internal Node A node with children; represents a test on a feature (e.g. Age > 30)
Branch / Edge Outcome of a feature test; path from parent to child node
Leaf Node Terminal node with no children; contains the final class label or value
Depth Length of longest path from root to leaf; controls model complexity
* Information Gain IG(S,A) = H(S) - Sum[ (|Sv|/|S|) * H(Sv) ] for each split v of feature A
* Choose the feature with HIGHEST Information Gain. If IG=0, no information gained. If H=0, pure node.
* Gini(S) = 1 - Sum[ P(c)^2 ] (ranges from 0 = pure to 0.5 = maximum impurity for binary)
* Choose the feature with LOWEST Gini Impurity. Computationally faster than entropy.
Pre-pruning (Early Stopping) Stop growing tree before it fully fits: set max_depth, min_samples_split,
min_samples_leaf as stopping criteria
Post-pruning (Reduced Error Grow full tree first, then remove branches that don't improve validation accuracy
Pruning)
Cost Complexity Pruning (CCP) Add penalty for tree size to cost function; used by sklearn's ccp_alpha parameter
ID3 Information Gain (Entropy) Categorical only Biased toward features with many
values
C4.5 Gain Ratio (normalizes IG) Categorical + Continuous Overcomes ID3's bias; handles missing
values
CART Gini Impurity / Variance Both; binary splits only Used by sklearn; creates binary trees;
Reduction handles regression too
EXAM TIPS
* Entropy formula and Information Gain calculation -- numerical questions are common
* When Entropy = 0 (pure node) and Entropy = 1 (maximum impurity) -- for binary class
Core Concepts
Term Definition
Support Vectors The data points closest to the hyperplane (from both classes). They define the margin.
Margin Distance between the hyperplane and the nearest support vectors from each class. SVM
maximizes this.
Hard Margin SVM No misclassifications allowed. Only works for perfectly linearly separable data.
Soft Margin SVM Allows some misclassifications (controlled by C). More practical for real data.
C Parameter Regularization. Small C = wider margin, more misclassification allowed. Large C = narrow
margin, fewer errors.
RBF / Gaussian K(x,y) = exp(-gamma * ||x-y||^2) Most common; works for most non-linear problems
SVM Hyperparameters
C (Regularization): Controls margin width. Low C = high bias (underfitting). High C = low bias but potential
overfitting.
Gamma (RBF kernel): Controls influence of each training point. Low gamma = far influence (smooth boundary).
High gamma = close influence (complex boundary).
Degree (Polynomial kernel): Degree of the polynomial. Higher degree = more complex boundary.
Pros: Works well in high dimensions; effective when features > samples; memory efficient (only support vectors
stored); versatile with kernels.
Cons: Slow on large datasets O(n^2 to n^3); not ideal for noisy data; results hard to interpret; feature scaling
required.
EXAM TIPS
* Kernel Trick -- what problem it solves and list 4 kernels with use cases
* Each tree sees a slightly different dataset -> diverse trees -> reduces variance.
* About 1/3 of data is not selected for each tree (called 'Out-of-Bag' or OOB samples -- used for validation).
* For classification: typically sqrt(total features) features are tried at each split.
* This decorrelates trees -- prevents all trees from looking similar and making the same errors.
* More trees = more stable predictions (but diminishing returns after ~100-500 trees).
Variance High (very sensitive to training data) Low (averaging reduces variance)
Bias Low (deep tree fits data closely) Slightly higher (but acceptable tradeoff)
Key Hyperparameters
max_depth Max depth of each tree; controls complexity None (grow fully) or tune
max_features Features considered at each split; 'sqrt' for classification 'sqrt' or 'log2'
min_samples_split Min samples required to split a node; prevents tiny splits 2-10
oob_score Use OOB samples for validation without a separate val True/False
set
EXAM TIPS
* Bagging vs Boosting -- Random Forest uses Bagging (parallel trees); AdaBoost/XGBoost uses Boosting (sequential)
* How Random Forest reduces variance -- ensemble averaging and OOB validation
* Random Forest vs Decision Tree -- 6-point comparison table is a classic exam format
Linear Reg. Regression Fit best line minimizing Simple, interpretable Assumes linearity Continuous output, linear
SSE relationship
Multiple Reg. Regression Multiple features -> Handles many Multicollinearity Multi-feature prediction
OLS/Regularization features issue problems
Logistic Reg. Classification Sigmoid maps linear to Probabilistic, fast Not for non-linear Binary/multi-class,
probability data linearly separable
KNN Both Vote of K nearest Simple, no training Slow prediction, Small datasets,
neighbours needed needs scaling non-linear boundary
Naive Bayes Classification Bayes Theorem + Very fast, good for Naive independence Text classification, spam
independence text assumption detection
Decision Tree Both Recursive feature-based Interpretable, no Overfits easily Mixed features, rule
splits scaling extraction
SVM Both Maximum margin High-dim, kernel Slow, hard to High-dimensional, clear
hyperplane + kernels versatility interpret margin data
Random Both Ensemble of Decision High accuracy, robust Slow, black box General-purpose,
Forest Trees (Bagging) handles non-linearity
Linear Regression Y=b0+b1X; OLS minimizes SSE; R-squared measures fit; 5 assumptions
Multiple Regression Multiple features; Adjusted R2; Ridge/Lasso prevent overfitting; VIF for multicollinearity
SVM Max-margin hyperplane; support vectors; kernel trick (RBF, Linear, Poly); C and gamma
Random Forest Bagging + random features; majority vote; OOB validation; feature importance; robust to
overfitting
EXAM TIPS
* GATE 2027: Focus on Entropy/IG numericals, SVM margin concepts, Bayesian classifier derivation
* 5-mark numericals: KNN classification example, Naive Bayes spam example, Entropy calculation
* Draw diagrams: Sigmoid curve, Decision Tree, SVM margin with support vectors
* Logistic Reg. vs Linear Reg -- this comparison appears in almost every exam
Q2. What is Logistic Regression? How does it differ from Linear Regression? [5 marks]
Logistic Regression is a classification algorithm that predicts the probability of a binary outcome using the Sigmoid
function: P(Y=1|X) = 1 / (1 + e^(-z)) where z is the linear combination of inputs.
Differences: Linear Regression predicts continuous values; Logistic Regression predicts probabilities (0 to 1). Linear
uses MSE as loss; Logistic uses Log Loss (Binary Cross-Entropy). Linear has a straight-line output; Logistic has an
S-shaped sigmoid output. Linear can predict any real number; Logistic output is always between 0 and 1.
Q3. Explain the KNN algorithm with its distance metrics and effect of K. [5/10 marks]
KNN (K-Nearest Neighbor) is a lazy, non-parametric algorithm. Steps: (1) Choose K; (2) Compute distance from new
point to all training points; (3) Select K nearest neighbours; (4) Assign majority class (classification) or average value
(regression).
Distance metrics: Euclidean = sqrt(Sum(Xi-Yi)^2); Manhattan = Sum(|Xi-Yi|); Minkowski is the general form.
Effect of K: Small K -> high variance, overfitting, sensitive to noise. Large K -> high bias, underfitting, over-smooth
boundary. Optimal K found via cross-validation.
Important: Feature scaling (normalization) is mandatory before KNN.
Q4. Explain Naive Bayes with Bayes' Theorem and Laplace Smoothing. [5/10 marks]
Bayes' Theorem: P(C|X) = P(X|C) * P(C) / P(X). Naive Bayes applies this with the 'naive' assumption that all features
are conditionally independent given class C.
Prediction: Choose class C that maximizes P(C) * Product[P(xi|C)].
Types: Gaussian NB for continuous features; Multinomial NB for word counts; Bernoulli NB for binary features.
Laplace Smoothing: Adds alpha (usually 1) to all counts to prevent zero probabilities when a feature value is unseen
for a class: P(xi|C) = (count(xi,C) + alpha) / (count(C) + alpha*V).
Application: Spam detection -- calculate P(spam|words) vs P(not spam|words) and classify.
Q5. Explain Decision Trees with Entropy, Information Gain, and Gini Impurity. [10 marks]
A Decision Tree recursively splits data on feature tests to maximize node purity.
Entropy: H(S) = -Sum[P(c)*log2(P(c))]. Ranges from 0 (pure) to 1 (maximum impurity for binary). Example: H([5+,5-]) =
-0.5*log2(0.5) - 0.5*log2(0.5) = 1.0.
Information Gain: IG(S,A) = H(S) - Sum[(|Sv|/|S|)*H(Sv)]. Choose the feature with HIGHEST IG. Used by ID3
algorithm.
Gini Impurity: Gini(S) = 1 - Sum[P(c)^2]. Ranges from 0 (pure) to 0.5 (max impurity for binary). Used by CART;
computationally faster than Entropy.
Algorithms: ID3 (categorical, Info Gain), C4.5 (Gain Ratio, handles continuous), CART (Gini, binary splits).
Pruning: Pre-pruning = max_depth, min_samples_split; Post-pruning = remove branches on validation set.
Q7. Explain Random Forest. How does it differ from a single Decision Tree? [5/10 marks]
Random Forest is an ensemble of Decision Trees built using Bagging + Random Feature Selection.
Steps: (1) Draw N bootstrap samples with replacement; (2) Train one Decision Tree on each, considering only sqrt(d)
features at each split; (3) Final prediction = majority vote (classification) or average (regression).
vs Decision Tree: DT has high variance and overfits; RF reduces variance by averaging diverse trees. DT is
interpretable; RF is a black box. DT is fast; RF is slower. RF provides feature importance scores.
OOB Score: ~1/3 of samples not used per tree are used for validation (Out-of-Bag), giving a free validation score
without a separate validation set.
Q8. Compare and contrast all 8 supervised learning algorithms covered in Unit II. [10 marks]
See the comparison table on the previous page for a structured overview. In paragraph form:
Linear/Multiple Regression are for continuous outputs, interpretable, but assume linearity. Logistic Regression
extends regression to classification using Sigmoid, fast and probabilistic. KNN is lazy, instance-based, requires no
training but is slow at prediction and needs scaling. Naive Bayes is the fastest, works extremely well for text, but
assumes feature independence. Decision Trees are interpretable and handle mixed features but overfit without
pruning. SVM is powerful in high-dimensional spaces and uses kernels for non-linearity but is slow on large data.
Random Forest is the most robust general-purpose algorithm, trading interpretability for accuracy.