Skip to content

Classification (Basic)

What Is Classification?

  • Classification (supervised): build a model from labeled training data (xi,yi) that assigns a discrete class label y to new instances.
  • Prediction/regression (a sibling task): predict a continuous value.
  • Typical flow: training (induce model) → testing (evaluate on hold-out) → application (classify new data).

Terminology

  • Classifier: the induced function y^=f(x).
  • Training set: labeled examples. Test set: unseen labeled examples.
  • Attribute: descriptive feature (predictor). Class label: target.

General Approach

1. Model construction (learning): training data → classifier (e.g., tree, rules).
2. Model usage: apply to test data / future data; estimate accuracy.

During training we also evaluate using accuracy, confusion matrix, etc. (see Evaluation section).

Decision Tree Induction

A decision tree: internal nodes = tests on an attribute; branches = outcomes; leaf = class prediction. Classification = follow root-to-leaf.

Algorithm (Top-Down, Greedy, Divide-and-Conquer — Hunt / ID3 / C4.5 / CART)

DTL(D, attribs):
  if all D same class c: return leaf(c)
  if attribs empty: return leaf(majority class of D)
  choose best attribute A by split criterion;
  for each value v of A:
      Dv = subset of D with A=v;
      child_v = DTL(Dv, attribs \ {A});
  return node(A, {child_v});

1. ID3 — Information Gain (entropy-based)

  • Entropy of data D with classes C1..Cm:Entropy(D)=i=1mpilog2pi,pi=|Ci||D|Entropy=0 when pure; max when uniform.
  • Information gain of splitting on A with v values:Gain(D,A)=Entropy(D)j=1v|Dj||D|Entropy(Dj)
  • ID3 picks the attribute with maximum gain.

2. C4.5 — Gain Ratio (corrects bias toward many-valued attrs)

SplitInfo(D,A)=j|Dj||D|log2|Dj||D|GainRatio(D,A)=Gain(D,A)SplitInfo(D,A)
  • Normalizes by the spread of the split; avoids preferring attributes with many distinct values.

3. CART — Gini Index (impurity)

  • Gini of D:Gini(D)=1i=1mpi2Lower = purer. Gini of a split:Ginisplit(D,A)=j|Dj||D|Gini(Dj)
  • CART picks the split minimizing Gini (binary splits). Also used for regression trees (minimize variance).
CriterionUsed byBiasNotes
Information gainID3toward many valuessimple, common in teaching
Gain ratioC4.5balancedhandles high-cardinality
GiniCARTbalancedfaster (no log), binary splits

Tree Overfitting & Pruning

  • Overfitting: tree fits training noise ⇒ poor generalization.
  • Pre-pruning: stop splitting when gain/sample below threshold, or node too small.
  • Post-pruning (e.g., error-based, cost-complexity): grow full tree, then prune subtrees replacing with leaf; keep if test accuracy doesn't drop. C4.5 uses a pessimistic estimate; CART uses cost-complexity α|leaves|+error.

Advantages / Disadvantages

  • ✅ interpretable, handles nominal & numeric, fast, insensitive to data scale.
  • ❌ greedy (locally optimal), unstable to small changes, bias toward dominant classes.

Naïve Bayes Classifier

Based on Bayes' theorem with the conditional independence assumption among attributes given the class.

P(Ck|X)=P(X|Ck)P(Ck)P(X)

With X=(x1..xn) and independence given class:

P(Ck|x1..xn)=P(Ck)i=1nP(xi|Ck)P(X)

Classify as y^=argmaxkP(Ck)iP(xi|Ck).

Estimating Probabilities

  • Categorical xi: P(xi|Ck)=count(xi,Ck)+1xcount(x,Ck)+|dom(xi)| (Laplacian / additive smoothing) to avoid zero.
  • Numeric xi: assume Gaussian: P(xi|Ck)=12πσkexp((xiμk)22σk2).

Properties

  • ✅ simple, fast (linear in attributes), robust with little data, good baseline.
  • ❌ independence assumption rarely holds (but often works well enough).
  • Zero-frequency problem solved by Laplace smoothing.

k-Nearest Neighbor (k-NN)

  • Lazy learner (instance-based; no explicit model built at training — just store data).
  • To classify x: find the k closest training points (by distance, e.g., Euclidean), predict the majority class (or weighted vote: wi=1/d(x,xi)).
