Multiclass Classification and the Softmax

Machine Learning Notes · note 4 of 6 · Multiclass and the softmax ← The network reference Developing a model →

Logistic regression answers one question: is this a yes or a no? Most real classification problems have more than two answers — a handwritten digit is one of ten, an email is one of several folders, a photograph holds one of a thousand objects. This note generalises the whole of logistic regression to $N$ classes at once. The result is the softmax, and almost nothing else has to change: the derivation is the same argument about log-odds, the loss is the same maximum-likelihood construction, and the gradient comes out in the same prediction minus truth form.

In one line. Give every class its own score $z_j = \vec{w}_j\cdot\vec{x} + b_j$, turn the scores into probabilities with $a_j = e^{z_j} / \sum_k e^{z_k}$, and train on the negative log-probability of the correct class; with $N = 2$ this is logistic regression.

Contents
  1. From two classes to many
  2. The softmax function
  3. Where the softmax comes from
  4. The loss: multiclass cross-entropy
  5. The gradients
  6. Convexity
  7. Softmax as a neural network output layer
  8. The numerical implementation
  9. Multi-label is a different problem
  10. Adam: learning rates that adapt
  11. Binary and multiclass, side by side
  12. Where this goes next

From two classes to many

What logistic regression already gives us

Logistic regression produces a single number and derives the second one from it. With $z = \vec{w}\cdot\vec{x} + b$:

$$ a_1 \;=\; \frac{1}{1 + e^{-z}} \;=\; P\left(y = 1 \mid \vec{x}\right), \qquad a_2 \;=\; 1 - a_1 \;=\; P\left(y = 0 \mid \vec{x}\right). \tag{1} $$
Equation 1: Binary classification. One score, one sigmoid, and the second probability is whatever is left over.

Two probabilities that sum to $1$, from one score. The full story — the sigmoid, the log-odds reading, the log loss and why squared error fails — is in logistic-regression.md; this note picks up exactly where that one leaves off.

What multiclass has to produce

Now let the target take $N$ values, $y \in {1, 2, \ldots, N}$ — ten digits, four folders, a thousand objects. The model can no longer emit one number, because $N-1$ of the probabilities are no longer determined by the first. It has to produce the whole distribution at once:

$$ a_j \;=\; P\left(y = j \mid \vec{x}\right) \quad\text{for } j = 1, \ldots, N, \qquad a_j > 0, \qquad \sum_{j=1}^{N} a_j \;=\; 1 . \tag{2} $$
Equation 2: What a multiclass model outputs: one probability per class, all positive, summing to one. This constraint is the entire design problem.

A vector that is positive everywhere and sums to one is a much stronger requirement than "a number between $0$ and $1$", and it is what rules out the obvious ideas. Running $N$ separate sigmoids gives $N$ numbers in $(0,1)$ that sum to whatever they like. The softmax is the construction that satisfies the constraint by design.


The softmax function

One score per class

Give every class its own weight vector and its own bias, and compute one score per class from the same input:

$$ z_j \;=\; \vec{w}_j\cdot\vec{x} + b_j, \qquad j = 1, \ldots, N, \qquad \text{parameters}\;\; \vec{w}_1, \ldots, \vec{w}_N \;\text{ and }\; b_1, \ldots, b_N . \tag{3} $$
Equation 3: The scores, one per class. Each class gets an independent parameter set, so the model has $N$ weight vectors and $N$ biases; the scores themselves are unrestricted real numbers.

These scores are usually called the logits. Nothing constrains them: a logit can be $-4$ or $+30$. All the work of turning them into probabilities happens in the next step.

Exponentiate and normalise

$$ a_j \;=\; \frac{e^{z_j}}{\displaystyle\sum_{k=1}^{N} e^{z_k}} \;=\; P\left(y = j \mid \vec{x}\right), \qquad a_1 + a_2 + \cdots + a_N \;=\; 1 . \tag{4} $$
Equation 4: The softmax. Exponentiating makes every entry positive; dividing by the total makes them sum to one.

