Loss Functions & Output Units
The last layer is where a network's hidden representation meets the task. Choosing an output unit and a loss is not two independent choices; maximum likelihood fixes the pair.
╌╌╌╌
A network's hidden layers learn a representation ; the output unit is the thin final transform that turns into a prediction, and the loss scores that prediction against the target. These two are not chosen independently. Fix the conditional distribution you intend the network to model, and maximum likelihood determines the output activation and the loss as a matched pair. The whole lesson is one table and the derivations behind its five rows.
| task | output unit | output activation | loss | |
|---|---|---|---|---|
| regression | 1 linear | identity | mean squared error | Gaussian |
| binary | 1 logit | sigmoid | binary cross-entropy | Bernoulli |
| multiclass | logits | softmax | categorical cross-entropy | Categorical |
| multi-label | logits | sigmoid (per class) | sum of binary cross-entropies | independent Bernoullis |
| count | 1 logit | softplus | Poisson negative log-likelihood | Poisson |
The pattern is rigid: pick the distribution that matches the target's type — real, binary, one-of-, several-of-, a nonnegative integer — let its natural parameter be the network's pre-activation, and the loss is the negative log-likelihood of that distribution. The rest of the lesson derives each row.1
Maximum likelihood is the loss
Every row above is one instance of a single principle. The network outputs the parameters of a conditional distribution , and training maximizes the likelihood of the observed targets, equivalently minimizes the negative log-likelihood (NLL).
This single choice removes the guesswork from loss design: the loss is read off as for whichever suits the target. Two consequences recur throughout.2
- The output activation is whatever maps an unbounded score into a valid parameter of — a probability needs , so a sigmoid; a rate needs , so a softplus.
- The in the NLL undoes the in every exponential-family output unit, and that cancellation is why the gradients below collapse so cleanly. A loss without that — squared error on a sigmoid — leaves the intact and the gradient saturates.
The second consequence is worth making precise, because it is the mechanism behind every clean gradient in this lesson. An exponential-family output writes the model probability as for some score and normalizer . Taking the negative log turns the ratio into a difference,
so the that built the probability is gone and the loss is linear in the score plus a smooth log-normalizer. Differentiating a linear term gives a constant, and differentiating returns the model's own predicted probabilities. The two pieces combine into with no leftover and no activation derivative multiplying the signal. Drop the — square the residual of a sigmoid instead — and the survives inside the gradient as the factor , which vanishes exactly where the model is most wrong. The last section of this lesson shows that failure numerically.
Regression: linear output, squared error
For a real-valued target take with the mean predicted by an identity output, , and fixed. The NLL is
Drop the additive constant and the scale, and the loss is the mean squared error . Squared error is not an arbitrary penalty but the log-likelihood of a Gaussian with fixed variance. Its gradient with respect to the score is the residual, with no saturating factor:
Because the output is the identity, this residual passes straight to the weights as . The lesson's recurring theme — gradient equals prediction minus target — starts here, in its simplest form.
Softmax: the multiclass output unit
For a one-of- label, the network emits a vector of scores (logits
)
, and the softmax turns them into a categorical
distribution over the classes.
The figure traces the three stages (score, exponentiate, normalize) that carry a logit vector to a probability distribution.
Softmax inherits two structural facts. It is shift-invariant: adding a constant to every logit multiplies numerator and denominator by and leaves unchanged. And the raw form overflows: explodes for large logits. Both are fixed at once by subtracting the maximum logit before exponentiating, which is the form every library actually computes.
A temperature rescales the logits before the softmax, , interpolating between a one-hot argmax () and the uniform distribution (). The bar chart shows the same logits sharpened and flattened.
The softmax + cross-entropy gradient
The matched loss for a softmax output is the categorical cross-entropy. With a one-hot target (so for the true class and otherwise),
The result that makes this pairing canonical is that the gradient with respect to the logits collapses to the residual . Derive it by differentiating through the softmax. First the log-sum-exp:
The first term is the indicator , which is precisely for a one-hot target; the second term is by the softmax definition. Therefore, for every coordinate,
This is the central fact of classification training. The error signal passed back to the network is just predicted distribution minus true distribution, with no activation derivative attenuating it.3
A worked pass through the numbers
For example, take classes with true class (so the one-hot target is ), and logits . The stable softmax subtracts :
Dividing gives the predicted distribution , which sums to and is identical to what the naive formula returns. The per-example loss is nats. The gradient with respect to the logits is one subtraction, :
The true-class logit gets a negative gradient, so gradient descent raises ; the two wrong-class logits get positive gradients, so descent lowers them. The magnitudes sum to zero (), a direct consequence of : softmax cross-entropy only ever redistributes probability mass, never creates or destroys it. In a minibatch of examples the logits are a matrix , the softmax acts row-wise, and the gradient has the same shape as the logits, ready to seed the backward pass.
Binary: sigmoid + binary cross-entropy
The two-class case is softmax with collapsed to a single logit. Model with the logistic sigmoid, take , and the Bernoulli NLL is the binary cross-entropy
Using , the awkward from the log derivative is cancelled by the sigmoid's own derivative, leaving the same residual:
This is the binary specialization of the softmax result, and it is why both output units share one backward implementation: combine the activation and the loss into a single op whose gradient is , never materializing the unstable intermediate .
Why squared error is wrong for a classifier
A tempting mistake is to keep MSE but put it on a sigmoid output, with . The problem is the gradient with respect to the score. By the chain rule it picks up the sigmoid's derivative as a multiplicative factor:
The factor causes saturation. When the model is confidently wrong — say but , so — the residual is large, yet drives the MSE gradient to nearly zero. The example that most needs correcting produces almost no learning signal. Cross-entropy has no such factor, so its gradient stays order exactly where it matters. The table below quantifies the failure.4
| state | |||||
|---|---|---|---|---|---|
| confidently wrong | |||||
| uncertain | |||||
| confidently right |
The first row is the key case: a weaker gradient on the worst prediction. Two figures plot the comparison: first the per-example loss as a function of the predicted probability of the true class, then the gradient magnitude across the score.
The BCE curve approaches its maximum gradient exactly in the region where the model is most wrong (); the MSE curve collapses to zero at both extremes, learning slowly precisely when it should learn fastest.
The output-unit map
Every row of the master table is the same construction applied to a different target type. The branching diagram fixes the mapping from what kind of thing is to the output unit and loss that maximum likelihood forces.
Two rows of the table extend the binary and count cases.
Multi-label. When an example may carry several labels at once (an image tagged
both beach
and sunset
), the classes are not mutually exclusive, so softmax is
wrong: it forces . Instead apply an independent sigmoid per
class and sum binary cross-entropies,
which is the NLL of independent Bernoullis. Each logit's gradient is its own residual .
Count. For a nonnegative integer target (events per interval) model with rate . The NLL drops the data-only term:
Softplus keeps the rate strictly positive while staying smooth, where a bare would overflow and a ReLU would kill the gradient at .
When the network predicts its own uncertainty
The regression row fixed and threw it away. Nothing forces that. If the target's noise varies across inputs (quiet in one region of , noisy in another), the network can predict the variance too. This is a heteroscedastic Gaussian output: two heads, for the mean and for the variance. The NLL keeps both terms this time:
The first term is a squared error weighted by the network's own confidence: where the model predicts small it is penalized heavily for being wrong, and where it predicts large the residual is discounted. The second term, , penalizes that discount, and it blocks the trivial solution of setting to zero out the first term. The two terms balance at the true noise level, so the network learns a calibrated variance alongside the mean.
A mixture-density network (MDN) goes further when the target is genuinely multimodal, one that maps to several plausible where any single Gaussian would average them into an implausible midpoint. The output parameterizes a mixture of Gaussians, emitting mixing weights through a softmax over components, plus a mean and variance per component:
The loss is still a negative log-likelihood, but now of a mixture, so the log sits outside the sum and does not collapse into a clean residual. The principle is unchanged though: pick the conditional distribution that matches the target, and the loss is .3
Label smoothing and class imbalance
Two practical edits to the target keep cross-entropy well-behaved. Both modify , not the loss.
Label smoothing. A hard one-hot target requires , which is reachable only as — the logits grow without bound and the model becomes overconfident. Label smoothing replaces the one-hot target with a softened version that mixes in the uniform distribution:
for a small (commonly ). The cross-entropy minimum now sits at finite logits, regularizing confidence and improving calibration.5
Class imbalance. When one class dominates the data, the majority dominates the averaged loss and the minority's gradient is negligible. The standard fix reweights each class's contribution by a factor inversely related to its frequency:
with the count of class . This restores per-class influence without touching the architecture; the gradient is simply scaled per example by .
Losses beyond maximum likelihood
Maximum likelihood is the base construction, but three widely used losses extend it in ways Goodfellow predates or treats only in passing.
Focal loss down-weights the easy examples. Class reweighting scales by label
frequency, but in extreme imbalance (dense object detection, where background
boxes
outnumber objects thousands to one) even the correctly classified easy
negatives dominate the summed gradient. Lin et al.'s focal loss (2017) multiplies
the cross-entropy of each example by , so a confident correct
prediction () contributes almost nothing and the loss concentrates
on the hard, still-misclassified cases. It is cross-entropy with a per-example
confidence gate, and it is the modern default wherever imbalance is severe.
Calibration is a separate axis from accuracy. The clean gradient trains a classifier to be accurate, but a network can be accurate and still badly calibrated — its softmax probabilities systematically over- or under-state the true likelihood. Guo et al. (2017) documented that modern deep nets are overconfident and that a one-parameter fix, temperature scaling — dividing the logits by a scalar tuned on held-out data, exactly the temperature of the softmax section — recovers calibration without touching accuracy. Label smoothing above is the training-time cousin of the same concern. The lesson from the literature is that the loss you minimize and the probabilities you can trust are related but not identical.
Contrastive losses are structurally cross-entropy. Self-supervised learning
trains without labels by a loss that is structurally the softmax cross-entropy of
this lesson. The InfoNCE objective (van den Oord et al., 2018; SimCLR, Chen et
al., 2020) treats one positive pair against negatives as an -way
classification problem: the logits are similarities, the target is the positive is class ,
and the loss is of the softmax over similarities. The residual
gradient derived here drives it too — the same output unit doing a
different job.6
The shared backward op
Across four of the five rows the backward pass is identical: the gradient at the score is the residual . That is the practical payoff of letting maximum likelihood choose the pairing: the forward unit and the loss are designed together so their derivatives cancel into one subtraction.
- 1if task is regression then
- 2identity output
- 3else if task is binary or multi-label then
- 4per-logit Bernoulli
- 5else if task is multiclass then
- 6stable softmax
- 7one residual, no activation-derivative factor
- 8returngradient w.r.t. the logits, ready for backprop
The lesson reduces to one instruction: choose the output distribution that matches the target's type, and the activation, the loss, and this clean residual gradient all follow. The matched pair then plugs straight into backpropagation as the seed of the backward pass, and into the optimizer as the gradient it descends.
Footnotes
- Chollet, Deep Learning with Python, Ch. 4–6 — the last-layer-activation/loss cheat sheet: sigmoid+
binary_crossentropy, softmax+categorical_crossentropy, linear+mse, the practical face of the maximum-likelihood pairing. ↩ - Goodfellow, Deep Learning, §6.2.1 — Learning Conditional Distributions with Maximum Likelihood: the loss is the negative log-likelihood , not an arbitrary penalty. ↩
- Goodfellow, Deep Learning, §6.2.2 — Output Units: linear/Gaussian, sigmoid/Bernoulli, and softmax/Categorical units, and why each pairs with the matching NLL so the gradient collapses to . ↩ ↩2
- Goodfellow, Deep Learning, §6.2.2.2 / §6.2.1 — why mean squared error on a sigmoid saturates: the factor crushes the gradient exactly when the model is confidently wrong, which the of cross-entropy removes. ↩
- Goodfellow, Deep Learning, §3.13 — Information Theory: cross-entropy, KL divergence, and entropy — the substrate in which NLL minimization equals minimizing , and label smoothing softens the target distribution. ↩
- Primary sources: Lin et al.,
Focal Loss for Dense Object Detection
(2017) for the down-weighting; Guo et al.,On Calibration of Modern Neural Networks
(2017) for temperature scaling; van den Oord et al.,Representation Learning with Contrastive Predictive Coding
(2018) and Chen et al.,SimCLR
(2020) for InfoNCE as a softmax cross-entropy over positives and negatives. ↩
╌╌ END ╌╌