Unit 5, lesson 29

Multiclass Classification and Softmax

How softmax turns class scores into a class probability vector, how multiclass cross-entropy and the log-sum-exp trick train it stably, and how multiclass, multilabel and one-vs-rest setups differ.

  • Video 29
  • Logistic Regression and Likelihood

Each parcel must go to exactly one of three handling routes, the standard conveyor, cold storage or oversized handling. A binary logistic model gives a single probability, but this task needs a probability for every route, all of them nonnegative and adding to 11. Softmax turns a vector of class scores into such a probability vector, and multiclass cross-entropy trains it. This lesson also separates tasks whose classes exclude each other from tasks where several labels can hold at once, and compares softmax with one-vs-rest.

Key terms

Multiclass classification

Definition Multiclass classification is a classification task with K≥3K \ge 3 classes in which every example belongs to exactly one class. The classes must be mutually exclusive and, for the cases the model is meant to handle, together cover every case. The label is coded as an index yy in {1,…,K}\{1, \dots, K\} or as a one-hot vector y\mathbf{y} in {0,1}K\{0, 1\}^K with a single 11 at the true class. A linear multiclass model computes one score per class,

z=Wx+b,\mathbf{z} = W\mathbf{x} + \mathbf{b} ,

where x\mathbf{x} in Rp\mathbb{R}^p holds the pp features, WW is a K×pK \times p weight matrix and b\mathbf{b} is in RK\mathbb{R}^K. The score of class kk is zk=bk+wk⊤xz_k = b_k + \mathbf{w}_k^{\top}\mathbf{x}, where wk⊤\mathbf{w}_k^{\top} is row kk of WW. With K=2K = 2 the task is binary classification.

In plain words Each case gets one answer from a fixed list. Whether a task is multiclass depends on what the labels mean, not on the software. If the routing rules send every parcel to exactly one route, with a stated priority when several properties apply, the route is a multiclass label. The scores can be any real numbers and are not yet probabilities.

Example Number the routes standard, cold and oversized as classes 11, 22 and 33. A parcel routed to cold storage has label y=2y = 2, or one-hot vector (0,1,0)(0, 1, 0). With pp features the matrix WW has 33 rows and pp columns, and the score vector z\mathbf{z} has 33 entries.

Multilabel classification

Definition Multilabel classification is a task with LL binary labels per example, any number of which can equal 11 at the same time, so the target is a vector y\mathbf{y} in {0,1}L\{0, 1\}^L that may contain several ones or none. A common model gives each label its own probability, P(Yl=1∣x)=σ(zl)P(Y_l = 1 \mid \mathbf{x}) = \sigma(z_l) for l=1,…,Ll = 1, \dots, L, and is trained with the sum or mean of the LL binary cross-entropies. These probabilities need not add to 11. Multiplying σ(zl)\sigma(z_l) or 1−σ(zl)1 - \sigma(z_l) across the labels to get the probability of a whole label vector additionally assumes that the labels are conditionally independent given x\mathbf{x}, which may be false.

In plain words A case can have several properties at once, so the model answers LL separate yes or no questions. A single softmax would make the labels compete for one unit of probability, which is wrong when two of them can both be true.

Example Take the properties fragile, chilled and heavy. A parcel that is fragile and chilled but not heavy has target (1,1,0)(1, 1, 0), while the multiclass route target (0,1,0)(0, 1, 0) picks exactly one route. If the three label scores are 11, 0.50.5 and −2-2, the sigmoids give about 0.73110.7311, 0.62250.6225 and 0.11920.1192, which add to about 1.47271.4727 with no contradiction. The summed binary cross-entropy for the target (1,1,0)(1, 1, 0) is about 0.91430.9143. Only under conditional independence would the probability of exactly this label vector be 0.7311⋅0.6225⋅(1−0.1192)≈0.40080.7311 \cdot 0.6225 \cdot (1 - 0.1192) \approx 0.4008.

Softmax function

Definition The softmax function maps a score vector z\mathbf{z} in RK\mathbb{R}^K to the vector p=softmax⁡(z)\mathbf{p} = \operatorname{softmax}(\mathbf{z}) whose entries, for k=1,…,Kk = 1, \dots, K, are