Both requirements from Equation 2 are met, and it is worth seeing how rather than taking it on trust. The exponential $e^{z}$ is positive for every real $z$, however negative — so every numerator is positive, and so is the denominator, being a sum of them. That gives $a_j > 0$. And the denominator is the sum of all the numerators, so adding up the $a_j$ adds up to the denominator over itself:

$$ \sum_{j=1}^{N} a_j \;=\; \sum_{j=1}^{N} \frac{e^{z_j}}{\sum_k e^{z_k}} \;=\; \frac{\sum_j e^{z_j}}{\sum_k e^{z_k}} \;=\; 1 . \tag{5} $$
Equation 5: Why the outputs sum to one: the shared denominator is exactly the sum of the numerators.

That shared denominator is the important structural fact about the softmax, and everything distinctive about it follows from there — including the awkward parts in §7.2 and §8.

A worked example

Take three classes with scores $\vec{z} = \begin{bmatrix} 3.0 & 1.0 & 0.2 \end{bmatrix}$:

Class $j$score $z_j$$e^{z_j}$$a_j = e^{z_j} / 24.025$
$1$$3.0$$20.086$$0.836$
$2$$1.0$$2.718$$0.113$
$3$$0.2$$1.221$$0.051$
total$1.000$
Table 1: Softmax on three scores. The exponentials are computed, then each is divided by their total, $20.086 + 2.718 + 1.221 = 24.025$. A score gap of $2$ becomes a probability ratio of about seven to one.

Read as a prediction: class 1 with about $84\%$ confidence, class 2 at $11\%$, class 3 at $5\%$. Notice how unforgiving the exponential is — class 1 leads class 2 by only $2$ points of score but takes seven times the probability. Softmax turns small score differences into large probability differences, which is what makes it decisive, and also what makes a badly calibrated model badly overconfident.

The classes compete

Because every output shares the one denominator, the probabilities are not computed independently: raising one class's score lowers everyone else's probability, even though their own scores never moved.

Figure 1: Sweeping the first score while the other two are held fixed at $z_2 = 1.0$ and $z_3 = 0.2$. As $z_1$ grows, $a_1$ rises along an S-curve and the other two probabilities fall — not because anything about classes 2 and 3 changed, but because the shared denominator grew. The three curves sum to $1$ at every point on the axis. At $z_1 = 3$ the values are the worked example above.

It contains the sigmoid

Set $N = 2$ and the softmax should reduce to logistic regression, or the generalisation is not one. It does, exactly:

$$ a_1 \;=\; \frac{e^{z_1}}{e^{z_1} + e^{z_2}} \;=\; \frac{1}{1 + e^{-(z_1 - z_2)}} \;=\; \sigma\left(z_1 - z_2\right), \qquad a_2 \;=\; \frac{e^{z_2}}{e^{z_1} + e^{z_2}} \;=\; 1 - a_1 . \tag{6} $$
Equation 6: The two-class softmax. Dividing numerator and denominator by $e^{z_1}$ turns it into the sigmoid of the score difference.

What the collapse teaches. Only the difference $z_1 - z_2$ matters, not the two scores individually. That is why binary logistic regression needs one score and not two: the second is redundant, and fixing $z_2 = 0$ loses nothing. The same redundancy exists for every $N$ — the softmax has one more parameter set than it strictly needs, which is the subject of §3.4.


Where the softmax comes from

The formula in Equation 4 can look arbitrary — why the exponential, and not squaring, or absolute values, which are also positive? It is not arbitrary. Repeat the argument that produced logistic regression, with $N$ classes instead of $2$, and the softmax is what comes out.

Why the derivation starts at the probability

