Multiclass and multilabel classification
More than two classes, and several labels per object. One-vs-rest and one-vs-one, softmax regression and the cross-entropy, the gradient p − y and shifting the scores, micro and macro averages, independent sigmoids and metrics for label sets.
More than two classes
The topic Kernels ended on a gap. The SVM and its kernels separate two classes, while digits come in ten and an article can carry several topics at once. Every model so far, from the perceptron to the kernel SVM, answers one question: which of two classes? The classes were for logistic regression and for margins.
Many problems have more. A digit recognizer chooses among ten classes. A language model chooses the next token among tens of thousands. Other problems attach several labels to one object: a news article can be about politics and the economy at once, a photo can show a dog and a beach. These are two different tasks.
- Multiclass: each object has exactly one of classes.
- Multilabel: each object has a set of labels of any size, the empty set included.
Notation for this topic. Classes are , and the label is . Its one-hot vector has a single 1 in position . A linear model gives each class a score . The rows form a weight matrix , so . The predicted class is the one with the largest score:
The running example is the digits set of scikit-learn: 1,797 images of pixels, 64 features each, half for training and half for testing. There are three ways to get the scores. Two of them split the problem into binary ones; the third trains one model with outputs.
One-vs-rest
The simplest reduction trains binary classifiers. Classifier separates class from all the others: class is labelled 1 (or for an SVM), the rest 0 (or ). Its score is , and the prediction is the class with the highest score, . The cost is binary trainings, each on all objects.
The argmax matters. If each classifier only said yes or no, some points would get no yes and others several. The argmax always names one class, but three problems remain.
- Scores on different scales. Each classifier is trained alone, so nothing makes comparable to . SVM scores are not probabilities at all; calibration from the topic Logistic regression helps.
- Imbalance by construction. With ten balanced digits, every binary problem is one against nine.
- A class between others. Its binary model can be wrong in form, whatever the amount of data.
The third problem is the subtle one. Put three classes on a line: is normal with variance 1 around , and , with equal priors. Fit each one-vs-rest logistic model to this distribution itself, so that there is no sampling noise at all. The outer models get the scores . The middle model gets weight 0 and predicts everywhere.
So the middle class wins only where both outer models drop below , for . The Bayes rule from the topic What machine learning is gives it . The recall of the middle class drops from to , and the accuracy from to .
Linear scores are not the culprit. The argmax of picks the middle class exactly for . What fails is the training: each score is fitted alone, to its own binary problem. In high dimension such configurations are rarer, and a well-regularized one-vs-rest is often as accurate as anything else (Rifkin and Klautau, 2004).
One-vs-one
The second reduction, one-vs-one, trains a classifier for every pair of classes, of them, each on the objects of its two classes only. To predict, every pairwise classifier votes, and the class with the most votes wins; ties go to the larger total score.
Each problem is small and balanced: with balanced classes it has about objects. Whether that is cheaper depends on how the training cost grows with the sample. Say training on objects costs . Then one-vs-rest costs , and one-vs-one costs
For a learner linear in the sample, , both are about . A kernel SVM from the previous topic works with an Gram matrix, so is about 2 or more, and one-vs-one wins several times over. That is why LIBSVM, and scikit-learn's SVC built on it, use one-vs-one (Hsu and Lin, 2002).
The price comes at prediction: all classifiers run on every input. Each of them also votes on objects of the other classes, which it has never seen. Its vote there means little; only the count over many pairs makes sense.
On the digits, with L2-regularized logistic regression as the binary learner, one-vs-rest with 10 models reaches a test accuracy of , and one-vs-one with 45 models reaches . Other reductions exist too: error-correcting output codes give each class a binary code word and train one classifier per bit (Dietterich and Bakiri, 1995).
Softmax regression
One model with scores avoids all three problems of one-vs-rest. The scores are trained together, on one scale, against one likelihood. To turn scores into probabilities we need positive numbers that sum to 1. The softmax does that:
The exponential makes every entry positive, and the division makes them sum to 1. The largest score gets the largest probability, and a score far above the rest takes almost all of it. Hence the name: a soft version of the argmax.
Why this form? Two answers are already known. The topic Lagrange multipliers and KKT conditions of Mathematics for ML showed that softmax is the maximum-entropy distribution with a given mean. And Bayes' formula gives a softmax for Gaussian classes with priors and a shared covariance. The quadratic term is the same for every class and cancels, so the posterior is the softmax of linear scores
For the three classes on the line these are , up to a common constant: the optimal scores of the previous block. Softmax regression, also called multinomial logistic regression, keeps this form and fits and directly, without assuming Gaussians.
The topic Logistic regression already met this form in passing; here it becomes a model of its own. The fit is maximum likelihood under the categorical distribution (the topics Maximum likelihood and Discrete distributions of Probability Theory). The loss of one object is minus the log-probability of its true class, the cross-entropy:
An example. The scores give , which sum to , so . If the true class is 1, the loss is . On the digits, one softmax model reaches a test accuracy of : between the two reductions, with one model instead of 10 or 45.
The gradient p − y
The topic Matrix calculus of Mathematics for ML differentiated this loss on the same example. The result, for one object:
Predicted minus observed: the same pattern as the residual of least squares and the of the topic Logistic regression. In the example, .
Read it as a rule for a gradient step. The true class has the component , so a step against the gradient raises its score, in proportion to . Every other class has the component , so its score goes down in proportion to its probability: the most tempting wrong class is pushed hardest. An object the model already gets right with confidence, , contributes almost nothing. The components of always sum to zero.
The loss is convex. Its Hessian in the scores is
the Hessian of log-sum-exp from the topic Convex sets and functions. There, turned out to be a variance, so it is never negative. The scores are linear in and , so the training loss is convex in the parameters too. Gradient descent, the stochastic optimizers of the earlier topics or Newton's method find its minimum, and there are no local minima to fear.
Shifting the scores
Add the same number to every score. The numerator and the denominator of the softmax are both multiplied by , so
Only differences of scores matter. This is the direction in which the Hessian of the previous block has zero curvature. Two consequences follow.
The parameters are not unique. Add the same vector to every and the same number to every . All scores shift by the same , and no probability changes. One fix is a reference class with and ; for this gives , binary logistic regression with a single score. Another fix is the L2 penalty of the topic Regularization. Among all equivalent weight sets it picks the one with the smallest norm, in which the class weights sum to zero.
scikit-learn does not penalize the intercepts, but its solvers return intercepts that sum to zero. On the line, softmax regression gets the weights and the intercepts instead of . This is the same posterior, shifted by . The joint fit recovers exactly the Bayes rule that one-vs-rest missed.
A stable computation. Subtract the largest score before exponentiating, as in the topic Conditioning and numerical stability. For the naive formula overflows, while is the same answer, computed safely. The loss is computed the same way, as .
Micro and macro averages
Precision, recall and from the topic Classification metrics are defined for one class against the rest. With classes there are such tables: , and count the true positives, false positives and false negatives of class . There are three ways to combine them.
- Macro averaging computes the metric per class and averages the numbers. Every class counts equally, however rare.
- Micro averaging sums , and over the classes and computes the metric once. Every object counts equally.
- Weighted averaging averages the per-class metrics with weights proportional to the class sizes.
With one label per object, micro averaging adds nothing. Every error is one false positive, for the predicted class, and one false negative, for the true class. So the totals of and of both equal the number of errors, and micro precision, micro recall and micro all equal the accuracy.
An example: 100 objects with classes of 80, 15 and 5. Rows are true classes, columns are predictions.
| true \ predicted | A | B | C |
|---|---|---|---|
| A (80) | 76 | 3 | 1 |
| B (15) | 6 | 9 | 0 |
| C (5) | 3 | 0 | 2 |
The accuracy, and so the micro , is . Per class, is for A, for B and for C. The macro is their mean, . The weighted is , close to the accuracy, because the large class dominates both.
Which number to report is a question about the task. If finding the 5 objects of class C matters as much as the 80 of class A, the macro average says the classifier is mediocre, and the micro average hides it. Ranking metrics carry over too: ROC AUC can be computed per class against the rest and macro-averaged.
Several labels per object
In a multilabel task the target is a vector with any number of ones: the tags of a photo, the topics of an article. The standard model gives each label its own sigmoid:
The product says that the labels are conditionally independent given . Its negative logarithm is a sum of binary cross-entropies, so this is logistic regressions trained side by side, an approach called binary relevance. The difference from softmax is the normalization. Softmax makes the classes compete for one unit of probability; independent sigmoids let any number of labels be likely at once, or none. Each label gets its own threshold, tuned on validation data as in the topic Classification metrics: a label present in 2% of objects rarely deserves the default 0.5. Labels that depend on the same features of still co-occur in the predictions. Dependence that remains once is known is lost; classifier chains, which feed the predictions for earlier labels as features to the next ones, recover some of it (Read et al., 2011).
Multilabel metrics compare a predicted set with the true set .
- Hamming loss: the share of wrong label decisions, , where is the symmetric difference.
- Subset accuracy (exact match): the share of objects whose whole set is right. It is harsh for large .
- Jaccard index , averaged over objects.
- Micro and macro over labels, as for many classes. Micro no longer equals any accuracy, since one object can contribute several true positives.
On a synthetic problem with 5 labels, about two per object, independent logistic regressions have a Hamming loss of , yet get the whole set right for only of the test objects. The two metrics measure very different things.
This closes the module on linear classification. Every model in it, binary or with classes, scores an input by a weighted sum of its features, or of features fixed in advance by a kernel. A weighted sum cannot express an interaction by itself. A loan may be risky when the income is low and the debt is high, but not when only one of them holds; then the effect of income depends on debt. A kernel can add such terms, but it has to be chosen in advance, and the inputs must be numbers on comparable scales. Real tables mix money, counts, categories and gaps. The topic Decision trees builds a model out of such conditions: a sequence of yes-or-no questions, each about one feature. It handles any number of classes in its leaves directly and needs no scaling.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.