Skip to content
ml-recall

Topic notes

Classification

Predicting categories — binary, multiclass and multilabel tasks, one-vs-rest, decisions from probabilities and costs, generative classifiers (naive Bayes, LDA/QDA) and how to compare classifiers.

4-min read AI-checked

Practise 34 questions Take a test

Key ideas

Kinds of tasks1. Classification is supervised learning with a categorical label: like regression it learns x↦y\mathbf{x} \mapsto y from labelled examples, but it answers "which one?" instead of "how much?". Binary: two classes. Multiclass: more than two classes, each example gets exactly one (a recipe's cuisine). Multilabel: each example may get any number of labels at once (the topics of an article)1.

Binary classifiers for many classes1. One-vs-rest (one-vs-all) trains one classifier per class, that class against all others — KK models, highest score wins; it is the usual default. One-vs-one trains one classifier per pair, K(K−1)/2K(K-1)/2 models, and takes a vote. Both are strategies that wrap a binary learner such as logistic regression, not algorithms of their own. Trees, kk-NN, naive Bayes and softmax regression handle many classes directly, and every scikit-learn classifier accepts multiclass targets out of the box1.

From probabilities to decisions5. A probabilistic classifier gives P(y∣x)P(y \mid \mathbf{x}). If predicting y′y' when the truth is yy costs l(y,y′)l(y, y'), the best decision minimizes the posterior expected loss ∑yl(y,y′)P(y∣x)\sum_y l(y, y')P(y \mid \mathbf{x})5. With the 0–1 loss (every mistake costs 1) that is simply the most probable class; unequal costs can make a less probable class the better bet. For two classes the rule becomes a threshold: predict positive when P(1∣x)>cFP/(cFP+cFN)P(1 \mid \mathbf{x}) > c_{FP}/(c_{FP} + c_{FN}). The Bayes classifier — this rule applied to the true distribution — has the lowest possible error; naive Bayes is only an approximation of it.

Generative vs discriminative. Generative classifiers model P(x∣y)P(\mathbf{x} \mid y) and P(y)P(y) and apply Bayes' rule (naive Bayes, LDA, QDA); discriminative ones model P(y∣x)P(y \mid \mathbf{x}) or the boundary directly (logistic regression, SVMs, trees). With Gaussian class densities4, a covariance shared by all classes (LDA) makes the quadratic terms cancel, leaving a linear boundary; class-specific covariances (QDA) give a quadratic boundary — an ellipse, parabola or hyperbola in 2-D. The prior enters each class score only as an additive log⁡P(y=k)\log P(y = k), so a larger prior lifts that class's score by the same constant everywhere4. QDA with diagonal covariances is Gaussian naive Bayes4. Only where the posteriors cross matters for decisions, so even wrong densities can give the right boundary.

Naive Bayes2,3. Assume the features are conditionally independent given the class: P(x∣y)=∏jP(xj∣y)P(\mathbf{x} \mid y) = \prod_j P(x_j \mid y). For dd binary features this replaces 2d2^d probabilities per class by dd2. Estimation is counting: priors are class frequencies, P(xj=1∣y)P(x_j = 1 \mid y) is the fraction of class-yy examples with feature jj on. P(x)P(\mathbf{x}) is the same for every class, so it can be dropped when comparing. A Bernoulli model with dd words and 2 classes has 2d+12d + 1 free parameters, and absent words count too, through 1−P(xj=1∣y)1 - P(x_j = 1 \mid y)3.

Choosing a classifier. Shortlist candidates that fit the data, then compare them on validation data, never by training accuracy. For wide, sparse bag-of-words text, linear models and naive Bayes are strong, cheap first choices; naive Bayes is fast and has a long record in document classification and spam filtering3. Two examples with identical features and different labels make zero training error impossible for any classifier.

Formulas

P(y∣x)=P(x∣y) P(y)P(x),y^NB=arg max⁡y[ln⁡P(y)+∑jln⁡P(xj∣y)]P(y \mid \mathbf{x}) = \frac{P(\mathbf{x} \mid y)\,P(y)}{P(\mathbf{x})}, \qquad \hat y_{\text{NB}} = \operatorname*{arg\,max}_y \Big[\ln P(y) + \sum_j \ln P(x_j \mid y)\Big] y^=arg min⁡y′∑yl(y,y′) P(y∣x)(0–1 loss: y^=arg max⁡yP(y∣x))\hat y = \operatorname*{arg\,min}_{y'} \sum_y l(y, y')\,P(y \mid \mathbf{x}) \quad \text{(0–1 loss: } \hat y = \operatorname*{arg\,max}_y P(y \mid \mathbf{x})\text{)}

LDA class score4: wk⊤x+wk0\mathbf{w}_k^\top\mathbf{x} + w_{k0} with wk=Σ−1μk\mathbf{w}_k = \Sigma^{-1}\boldsymbol\mu_k and wk0=−12μk⊤Σ−1μk+log⁡P(y=k)w_{k0} = -\tfrac12\boldsymbol\mu_k^\top\Sigma^{-1}\boldsymbol\mu_k + \log P(y = k). Classifier counts for K=5K = 5: one-vs-rest 5, one-vs-one 10.

Worked example

Bernoulli naive Bayes with features (free, meeting, link). Spam: (1,0,1),(1,0,0),(0,0,1)(1,0,1), (1,0,0), (0,0,1); ham: (0,1,0),(1,1,0),(0,1,1),(0,0,0)(0,1,0), (1,1,0), (0,1,1), (0,0,0). New message (1,0,1)(1, 0, 1):

Costs. P(y∣x)=(0.6,0.25,0.15)P(y \mid \mathbf{x}) = (0.6, 0.25, 0.15) for classes A, B, C; predicting A when the truth is C costs 8, every other mistake 1. Expected costs: A 0.25+0.15⋅8=1.450.25 + 0.15 \cdot 8 = 1.45, B 0.6+0.15=0.750.6 + 0.15 = 0.75, C 0.6+0.25=0.850.6 + 0.25 = 0.85. Predict B, although A is the most probable class.

In code

import numpy as np
from sklearn.naive_bayes import BernoulliNB

X = [[1, 0, 1], [1, 0, 0], [0, 0, 1],               # spam   (free, meeting, link)
     [0, 1, 0], [1, 1, 0], [0, 1, 1], [0, 0, 0]]    # ham
y = [1, 1, 1, 0, 0, 0, 0]
nb = BernoulliNB(alpha=1.0).fit(X, y)               # alpha = 1: Laplace smoothing
print(np.exp(nb.class_log_prior_).round(3))         # [0.571 0.429]  P(ham), P(spam)
print(np.exp(nb.feature_log_prob_).round(3).tolist())  # [[0.333, 0.667, 0.333], [0.6, 0.2, 0.6]]
print(nb.predict_proba([[1, 0, 1]]).round(4))       # [[0.1464 0.8536]]

The middle line holds P(xj=1∣ham)P(x_j = 1 \mid \text{ham}) and P(xj=1∣spam)P(x_j = 1 \mid \text{spam}), and the last line matches the smoothed hand computation.

Common pitfalls

References

  1. scikit-learn User Guide — Sec. 1.12 Multiclass and multioutput algorithms (1.12.1 Multiclass classification, 1.12.1.2 OneVsRestClassifier, 1.12.1.3 OneVsOneClassifier, 1.12.2 Multilabel classification)
  2. Dive into Deep Learning — Sec. 22.9 Naive Bayes (22.9.3 The Naive Bayes Classifier, 22.9.4 Training)
  3. scikit-learn User Guide — Sec. 1.9 Naive Bayes (intro; 1.9.2 Multinomial Naive Bayes; 1.9.4 Bernoulli Naive Bayes)
  4. scikit-learn User Guide — Sec. 1.2.2 Mathematical formulation of the LDA and QDA classifiers
  5. Wikipedia: Bayes estimator — Definition (minimizing the posterior expected loss)