Both derivations begin at $p$, the quantity to be predicted, and work outwards to a linear model — never the other way round. The reason is that $p$ is trapped in $(0,1)$ while $\vec{w}\cdot\vec{x} + b$ ranges over all of $\mathbb{R}$, so the two cannot simply be set equal. Something has to carry $(0,1)$ onto $\mathbb{R}$ first, and the requirements on that link function are strict enough to pin it down almost uniquely:

The function that satisfies them is the log-odds, or logit, $\log\left(p / (1-p)\right)$, and modelling it linearly is the assumption from which everything else follows. Starting instead from an unconstrained linear model and hoping the output behaves like a probability gives up all five properties at once.

Relative log-odds against a reference class

With $N$ classes there is no single "odds" to take, because there is no single alternative — so pick one class as the reference and model the log-odds of every other class against it. Taking class $N$ as the reference:

$$ \log \frac{P\left(y = j \mid \vec{x}\right)}{P\left(y = N \mid \vec{x}\right)} \;=\; \vec{w}_j\cdot\vec{x} + b_j \;=\; z_j, \qquad j = 1, \ldots, N-1 . \tag{7} $$
Equation 7: The multiclass modelling assumption: each class's log-odds relative to the reference class is linear in the input. For $N = 2$ this is exactly the binary assumption.

Exponentiating gives every probability in terms of the reference one:

$$ P\left(y = j \mid \vec{x}\right) \;=\; P\left(y = N \mid \vec{x}\right)\, e^{z_j} . \tag{8} $$
Equation 8: Each class's probability as a multiple of the reference class's probability

Solving for the probabilities

One condition is still unused: the probabilities have to sum to $1$. Impose it and the reference probability is forced.

Summing Equation 8 over all classes, and writing $z_N = 0$ for the reference (its log-odds against itself is $\log 1 = 0$): $$1 = \sum_{j=1}^{N} P(y = j \mid \vec{x}) = P(y = N \mid \vec{x})\sum_{j=1}^{N} e^{z_j},$$ so $P(y = N \mid \vec{x}) = 1 / \sum_j e^{z_j}$. Substituting that back into Equation 8 gives every other class.

$$ P\left(y = N \mid \vec{x}\right) = \frac{1}{\displaystyle\sum_{k=1}^{N} e^{z_k}}, \qquad P\left(y = j \mid \vec{x}\right) = \frac{e^{z_j}}{\displaystyle\sum_{k=1}^{N} e^{z_k}} . \tag{9} $$
Equation 9: The result: the softmax, derived rather than assumed. Nothing was chosen along the way except the modelling assumption in @eq-relative-logodds; the exponential arrived by inverting a logarithm and the denominator by enforcing that probabilities sum to one.

That is Equation 4. The exponential is not a design choice — it is the inverse of the logarithm in the log-odds, and the denominator is not a normalising hack but the unique constant that makes the distribution valid.

The reference class does not matter

Choosing class $N$ as the reference looks like it should bias the model, and it does not, because of a property worth stating on its own: adding the same constant to every score leaves the softmax unchanged.

$$ \text{softmax}\left(z_1 + c, \ldots, z_N + c\right)_j = \frac{e^{z_j + c}}{\sum_k e^{z_k + c}} = \frac{e^{c}\,e^{z_j}}{e^{c}\sum_k e^{z_k}} = \frac{e^{z_j}}{\sum_k e^{z_k}} = \text{softmax}\left(\vec{z}\right)_j . \tag{10} $$
Equation 10: Shift invariance. The factor $e^{c}$ appears in every numerator and in the denominator, and cancels.

Two consequences follow, one theoretical and one intensely practical.


The loss: multiclass cross-entropy

From maximum likelihood

The loss is not invented either. It is the same five-step maximum-likelihood construction used for the binary log loss, with the Bernoulli distribution replaced by the categorical one.