pk=ezk∑j=1Kezj.p_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}} .

The result is a class probability vector, a vector p\mathbf{p} in RK\mathbb{R}^K with pk≥0p_k \ge 0 for every kk and p1+⋯+pK=1p_1 + \cdots + p_K = 1. In a model pkp_k is the modeled probability P(Y=k∣x)P(Y = k \mid \mathbf{x}). For finite scores every softmax entry is strictly positive, so with K≥2K \ge 2 each entry lies strictly between 00 and 11. Adding the same constant cc to every score leaves the output unchanged, because the factor ece^{c} cancels. The ratio of two entries is pj/pk=ezj−zkp_j / p_k = e^{z_j - z_k}, and for K=2K = 2 the first entry is σ(z1−z2)\sigma(z_1 - z_2). Multiplying all scores by a positive constant other than 11 keeps the order of the entries but changes their values unless all scores are equal. When every wrong class costs the same and a correct class costs nothing, predicting a class with the largest pkp_k minimizes the modeled probability of error.

Because of the shift invariance, adding the same vector to every row of WW and the same number to every entry of b\mathbf{b} leaves all the probabilities of a linear softmax model unchanged. Its parameters are therefore determined only up to such a shift unless one class is fixed as a reference with scores 00.

In plain words Exponentiating makes every score positive, and dividing by the total makes the results add to 11. Only differences between scores matter, and a larger gap gives the leading class more probability. To check a proposed probability vector, check that no entry is negative and that the entries add to 11. Passing that check is a mathematical property. Whether cases given probability 1/21/2 for cold storage really need it about half the time is calibration, a separate question checked on held-out data.

Example For scores (ln⁡2,ln⁡3,0)(\ln 2, \ln 3, 0) in the order standard, cold, oversized, the exponentials are 22, 33 and 11 with total 66, so p=(1/3,1/2,1/6)\mathbf{p} = (1/3, 1/2, 1/6). Cold storage has the largest score and the largest probability. Adding 5050 to every score gives the same vector. Doubling the scores gives exponentials 44, 99 and 11 and probabilities (4/14,9/14,1/14)(4/14, 9/14, 1/14), still led by cold storage but more concentrated. A sharper vector is not by itself a better or better calibrated prediction.

Log-sum-exp trick

Definition The log-sum-exp of a score vector z\mathbf{z} in RK\mathbb{R}^K is LSE⁡(z)=ln⁡∑jezj\operatorname{LSE}(\mathbf{z}) = \ln \sum_{j} e^{z_j}, and the logarithms of the softmax probabilities are ln⁡pk=zk−LSE⁡(z)\ln p_k = z_k - \operatorname{LSE}(\mathbf{z}). Let m=max⁡jzjm = \max_j z_j be the largest score and

S=∑j=1Kezj−mS = \sum_{j=1}^{K} e^{z_j - m}

the sum of the shifted exponentials. Since ∑jezj=emS\sum_j e^{z_j} = e^{m} S, the trick computes both quantities as

LSE⁡(z)=m+ln⁡S,ln⁡pk=(zk−m)−ln⁡S.\begin{gathered} \operatorname{LSE}(\mathbf{z}) = m + \ln S , \\[0.4em] \ln p_k = (z_k - m) - \ln S . \end{gathered}

The shifted scores zj−mz_j - m are all at most 00, with at least one equal to 00, so every shifted exponential lies in (0,1](0, 1] and SS lies in [1,K][1, K]. It follows that m≤LSE⁡(z)≤m+ln⁡Km \le \operatorname{LSE}(\mathbf{z}) \le m + \ln K, and the partial derivative of LSE⁡\operatorname{LSE} with respect to zkz_k is pkp_k.

In plain words Exponentials of large scores overflow, and exponentials of very negative scores round to 00. Subtracting the largest score first gives the same probabilities, since softmax ignores a common shift, and keeps every exponential at most 11. Computing log probabilities straight from the shifted scores also avoids taking the logarithm of a probability that has already rounded to 00. The exponential of a very negative shifted score can still round to 00 inside SS, which is harmless because SS is at least 11.

