Skip to content
BIASED

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 {0,1}\{0, 1\} for logistic regression and {−1,+1}\{-1, +1\} 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 KK classes.
  • Multilabel: each object has a set of labels of any size, the empty set included.

Notation for this topic. Classes are 1,…,K1, \dots, K, and the label is y∈{1,…,K}y \in \{1, \dots, K\}. Its one-hot vector y∈{0,1}K\mathbf y \in \{0, 1\}^K has a single 1 in position yy. A linear model gives each class a score zk=⟨wk,x⟩+bkz_k = \langle w_k, x\rangle + b_k. The rows wkw_k form a weight matrix WW, so z=Wx+bz = Wx + b. The predicted class is the one with the largest score:

y^=arg⁡max⁡kzk.\hat y = \arg\max_k z_k .

The running example is the digits set of scikit-learn: 1,797 images of 8×88 \times 8 pixels, 64 features each, half for training and half for testing. There are three ways to get the KK scores. Two of them split the problem into binary ones; the third trains one model with KK outputs.

One-vs-rest

The simplest reduction trains KK binary classifiers. Classifier kk separates class kk from all the others: class kk is labelled 1 (or +1+1 for an SVM), the rest 0 (or −1-1). Its score is fk(x)f_k(x), and the prediction is the class with the highest score, y^=arg⁡max⁡kfk(x)\hat y = \arg\max_k f_k(x). The cost is KK binary trainings, each on all nn 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 f3(x)=2f_3(x) = 2 comparable to f7(x)=2f_7(x) = 2. 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: xx is normal with variance 1 around −2-2, 00 and 22, 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 ∓2.11x−2.17\mp 2.11x - 2.17. The middle model gets weight 0 and predicts 1/31/3 everywhere.

So the middle class wins only where both outer models drop below 1/31/3, for ∣x∣<0.70\lvert x\rvert \lt 0.70. The Bayes rule from the topic What machine learning is gives it ∣x∣<1\lvert x\rvert \lt 1. The recall of the middle class drops from 0.680.68 to 0.510.51, and the accuracy from 0.7880.788 to 0.7740.774.

Linear scores are not the culprit. The argmax of (−2x−2, 0, 2x−2)(-2x - 2,\ 0,\ 2x - 2) picks the middle class exactly for ∣x∣<1\lvert x\rvert \lt 1. 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, K(K−1)/2K(K-1)/2 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 2n/K2n/K objects. Whether that is cheaper depends on how the training cost grows with the sample. Say training on mm objects costs mam^a. Then one-vs-rest costs KnaK n^a, and one-vs-one costs

K(K−1)2(2nK)a.\frac{K(K-1)}{2}\Big(\frac{2n}{K}\Big)^a .

For a learner linear in the sample, a=1a = 1, both are about KnKn. A kernel SVM from the previous topic works with an m×mm \times m Gram matrix, so aa 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 K(K−1)/2K(K-1)/2 classifiers run on every input. Each of them also votes on objects of the other K−2K - 2 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 0.9530.953, and one-vs-one with 45 models reaches 0.9660.966. 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 KK 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:

pk=softmax⁡(z)k=ezk∑j=1Kezj.p_k = \operatorname{softmax}(z)_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}} .

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 N(μk,Σ)N(\mu_k, \Sigma) with priors πk\pi_k and a shared covariance. The quadratic term −12x⊤Σ−1x-\tfrac12 x^\top \Sigma^{-1} x is the same for every class and cancels, so the posterior is the softmax of linear scores

zk=⟨Σ−1μk, x⟩−12μk⊤Σ−1μk+log⁡πk.z_k = \langle \Sigma^{-1}\mu_k,\ x\rangle - \tfrac12 \mu_k^\top \Sigma^{-1} \mu_k + \log \pi_k .

For the three classes on the line these are (−2x−2, 0, 2x−2)(-2x - 2,\ 0,\ 2x - 2), up to a common constant: the optimal scores of the previous block. Softmax regression, also called multinomial logistic regression, keeps this form and fits WW and bb 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:

L=−log⁡py=−∑kyklog⁡pk=−zy+log⁡∑jezj.L = -\log p_y = -\sum_k \mathbf y_k \log p_k = -z_y + \log \sum_j e^{z_j} .

An example. The scores z=(2,1,0.1)z = (2, 1, 0.1) give ez=(7.389,2.718,1.105)e^z = (7.389, 2.718, 1.105), which sum to 11.21211.212, so p=(0.659,0.242,0.099)p = (0.659, 0.242, 0.099). If the true class is 1, the loss is −log⁡0.659=0.417-\log 0.659 = 0.417. On the digits, one softmax model reaches a test accuracy of 0.9630.963: 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:

∂L∂z=p−y,∂L∂W=(p−y) x⊤,∂L∂b=p−y.\frac{\partial L}{\partial z} = p - \mathbf y, \qquad \frac{\partial L}{\partial W} = (p - \mathbf y)\, x^\top, \qquad \frac{\partial L}{\partial b} = p - \mathbf y .