StepMathematicsIn words
Model$p_k^{(i)} = \text{softmax}\left(\vec{z}^{(i)}\right)_k$The predicted probability of class $k$ for example $i$.
Likelihood of one example$L^{(i)} = \prod_{k=1}^{N} \left(p_k^{(i)}\right)^{y_k^{(i)}}$Every exponent is $0$ except the true class's, so only that one factor contributes.
Likelihood of the dataset$L = \prod_{i=1}^{m} L^{(i)}$Examples are assumed independent, so probabilities multiply.
Log-likelihood$\log L = \sum_{i=1}^{m}\sum_{k=1}^{N} y_k^{(i)} \log p_k^{(i)}$The logarithm turns the product into a sum.
Loss to minimise$J = -\frac{1}{m}\log L$Negate to turn "maximise" into "minimise", average to make it independent of $m$.
Table 3: Maximum likelihood to multiclass cross-entropy, one step at a time. Here $p_k^{(i)}$ is the model's predicted probability of class $k$ for example $i$, and $y_k^{(i)}$ is $1$ if $k$ is the true class of example $i$ and $0$ otherwise.
$$ J(W, b) \;=\; -\frac{1}{m}\sum_{i=1}^{m}\sum_{k=1}^{N} y_k^{(i)} \log p_k^{(i)} . \tag{11} $$
Equation 11: Multiclass cross-entropy, also called the categorical negative log-likelihood. It is the loss that softmax outputs are always trained with.

One-hot targets, and what survives the sum

The target $y^{(i)}$ is a class label, but the loss wants a vector. One-hot encoding supplies it: a length-$N$ vector that is $1$ in the position of the true class and $0$ everywhere else. For $N = 4$ and a true class of $3$, $\;y = \begin{bmatrix} 0 & 0 & 1 & 0\end{bmatrix}$.

That makes the inner sum in Equation 11 far less intimidating than it looks. Every term is multiplied by a $y_k^{(i)}$ that is zero except one, so the entire sum over $k$ collapses to a single term:

$$ L^{(i)} \;=\; -\log p_{c}^{(i)}, \qquad\text{where } c \text{ is the true class of example } i . \tag{12} $$
Equation 12: The loss of a single example, once the one-hot target has done its work. Only the probability assigned to the correct class appears; the model's opinion about the other $N-1$ classes is scored only indirectly, through the shared denominator that forced them to fit in the leftover probability.

What the loss does to one example

$-\log p$ is worth looking at directly, because its shape is the whole training signal.

Figure 2: The loss of one example as a function of the probability it gave the correct class. Being right costs nothing: at $p = 1$ the loss is exactly $0$. Being unsure is cheap — $p = 0.5$ costs $0.69$. Being confidently wrong is ruinous, and the curve rises without bound as $p$ approaches $0$. The marked points are the worked example of §2.3 read three ways: if class 1 was correct the loss is $0.18$, if class 2 was correct it is $2.18$, and if class 3 was correct it is $2.98$.

The asymmetry is the point. A loss that just counted mistakes would give the same score to a model that was wrong by a hair and one that was catastrophically, confidently wrong. Cross-entropy punishes confident errors without limit, which is precisely the behaviour you want from a probability model.


The gradients

The derivative with respect to the scores

Everything rests on one result, and it is remarkably clean:

$$ \frac{\partial L}{\partial z_k} \;=\; p_k - y_k . \tag{13} $$
Equation 13: The derivative of one example's loss with respect to the scores. As a vector: $\partial L / \partial \vec{z} = \vec{p} - \vec{y}$, the predicted distribution minus the one-hot truth.

Where it comes from. Write $L = -\log p_c$ with $c$ the true class and $p_c = e^{z_c} / S$, where $S = \sum_j e^{z_j}$. Then $L = -z_c + \log S$, which is much easier to differentiate than it first appears. Since $\partial S / \partial z_k = e^{z_k}$, the second term contributes $e^{z_k}/S = p_k$ for every $k$. The first term contributes $-1$, but only when $k = c$ — and "$1$ when $k$ is the true class, $0$ otherwise" is exactly $y_k$. Adding the two gives $p_k - y_k$, with no case analysis left over.

