Key ideas
Kinds of tasks1. Classification is supervised learning with a categorical label: like regression it learns 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 — models, highest score wins; it is the usual default. One-vs-one trains one classifier per pair, models, and takes a vote. Both are strategies that wrap a binary learner such as logistic regression, not algorithms of their own. Trees, -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 . If predicting when the truth is costs , the best decision minimizes the posterior expected loss 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 . 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 and and apply Bayes' rule (naive Bayes, LDA, QDA); discriminative ones model 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 , 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: . For binary features this replaces probabilities per class by 2. Estimation is counting: priors are class frequencies, is the fraction of class- examples with feature on. is the same for every class, so it can be dropped when comparing. A Bernoulli model with words and 2 classes has free parameters, and absent words count too, through 3.
- Zero counts: one feature value never seen with a class makes that class's product 0, whatever the other features say. Laplace smoothing adds pseudo-counts: for a binary feature2; multinomial NB uses with 3.
- Underflow: products of hundreds of small probabilities round to 0, so sum log-probabilities instead2.
- Missing feature at prediction time: leave its factor out (summing it out gives a factor of 1).
- Variants: Gaussian NB for continuous features, multinomial for counts, Bernoulli for presence/absence3.
- The independence assumption is usually false — on XOR data NB outputs 0.5 everywhere — yet NB often classifies well (spam filtering); its
predict_probavalues should not be taken at face value3.
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
LDA class score4: with and . Classifier counts for : one-vs-rest 5, one-vs-one 10.
Worked example
Bernoulli naive Bayes with features (free, meeting, link). Spam: ; ham: . New message :
- Plain counting: spam ; ham ; so .
- Laplace smoothing: spam ; ham ; so .
- Message : "meeting" never occurs in spam, so without smoothing spam scores exactly 0; with smoothing .
Costs. for classes A, B, C; predicting A when the truth is C costs 8, every other mistake 1. Expected costs: A , B , C . 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 and , and the last line matches the smoothed hand computation.
Common pitfalls
- Multiclass (exactly one of classes) is not multilabel (several labels at once).
- One-vs-rest and one-vs-one are ways to combine binary classifiers, not classification algorithms.
- Choosing the most probable class is optimal only when all mistakes cost the same.
- Without smoothing a single unseen feature value vetoes a class; Laplace smoothing changes the conditional estimates, not only the priors.
- Naive Bayes is not the Bayes-optimal classifier: its independence assumption is usually wrong, and its probabilities are poorly calibrated even when its decisions are good.
- LDA's boundary is linear only because the covariance is shared; with different covariances the Bayes boundary is quadratic.
- Compare classifiers on held-out data; the highest training accuracy usually belongs to the most overfit model.
- No classifier reaches zero training error when identical inputs carry different labels.
References
- 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)
- Dive into Deep Learning — Sec. 22.9 Naive Bayes (22.9.3 The Naive Bayes Classifier, 22.9.4 Training)
- scikit-learn User Guide — Sec. 1.9 Naive Bayes (intro; 1.9.2 Multinomial Naive Bayes; 1.9.4 Bernoulli Naive Bayes)
- scikit-learn User Guide — Sec. 1.2.2 Mathematical formulation of the LDA and QDA classifiers
- Wikipedia: Bayes estimator — Definition (minimizing the posterior expected loss)