AspectNotes
DistanceEuclidean / Minkowski / cosine (normalize first!)
k choicesmall k → noisy; large k → smooth; choose via CV
Prosno training cost, adapts, handles complex boundaries
Consslow query (scan all data), sensitive to scale/irrelevant attrs, needs feature weighting
  • Curse of dimensionality degrades distance meaning in high-D; use normalization & feature selection.

Model Evaluation & Selection

Train/Test Split

  • Hold-out: split into training and test (e.g., 70/30).
  • Cross-validation (k-fold): partition into k folds; train on k1, test on 1, repeat; report mean accuracy. Leave-one-out = k=n.
  • Bootstrapping: resample with replacement; estimate accuracy on out-of-bag.

Accuracy & Error

  • Accuracy = correctly classified / total. Error rate = 1 − accuracy.

Confusion Matrix (binary)

Actual +Actual −
Pred +TPFP
Pred −FNTN
  • Precision =TP/(TP+FP)
  • Recall (Sensitivity) =TP/(TP+FN)
  • F1 =2PR/(P+R) (harmonic mean)
  • Specificity =TN/(TN+FP)

Other Metrics

  • ROC curve: plot TPR vs FPR at varying thresholds; AUC (area under) summarizes discriminative power (1.0 perfect, 0.5 random).
  • Recall-Precision curve; stratified/fairness considerations.
  • Significance test: compare two classifiers with paired t-test / McNemar on the same test set.

Overfitting vs Underfitting

  • Bias (underfitting): model too simple. Variance (overfitting): model too complex. Aim for the sweet spot (bias-variance trade-off), guided by validation error.

Comparing the Basic Classifiers

ClassifierTypeModelProsCons
Decision treeeagertreeinterpretable, handles mixed typesgreedy, unstable
Naïve Bayeseager, generativeprobabilityfast, robust, good baselineindependence assumption
k-NNlazyinstance-basedno training, adaptsslow query, scale-sensitive

Worked Confusion Matrix (binary)

Test set of 100; classifier predicts:

Actual +Actual −
Pred +TP=40FP=10
Pred −FN=15TN=35
  • Accuracy = (40+35)/100=75%.
  • Precision = 40/(40+10)=80%.
  • Recall = 40/(40+15)=72.7%.
  • F1 = 20.80.727/(0.8+0.727)76.2%.
  • Specificity = 35/(35+10)=77.8%.

Handling Missing Values at Classify Time

  • Decision trees: route down both/weighted branches, or use surrogate splits (C4.5).
  • Naïve Bayes: marginalize over the missing attribute.
  • k-NN: use only available features (distance over present dims) or impute.

Bias–Variance Trade-off (Detail)

Total error ≈ bias² + variance + noise.

  • High bias (underfit): model too simple, misses structure (e.g., linear on non-linear).
  • High variance (overfit): model too sensitive to training quirks (deep tree, small k in k-NN).
  • Use validation error to pick model complexity; CV selects the sweet spot.

Multi-Class Classification

Binary learners extend to >2 classes via:

  • One-vs-Rest (OvR): train one classifier per class vs all others; pick the highest-score class. Simple, k models.
  • One-vs-One (OvO): train a classifier for every pair; majority vote among k(k1)/2 models. Often better for SVMs (smaller problems) but more models.
  • Native multi-class: decision trees, Naïve Bayes, and neural nets classify multiple classes directly.

Naïve Bayes — Worked Sketch

Test record x=(outlook=sunny,humidity=high). For classes Play=yes/no:

P(yes|x)P(yes)P(sunny|yes)P(high|yes)P(no|x)P(no)P(sunny|no)P(high|no)

Predict the larger posterior (after Laplace smoothing to avoid zero factors). Fast and surprisingly accurate on text/spam.

Common Pitfalls

  • Forgetting to normalize before distance/linear models.
  • Using accuracy on imbalanced data (use precision/recall/AUC).
  • Overfitting a deep tree or small-k k-NN (validate via CV).
  • Leakage: using test info during training/preprocessing (e.g., scaling on full data).

Summary

Classification learns a mapping from features to discrete labels. Decision trees (ID3/C4.5/CART) use entropy/gain, gain-ratio, and Gini to greedily split, with pruning to control overfitting. Naïve Bayes applies Bayes' theorem under conditional independence, with Laplace smoothing for zeros. k-NN is a lazy instance-based method using local majority voting. Evaluation relies on hold-out/CV, accuracy, the confusion matrix (precision/recall/F1), and ROC/AUC — always watch the bias-variance trade-off.