Compare with logistic regression, where the same derivative is $a - y$. It is the identical statement: how wrong were you, in probability. The exponentials and the shared denominator all cancel, which is not luck — it is the pairing of the softmax with its matching log-likelihood loss, and it is the reason those two are never used apart.

The derivative with respect to the parameters

From the scores to the parameters is one application of the chain rule. Since $z_\ell = \vec{w}_\ell\cdot\vec{x} + b_\ell$, the score $z_\ell$ depends on $\vec{w}_k$ only when $\ell = k$, and then the derivative is just $\vec{x}$:

$$ \frac{\partial J}{\partial \vec{w}_k} \;=\; \frac{1}{m}\sum_{i=1}^{m}\left(p_k^{(i)} - y_k^{(i)}\right)\vec{x}^{(i)}, \qquad \frac{\partial J}{\partial b_k} \;=\; \frac{1}{m}\sum_{i=1}^{m}\left(p_k^{(i)} - y_k^{(i)}\right). \tag{14} $$
Equation 14: The gradients for training. Each class's weight vector is corrected by the average of its own probability error, weighted by the input — the same shape as every gradient in linear and logistic regression.

Read what training actually does with these. For the true class, $y_k = 1$ so $p_k - y_k$ is negative, and the update pushes $\vec{w}_k$ toward $\vec{x}$ — raising that class's score on inputs like this one. For every other class, $y_k = 0$ so $p_k - y_k$ is positive, and the update pushes their weights away. Each example simultaneously promotes one class and demotes the rest, in proportion to how much probability each was wrongly holding.


Convexity

For a linear softmax model — no hidden layers — the cross-entropy loss is globally convex in the parameters, so gradient descent cannot get stuck in a bad local minimum. Three facts compose:

  1. The Hessian in score space is positive semi-definite. For one example with probability vector $\vec{p}$, the second-derivative matrix of the loss with respect to $\vec{z}$ is $H_z = \text{diag}(\vec{p}) - \vec{p}\,\vec{p}^{\mathsf{T}}$ — which is the covariance matrix of a categorical random variable, and every covariance matrix is positive semi-definite.
  2. An affine map preserves convexity. The scores are affine in the parameters, $\vec{z} = W\vec{x} + \vec{b}$, and a convex function composed with an affine map is still convex.
  3. Averaging preserves convexity. The cost is a mean over examples, and a mean of convex functions is convex.

The binary case is the same argument with a scalar in place of a matrix: there the second derivative is $\sigma(z)\left(1 - \sigma(z)\right) > 0$, positive at every $z$, and steps 2 and 3 are unchanged.

The caveat that matters later. This guarantee covers the linear model only. Put a softmax on top of a neural network with hidden layers and the composition is no longer affine — the cost surface becomes non-convex, with all the local minima that implies. The loss is still the right loss and the gradient is still $\vec{p} - \vec{y}$; only the promise about global optimality is lost.


Softmax as a neural network output layer

The architecture

In practice the softmax is rarely used on raw inputs. It is the output layer of a network: hidden layers with ReLU do the representation work, and the final layer has one unit per class with softmax as its activation. For handwritten digits, a standard small network is $25$ ReLU units, then $15$, then $10$ softmax units — one per digit.

Figure 3: A classification network with a softmax output, drawn small. The real digit network has 25 and 15 hidden units and 10 output units; the shape is what matters. Hidden layers use ReLU and each unit computes its own activation independently. The output layer computes one score per class and then passes all of them through the softmax together, which is why it is drawn as one band: the outputs are coupled.

The last layer works exactly like Equation 3, with the previous layer's activations playing the part of $\vec{x}$: each output unit computes its own score from the same incoming vector, and then the softmax is applied across all of them.

The one activation that is not element-wise