Example For scores (1000,1001,999)(1000, 1001, 999), computing e1000e^{1000} directly overflows, since the largest double-precision number is about 1.8×103081.8 \times 10^{308}, roughly e709.78e^{709.78}. With m=1001m = 1001 the shifted scores are (−1,0,−2)(-1, 0, -2), so S=e−1+1+e−2≈1.5032S = e^{-1} + 1 + e^{-2} \approx 1.5032 and LSE⁡(z)=1001+ln⁡S≈1001.4076\operatorname{LSE}(\mathbf{z}) = 1001 + \ln S \approx 1001.4076. The probabilities are about 0.24470.2447, 0.66520.6652 and 0.09000.0900. If the true class is oversized, its loss is LSE⁡(z)−z3≈2.4076\operatorname{LSE}(\mathbf{z}) - z_3 \approx 2.4076.

Multiclass cross-entropy

Definition For one example with true class tt, one-hot target y\mathbf{y} and softmax probabilities p=softmax⁡(z)\mathbf{p} = \operatorname{softmax}(\mathbf{z}), the multiclass cross-entropy is

L(z,y)=−∑k=1Kykln⁡pk=−ln⁡pt=LSE⁡(z)−zt.\begin{aligned} L(\mathbf{z}, \mathbf{y}) &= -\sum_{k=1}^{K} y_k \ln p_k \\[0.4em] &= -\ln p_t \\[0.4em] &= \operatorname{LSE}(\mathbf{z}) - z_t . \end{aligned}

Its gradient with respect to the scores has entries pk−ykp_k - y_k, because the derivative of LSE⁡(z)\operatorname{LSE}(\mathbf{z}) with respect to zkz_k is pkp_k and the derivative of ztz_t with respect to zkz_k is 11 for k=tk = t and 00 otherwise. Training minimizes the average R^=1n∑iL(zi,yi)\hat{R} = \frac{1}{n}\sum_{i} L(\mathbf{z}_i, \mathbf{y}_i) over the nn training examples, often plus a penalty. If the labels are conditionally independent given their features and the parameters, this average is the categorical negative log likelihood divided by nn, so minimizing it is maximum likelihood. For K=2K = 2 it is the binary cross-entropy of the previous lesson.

In plain words Only the probability of the true class enters the loss, but softmax ties it to every score, so raising that probability lowers the total of the others. A gradient step raises the true class’s score in proportion to 1−pt1 - p_t and lowers each other score in proportion to its probability. The loss measures confidence as well as correctness, so two models that predict the same classes can have very different cross-entropy.

Example For p=(1/3,1/2,1/6)\mathbf{p} = (1/3, 1/2, 1/6) and true class cold, the loss is −ln⁡(1/2)=ln⁡2≈0.6931-\ln(1/2) = \ln 2 \approx 0.6931. If the true class were oversized, the same prediction would cost ln⁡6≈1.7918\ln 6 \approx 1.7918. With true class cold the gradient is (1/3,−1/2,1/6)(1/3, -1/2, 1/6), and a step of size 0.60.6 taken on the scores themselves changes them by −0.2-0.2, +0.3+0.3 and −0.1-0.1. The probability of cold rises to about 0.61430.6143 and the loss falls to about 0.48720.4872. In a real linear model the step updates the shared WW and b\mathbf{b}, so it changes the scores of every example. A model that gave cold storage probability 0.90.9 would make the same decision with loss −ln⁡0.9≈0.1054-\ln 0.9 \approx 0.1054.

One-vs-rest

Definition One-vs-rest, also called one-vs-all, reduces a KK-class problem to KK binary problems. For each class kk a separate binary classifier is trained with class kk as the positive class and all other classes together as the negative class, and it returns a score or an estimated probability qk(x)q_k(\mathbf{x}). A new case is assigned to a class with the largest of these KK outputs, which presumes they are on comparable scales. The KK objectives are fitted separately, so the qk(x)q_k(\mathbf{x}) need not add to 11. Dividing them by their sum afterward gives a vector that adds to 11, but it does not make the training a softmax cross-entropy fit.

