Unit 3: Classification & Prediction

Supervised Learning · 5 Sections

3.1 Decision Trees

A Decision Tree is a supervised learning algorithm that splits data into subsets using attribute tests, building a tree structure of decisions. Each internal node tests an attribute, each branch represents an outcome, and each leaf holds a class label.

Tree Building Algorithms

  • ID3 (Iterative Dichotomiser 3): Uses Information Gain to select the best splitting attribute at each node. Works only with categorical attributes.
  • C4.5 (successor to ID3): Uses Gain Ratio (normalizes Information Gain). Handles continuous attributes by finding optimal split thresholds and missing values.
  • CART (Classification and Regression Trees): Uses Gini Index for splitting. Produces binary trees (two branches per node).
Key Metrics for Splitting:
  • Entropy: Measures impurity. H(S) = -Σ p(i) log₂ p(i). Range: 0 (pure) to log₂(k) (max impurity for k classes).
  • Information Gain: IG(S, A) = H(S) - Σ (|Sᵥ|/|S|) × H(Sᵥ). The attribute with highest IG is selected for splitting.
  • Gini Index: Gini(S) = 1 - Σ p(i)². Range: 0 (pure) to 1 - 1/k. CART uses Gini; lower is better.
  • Gain Ratio: GR = IG / SplitInfo. Normalizes Information Gain to avoid bias toward attributes with many values.

Pruning

  • Pre-pruning (early stopping): Stop growing the tree before it perfectly classifies training data (max depth, min samples per leaf).
  • Post-pruning: Grow the full tree first, then remove branches that don't improve validation accuracy.

3.2 Naive Bayes Classifier

Naive Bayes is a probabilistic classifier based on Bayes' Theorem with the "naive" assumption that features are conditionally independent given the class label.

Bayes' Theorem:

P(Class | Features) = P(Features | Class) × P(Class) / P(Features)

  • P(Class | Features): Posterior probability — what we want to compute.
  • P(Features | Class): Likelihood — probability of features given the class.
  • P(Class): Prior probability — frequency of each class in training data.
  • P(Features): Evidence — total probability of features (constant for all classes).

Handling Text Data

  • Bag-of-Words (BoW): Represents text as word frequency vectors, ignoring grammar and word order.
  • TF-IDF: Weighs words by importance: TF (term frequency) × IDF (inverse document frequency).
  • Laplace Smoothing: Adds +1 to all word counts to avoid zero probabilities for unseen words. P(w|class) = (count(w) + 1) / (total_words + vocabulary_size).
1
Naive Bayes Classification Workflow
graph LR INPUT[(Input Email)] --> TOKEN[Tokenize
Split into words] TOKEN --> BOW[Bag-of-Words
Word frequency vector] BOW --> PROB[Calculate P(Class|Words)
Bayes Theorem] PROB --> PRIOR[Prior P(Class)
Spam vs Ham ratio] PROB --> LIKE[Likelihood P(Word|Class)
With Laplace +1] PRIOR --> POST[Posterior
Multiply prior x likelihood] LIKE --> POST POST --> DECIDE{Higher
Probability?
} DECIDE -->|P(Spam)| SPAM[(Spam)] DECIDE -->|P(Ham)| HAM[(Ham)] classDef decision fill:#0891b2,stroke:#06b6d4,color:#fff,font-size:18px,font-weight:bold classDef process fill:#6366f1,stroke:#818cf8,color:#fff,font-size:18px,font-weight:bold classDef success fill:#22c55e,stroke:#4ade80,color:#fff,font-size:18px,font-weight:bold classDef error fill:#ef4444,stroke:#f87171,color:#fff,font-size:18px,font-weight:bold classDef info fill:#8b5cf6,stroke:#a78bfa,color:#fff,font-size:18px,font-weight:bold class INPUT,DECIDE decision class TOKEN,BOW,PROB process class SPAM error class HAM success class PRIOR,LIKE,POST info
Note: Laplace smoothing adds +1 to all word counts, ensuring no probability is ever zero for unseen words. Gmail achieves 99.9% spam detection accuracy with this approach.

3.3 k-Nearest Neighbors (k-NN)

k-NN is an instance-based (lazy) learning algorithm that classifies a new data point based on the majority class of its k nearest neighbors in the training set. No model is built during training — all computation happens at prediction time.

Distance Metrics:
  • Euclidean Distance: √(Σ(xᵢ - yᵢ)²). Most common for continuous numeric features.
  • Manhattan Distance: Σ|xᵢ - yᵢ|. More robust to outliers than Euclidean.
  • Minkowski Distance: Generalized form: (Σ|xᵢ - yᵢ|^p)^(1/p). p=1 → Manhattan, p=2 → Euclidean.

Key Considerations

  • k Selection: Small k (e.g., 1) captures noise; large k smooths boundaries. Use cross-validation to find optimal k.
  • Feature Normalization: Critical because distance metrics are scale-sensitive. Min-Max or Z-score normalization is essential.
  • Lazy Learning: No training phase — stores all data and classifies at query time. Fast to train but slow to predict.
  • Curse of Dimensionality: Distance metrics become less meaningful in high dimensions. Dimensionality reduction helps.