Every other activation in a network is a scalar function applied separately to each unit: $a = \text{ReLU}(z)$ or $a = \sigma(z)$, one unit at a time, with no reference to its neighbours. The softmax is the exception. Because of the shared denominator, computing $a_1$ requires $z_1$ and every other score in the layer:

$$ \underbrace{a_j = g\left(z_j\right)}_{\text{ReLU, sigmoid, tanh}} \qquad\text{versus}\qquad \underbrace{a_j = g\left(z_1, z_2, \ldots, z_N\right)_j}_{\text{softmax}} . \tag{15} $$
Equation 15: Element-wise activations against the softmax. Only the softmax needs the whole score vector to produce a single output.

This is worth knowing for two reasons. It is why the softmax layer's backward pass is a genuine Jacobian rather than an element-wise multiply — the $H_z$ of §6 is that Jacobian in disguise. And it is why frameworks treat the softmax as belonging to the loss rather than to the layer, which is the subject of the next section.


The numerical implementation

Roundoff error is real

Before the softmax specifically, a fact about computer arithmetic that this layer makes painful. Computers store numbers in binary, so a decimal like $0.0002$ has no exact representation — it is stored as the nearest available binary fraction, in the same way $1/3$ has no exact decimal. Two calculations that are equal on paper can therefore differ in the answer:

x1 = 2.0 / 10000
print(f"{x1:.18f}")            # 0.000200000000000000

x2 = (1 + 1/10000) - (1 - 1/10000)
print(f"{x2:.18f}")            # 0.000199999999999978

Both should be $0.0002$. The second is wrong in the fourteenth decimal place, and it is wrong for a specific reason: it subtracted two nearly equal large-ish numbers, and the digits they had in common cancelled, leaving only the noisy tail. The error is tiny in absolute terms ($2 \times 10^{-17}$) and it does not matter here — but a loss function that repeats such a step millions of times, and then differentiates through it, is a different matter.

Two ways softmax breaks

Implemented literally — compute $\vec{a}$ with Equation 4, then take $\log a_c$ for the loss — the softmax has two failure modes, and both are routine rather than exotic:

The fix: keep the logits

Both problems come from computing the probability and then its logarithm, as two separate steps. The fix is to never form the probability at all. Expand the loss algebraically:

$$ L \;=\; -\log p_c \;=\; -\log \frac{e^{z_c}}{\sum_k e^{z_k}} \;=\; -z_c + \log\sum_{k=1}^{N} e^{z_k} . \tag{16} $$
Equation 16: The loss written directly in terms of the scores. No probability is ever computed, so nothing can round to zero before the logarithm sees it; subtracting the largest score first also removes any risk of overflow.

This is why frameworks ask you to hand them the raw scores. In practice the output layer is declared with a linear activation and the softmax is folded into the loss:

model = Sequential([
    Dense(25, activation='relu'),
    Dense(15, activation='relu'),
    Dense(10, activation='linear'),        # the scores, NOT the probabilities
])
model.compile(loss=SparseCategoricalCrossentropy(from_logits=True))

from_logits=True is the instruction "these are scores; do the softmax and the logarithm together, the stable way." The cost is that the model's output is no longer a probability, so predictions have to be pushed through a softmax explicitly afterwards. That is the trade the whole ecosystem makes: a little inconvenience at prediction time in exchange for a loss that cannot silently produce infinities during training.


Multi-label is a different problem

There is a problem that looks like multiclass and is not, and mixing them up is a common mistake. Consider a photograph from a car's camera, with three questions: is there a car? a bus? a pedestrian? The answers are not exclusive — a street scene can easily contain all three, or none.

MulticlassMulti-label
QuestionWhich one of $N$?Which of $N$, independently?
ExampleWhich digit is this, $0$ to $9$?Does the image contain a car, a bus, a pedestrian?
Targetone-hot, e.g. $\begin{bmatrix}0&1&0\end{bmatrix}$any pattern, e.g. $\begin{bmatrix}1&0&1\end{bmatrix}$
Outputs sum to$1$, alwaysanything from $0$ to $N$
Output activationone softmax over all unitsa separate sigmoid on each unit
Losscategorical cross-entropybinary cross-entropy, summed over units
Table 4: Multiclass against multi-label. The distinguishing question is whether the classes are mutually exclusive; the answer decides the output activation and the loss.