Predicted minus observed: the same pattern as the residual of least squares and the p−yp - y of the topic Logistic regression. In the example, p−y=(−0.341,0.242,0.099)p - \mathbf y = (-0.341, 0.242, 0.099).

Read it as a rule for a gradient step. The true class has the component py−1<0p_y - 1 \lt 0, so a step against the gradient raises its score, in proportion to 1−py1 - p_y. Every other class has the component pk>0p_k \gt 0, 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, py≈1p_y \approx 1, contributes almost nothing. The components of p−yp - \mathbf y always sum to zero.

The loss is convex. Its Hessian in the scores is

H=diag⁡(p)−pp⊤,H = \operatorname{diag}(p) - pp^\top ,

the Hessian of log-sum-exp from the topic Convex sets and functions. There, v⊤Hvv^\top H v turned out to be a variance, so it is never negative. The scores are linear in WW and bb, 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 cc to every score. The numerator and the denominator of the softmax are both multiplied by ece^c, so

softmax⁡(z+c1)=softmax⁡(z).\operatorname{softmax}(z + c\mathbf 1) = \operatorname{softmax}(z) .

Only differences of scores matter. This is the direction (1,…,1)(1, \dots, 1) in which the Hessian of the previous block has zero curvature. Two consequences follow.

The parameters are not unique. Add the same vector vv to every wkw_k and the same number to every bkb_k. All scores shift by the same ⟨v,x⟩+c\langle v, x\rangle + c, and no probability changes. One fix is a reference class with wK=0w_K = 0 and bK=0b_K = 0; for K=2K = 2 this gives p1=σ(z1−z2)p_1 = \sigma(z_1 - z_2), 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 (−2,0,2)(-2, 0, 2) and the intercepts (−0.667,1.333,−0.667)(-0.667, 1.333, -0.667) instead of (−2,0,−2)(-2, 0, -2). This is the same posterior, shifted by 4/34/3. 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 z=(1000,999)z = (1000, 999) the naive formula overflows, while softmax⁡(0,−1)=(0.731,0.269)\operatorname{softmax}(0, -1) = (0.731, 0.269) is the same answer, computed safely. The loss is computed the same way, as −zy+max⁡jzj+log⁡∑jezj−max⁡jzj-z_y + \max_j z_j + \log \sum_j e^{z_j - \max_j z_j}.

Micro and macro averages

Precision, recall and F1F_1 from the topic Classification metrics are defined for one class against the rest. With KK classes there are KK such tables: TPk\mathrm{TP}_k, FPk\mathrm{FP}_k and FNk\mathrm{FN}_k count the true positives, false positives and false negatives of class kk. There are three ways to combine them.

  • Macro averaging computes the metric per class and averages the KK numbers. Every class counts equally, however rare.
  • Micro averaging sums TPk\mathrm{TP}_k, FPk\mathrm{FP}_k and FNk\mathrm{FN}_k 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 FP\mathrm{FP} and of FN\mathrm{FN} both equal the number of errors, and micro precision, micro recall and micro F1F_1 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 F1F_1, is 87/100=0.8787/100 = 0.87. Per class, F1=2TP/(2TP+FP+FN)F_1 = 2\mathrm{TP}/(2\mathrm{TP} + \mathrm{FP} + \mathrm{FN}) is 152/165=0.921152/165 = 0.921 for A, 18/27=0.66718/27 = 0.667 for B and 4/8=0.54/8 = 0.5 for C. The macro F1F_1 is their mean, 0.6960.696. The weighted F1F_1 is 0.8620.862, 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 y∈{0,1}K\mathbf y \in \{0, 1\}^K with any number of ones: the tags of a photo, the topics of an article. The standard model gives each label its own sigmoid:

P(y∣x)=∏k=1Kpkyk(1−pk)1−yk,pk=σ(⟨wk,x⟩+bk).P(\mathbf y \mid x) = \prod_{k=1}^K p_k^{\mathbf y_k} (1 - p_k)^{1 - \mathbf y_k}, \qquad p_k = \sigma(\langle w_k, x\rangle + b_k) .

The product says that the labels are conditionally independent given xx. Its negative logarithm is a sum of KK binary cross-entropies, so this is KK 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 xx still co-occur in the predictions. Dependence that remains once xx 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 ZiZ_i with the true set YiY_i.

  • Hamming loss: the share of wrong label decisions, 1nK∑i∣Yi△Zi∣\frac{1}{nK} \sum_i \lvert Y_i \triangle Z_i\rvert, where △\triangle is the symmetric difference.
  • Subset accuracy (exact match): the share of objects whose whole set is right. It is harsh for large KK.
  • Jaccard index ∣Yi∩Zi∣/∣Yi∪Zi∣\lvert Y_i \cap Z_i\rvert / \lvert Y_i \cup Z_i\rvert, averaged over objects.
  • Micro and macro F1F_1 over labels, as for many classes. Micro F1F_1 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 0.2160.216, yet get the whole set right for only 0.3510.351 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 KK 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.