2
k-NN Classification Workflow
graph TD NEW[(New Data Point)] --> NORM[Normalize Features
Min-Max or Z-Score] NORM --> DIST[Calculate Distances
Euclidean / Manhattan] DIST --> SORT[Sort by Distance
Find k nearest neighbors] SORT --> K{Choose k
e.g. k=5} K --> VOTE[Majority Voting
Count class among neighbors] VOTE --> CLASS[Predicted Class
Most frequent neighbor class] classDef decision fill:#0891b2,stroke:#06b6d4,color:#fff,font-size:18px,font-weight:bold classDef process fill:#6366f1,stroke:#818cf8,color:#fff,font-size:18px,font-weight:bold classDef success fill:#22c55e,stroke:#4ade80,color:#fff,font-size:18px,font-weight:bold classDef warning fill:#f59e0b,stroke:#fbbf24,color:#1e1b4b,font-size:18px,font-weight:bold class NEW,K decision class NORM,DIST,SORT,VOTE process class CLASS success
Note: k-NN is a "lazy learner" — it stores all training data and performs computation only at prediction time. Feature normalization is critical because distance metrics are scale-sensitive.

3.4 Rule-Based Classifiers

Rule-Based Classifiers use IF-THEN rules to classify data. Each rule is a conjunction of conditions (IF) leading to a class prediction (THEN).

Rule Structure

  • Rule: IF (condition₁ AND condition₂ AND ...) THEN class.
  • Coverage: Number of instances satisfying the rule's conditions (antecedent).
  • Accuracy: Proportion of covered instances that belong to the predicted class.

Rule Generation Methods

  • Sequential Covering: Learn one rule at a time, remove covered instances, repeat until no instances remain.
  • RIPPER (Repeated Incremental Pruning): Optimizes rules by growing and pruning sequentially.
  • Decision Tree to Rules: Convert each root-to-leaf path into a rule (one rule per leaf).
Rule Pruning:
  • Pre-pruning: Stop growing rules when coverage or accuracy drops below a threshold.
  • Post-pruning: Grow complete rules, then remove conditions that don't improve validation accuracy.
  • Ordered Rules: Rules are evaluated in order; first matching rule wins (reduces conflicts).

3.5 Model Evaluation

Evaluating classification models requires metrics beyond simple accuracy, especially with imbalanced datasets.

Confusion Matrix

  • True Positive (TP): Correctly predicted positive.
  • True Negative (TN): Correctly predicted negative.
  • False Positive (FP): Incorrectly predicted positive (Type I error).
  • False Negative (FN): Incorrectly predicted negative (Type II error).
Evaluation Metrics:
  • Accuracy: (TP + TN) / Total. Misleading with imbalanced classes.
  • Precision: TP / (TP + FP). Of all predicted positives, how many are correct?
  • Recall (Sensitivity): TP / (TP + FN). Of all actual positives, how many were found?
  • F1-Score: 2 × (Precision × Recall) / (Precision + Recall). Harmonic mean balancing precision and recall.
  • ROC Curve: Plots True Positive Rate vs False Positive Rate across thresholds. AUC (Area Under Curve) = 1.0 is perfect; 0.5 is random.

Cross-Validation

  • Holdout Method: Split data into training (70%) and test (30%) sets. Simple but depends on the split.
  • k-Fold Cross-Validation: Split data into k folds. Train on k-1 folds, test on 1. Repeat k times and average results. Most common: k=5 or k=10.
  • Leave-One-Out (LOO): k = n (number of instances). Each instance is tested once. Computationally expensive.
3
Decision Tree Classification Process
graph TD START[(Training Data)] --> CALC[Calculate Entropy
H of class labels] CALC --> BEST[Select Best Attribute
Highest Information Gain] BEST --> SPLIT[Split Data
Create child nodes
by attribute values] SPLIT --> CHECK{Stopping
Criteria?
} CHECK -->|No: More splits| CALC CHECK -->|Yes: Pure or Max Depth| LEAF[Leaf Node
Assign class label] LEAF --> TREE[Complete Decision Tree] TREE --> PREDICT[Classify New Instance
Traverse tree from root] PREDICT --> RESULT[Predicted Class] classDef decision fill:#0891b2,stroke:#06b6d4,color:#fff,font-size:18px,font-weight:bold classDef process fill:#6366f1,stroke:#818cf8,color:#fff,font-size:18px,font-weight:bold classDef success fill:#22c55e,stroke:#4ade80,color:#fff,font-size:18px,font-weight:bold classDef warning fill:#f59e0b,stroke:#fbbf24,color:#1e1b4b,font-size:18px,font-weight:bold class START,TREE decision class CALC,BEST,SPLIT process class LEAF,PREDICT,RESULT success class CHECK warning
Note: Information Gain = Parent Entropy - Weighted Average Child Entropy. Higher gain means a better split. C4.5 normalizes this with Gain Ratio.
Unit 2 Activity Case Studies