In plain words Softmax regression fits all classes together, with one shared denominator and one categorical loss. One-vs-rest asks KK separate questions of the form “this class or not” and compares the answers. Which approach predicts better on new data is a question for validation, and neither one wins on every problem. For multilabel tasks separate sigmoids are the natural model, because there the probabilities should not be forced to add to 11.

Example To compare only the output functions, apply a sigmoid to each of the scores (ln⁡2,ln⁡3,0)(\ln 2, \ln 3, 0) instead of softmax. The results are 2/32/3, 3/43/4 and 1/21/2, which add to 23/12≈1.91723/12 \approx 1.917, while softmax of the same scores gives (1/3,1/2,1/6)(1/3, 1/2, 1/6). Separately fitted one-vs-rest classifiers would not learn these same scores, so this compares two conversions, not two trained models. Both pick cold storage here.

Check yourself

  1. For three mutually exclusive classes, decide which of these vectors are valid class probability vectors, and whether a valid one could be the softmax of finite scores. The vectors are (0.2,0.5,0.4)(0.2, 0.5, 0.4), (0.6,0.45,−0.05)(0.6, 0.45, -0.05) and (0.7,0.3,0)(0.7, 0.3, 0).
Show the answer

The first vector is invalid, since its entries add to 1.11.1. The second adds to 11 but has a negative entry, and a sum of 11 cannot rescue a negative probability, so it is invalid too. The third has no negative entry and adds to 11, so it is a valid probability vector. It cannot be the softmax of finite scores, because every softmax entry is strictly positive. A model that output it would also have infinite cross-entropy on any case from the third class.

  1. Scores in the order standard, cold, oversized are (ln⁡6,ln⁡3,0)(\ln 6, \ln 3, 0), and the true class is cold. Find the probability vector, the predicted class when all errors cost the same, and the cross-entropy. What changes if 100100 is added to every score, and what if every score is doubled?
Show the answer

The exponentials are 66, 33 and 11 with total 1010, so the probabilities are (0.6,0.3,0.1)(0.6, 0.3, 0.1), which are positive and add to 11. Standard has the largest probability and is the prediction, so this case is misclassified. The loss uses the probability of the true class,

−ln⁡0.3=ln⁡103≈1.2040.-\ln 0.3 = \ln \frac{10}{3} \approx 1.2040 .

Adding 100100 to every score changes nothing, since softmax depends only on differences. Doubling gives exponentials 3636, 99 and 11 and probabilities (36/46,9/46,1/46)≈(0.7826,0.1957,0.0217)(36/46, 9/46, 1/46) \approx (0.7826, 0.1957, 0.0217). The wrong prediction becomes more confident, and the loss rises to ln⁡(46/9)≈1.6314\ln(46/9) \approx 1.6314.

  1. Each support ticket is sent to exactly one team, billing, technical or shipping, and can also carry any of the tags urgent, refund request and repeat contact. Which part is multiclass and which is multilabel, and what output suits each? For the team, someone trains three one-vs-rest classifiers, gets 0.70.7, 0.60.6 and 0.20.2 for one ticket, and reports these as the probabilities of the three teams. What is wrong?
Show the answer

The team is a multiclass label, provided the routing rules make the teams exclusive and cover every ticket, so a softmax over three scores fits and its probabilities add to 11. The tags are multilabel, since a ticket can be urgent and a repeat contact at once, so three sigmoids trained with binary cross-entropy fit, and their probabilities may add to more or less than 11. The one-vs-rest outputs add to 1.51.5, so they are not a probability vector over three exclusive teams. Choosing billing, the largest output, is a reasonable decision if the three classifiers give comparable scores. Dividing by 1.51.5 gives about (0.467,0.4,0.133)(0.467, 0.4, 0.133), which adds to 11, but those numbers were not trained as joint class probabilities, so they need a calibration check on held-out data, or a softmax model can be fitted instead.

How this lesson connects