You could train three completely separate networks, one per question. Usually you do not: one network with three sigmoid output units shares all the hidden layers, so the features that detect "vehicle-shaped thing in the road" are learned once and reused by every output. The architecture is identical to Figure 3 — only the output activation and the loss change.

The one-line test. Ask whether the answers can be simultaneously true. If they cannot, the classes compete for a fixed budget of probability and you want a softmax. If they can, each unit gets its own independent sigmoid, and the shared denominator that makes softmax work would actively get in the way.


Adam: learning rates that adapt

One last piece of practical machinery, because it is what these networks are actually trained with. Plain gradient descent uses one learning rate for every parameter, which the contour picture in linear-regression.md showed to be the wrong tool for a stretched cost surface: too large in the steep directions, too small in the shallow ones.

AdamAdaptive Moment estimation — keeps a separate learning rate for every single parameter and adjusts each one during training, using a simple observation about what the recent gradients have been doing:

What the recent steps look likeWhat it meansWhat Adam does
Consistently in the same directionThe parameter is far from where it needs to be and the path is not in doubtIncrease its learning rate — go faster
Oscillating back and forthThe steps are jumping across a narrow valleyDecrease its learning rate — go slower
Table 5: How Adam adapts each parameter's step. The rule is applied per parameter, so different weights can be moving at very different speeds at the same moment in training.

In code it is a one-line change, and it is close to a default in modern practice — the initial learning rate still has to be set, but the algorithm is dramatically less sensitive to getting it exactly right:

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
    loss=SparseCategoricalCrossentropy(from_logits=True),
)

Binary and multiclass, side by side

Everything above, as one comparison. The right-hand column is the left-hand column with "the other class" replaced by "all the other classes".

TopicBinary, $N = 2$Multiclass, $N \geq 3$
Scores$z = \vec{w}\cdot\vec{x} + b$, one of them$z_k = \vec{w}_k\cdot\vec{x} + b_k$, one per class
Modelled quantitythe log-odds, $\log\frac{p_1}{p_0} = z$pairwise log-odds, $\log\frac{p_k}{p_j} = z_k - z_j$
Scores to probabilitiessigmoid, $p_1 = \frac{1}{1 + e^{-z}}$softmax, $p_k = \frac{e^{z_k}}{\sum_j e^{z_j}}$
LikelihoodBernoulli, $P(y) = p_1^{y}\left(1-p_1\right)^{1-y}$categorical, $P(y) = \prod_k p_k^{y_k}$
Lossbinary cross-entropy, $-\left[y\log p_1 + (1-y)\log p_0\right]$categorical cross-entropy, $-\sum_k y_k \log p_k$
Gradient at the scores$\partial L / \partial z = p - y$$\partial L / \partial \vec{z} = \vec{p} - \vec{y}$
Convexity, linear modelconvex in $\vec{w}, b$convex in $W, b$
Special case$N = 2$ collapses to the sigmoid and the binary loss
Table 6: Logistic regression and softmax regression compared line by line. Every row is the same idea at two sizes, and the last row is the check that the generalisation is a genuine one.

Where this goes next

The classifier is now built and, with Adam, trainable. What is missing is everything about whether it is any good — and that turns out to be a bigger subject than the model itself.

Backwards from here: logistic-regression.md is the two-class model this note generalised, linear-regression.md has the gradient descent and feature-scaling machinery all of it runs on, and neural-networks-reference.md covers the hidden layers that sit underneath the softmax output.

Machine Learning Notes · note 4 of 6 · Multiclass and the softmax ← The network reference Developing a model →