Output Layers and Their Losses
The hidden layers of a network are the same whatever the task; the last layer is not. A house-price model, a spam filter, a digit classifier and a photo tagger can share every hidden layer and differ only in the head: how many outputs the last Linear layer has, what (if anything) is applied to them, which loss compares them with the targets, and in what shape and dtype the targets must arrive. Getting the head wrong rarely crashes. It trains, slowly or badly, which is worse.
The losses themselves (MSE, cross-entropy, their probabilistic meaning) are taught in regression losses and cross-entropy losses, and the gradient of softmax plus cross-entropy is derived in the Mathematics track. This lesson is about the network side: which head, what shape, what the framework expects, and how the numerically stable versions are computed.
Four heads
| Task | Last layer outputs | Output function | Loss | PyTorch loss | Target |
|---|---|---|---|---|---|
| Regression, values | none (identity) | MSE | nn.MSELoss |
float, shape (n, k) |
|
| Binary classification | 1 logit | sigmoid | binary cross-entropy | nn.BCEWithLogitsLoss |
float 0/1, shape (n,) or (n, 1) like the logits |
| Multi-class, classes, exactly one true | logits | softmax | cross-entropy | nn.CrossEntropyLoss |
int64 class index, shape (n,) |
| Multi-label, tags, any subset true | logits | independent sigmoids | BCE per tag | nn.BCEWithLogitsLoss |
float 0/1, shape (n, L) |
A logit is the raw, unbounded output of the last linear layer. In every classification row the output function is listed but not part of the model: PyTorch's losses take logits and apply the sigmoid or softmax internally, in a combined form that is stable. You apply the output function yourself only at prediction time, when you want probabilities.
The stable formulas
For multi-class classification with logits and true class , the loss is the negative log-probability of the true class. Written with log-sum-exp, the softmax never has to be formed:
Subtracting keeps every exponent at most 0, so nothing overflows, and the largest term of the sum is exactly 1, so the logarithm never sees 0. The gradient of with respect to the logits is the famous
and for a batch mean the whole matrix is , with the one-hot targets. It is bounded between and , which is one reason why softmax with cross-entropy trains well. For the binary head with logit the same idea gives
which is what BCEWithLogitsLoss computes. With pos_weight the positive term is multiplied by , useful when positives are rare. MSE with a linear head, , has gradient : the same "prediction minus target" pattern. Each of these heads is the natural pairing of an output function with its log-likelihood, which is why all three gradients look alike.
Multi-class in NumPy
A naive softmax of logits around 1000 overflows; the log-sum-exp form does not. Then a cross-entropy over a batch of 4 with 3 classes, its gradient and a numerical check of all 12 entries:
import numpy as np
def logsumexp(Z):
m = Z.max(axis=1, keepdims=True)
return m + np.log(np.exp(Z - m).sum(axis=1, keepdims=True))
def log_softmax(Z):
return Z - logsumexp(Z)
def cross_entropy(Z, y): # Z: (n, C) logits, y: (n,) class indices
return float(-log_softmax(Z)[np.arange(len(y)), y].mean())
big = np.array([[1000.0, 1001.0, 1002.0]])
with np.errstate(over="ignore", invalid="ignore"):
naive = np.exp(big) / np.exp(big).sum()
print("naive softmax of [1000, 1001, 1002]:", naive.round(4).tolist())
print("stable log-softmax:", log_softmax(big).round(4).tolist(), " probs:", np.exp(log_softmax(big)).round(4).tolist())
rng = np.random.default_rng(0)
Z = rng.normal(0, 2, (4, 3)) # 4 examples, 3 classes
y = np.array([0, 2, 1, 2])
print("loss:", round(cross_entropy(Z, y), 4), " uniform guess would be ln 3 =", round(float(np.log(3)), 4))
# gradient of the mean loss w.r.t. the logits: (softmax(Z) - onehot(y)) / n
P = np.exp(log_softmax(Z))
G = (P - np.eye(3)[y]) / len(y)
num = np.zeros_like(Z); h = 1e-6
for i in range(4):
for j in range(3):
Zp, Zm = Z.copy(), Z.copy(); Zp[i, j] += h; Zm[i, j] -= h
num[i, j] = (cross_entropy(Zp, y) - cross_entropy(Zm, y)) / (2 * h)
print("analytic grad row 0:", G[0].round(4).tolist(), " every row sums to 0:", bool(np.allclose(G.sum(axis=1), 0)))
print("max |analytic - numeric| < 1e-8:", bool(np.abs(G - num).max() < 1e-8))naive softmax of [1000, 1001, 1002]: [[nan, nan, nan]]
stable log-softmax: [[-2.4076, -1.4076, -0.4076]] probs: [[0.09, 0.2447, 0.6652]]
loss: 0.8661 uniform guess would be ln 3 = 1.0986
analytic grad row 0: [-0.1931, 0.034, 0.1592] every row sums to 0: True
max |analytic - numeric| < 1e-8: True
The naive version returns nan (it computes ), while the stable one gives log-probabilities : only the differences between logits matter. The batch loss is 0.8661, below the 1.0986 () of a model that guesses uniformly. The first row of the gradient is : negative for the true class 0 (raise its logit), positive for the others. Each row sums to 0, since both and the one-hot vector sum to 1, and the analytic gradient agrees with the numerical one.
Binary and multi-label in NumPy
import numpy as np
sigmoid = lambda z: 1 / (1 + np.exp(-z))
def bce_naive(z, y):
p = sigmoid(z)
with np.errstate(divide="ignore"):
return -(y * np.log(p) + (1 - y) * np.log(1 - p))
def bce_logits(z, y, pos_weight=1.0): # stable: log(1 + e^-|z|) never overflows
log_p = -(np.maximum(-z, 0) + np.log1p(np.exp(-np.abs(z)))) # log sigmoid(z)
log_1mp = -(np.maximum(z, 0) + np.log1p(np.exp(-np.abs(z)))) # log (1 - sigmoid(z))
return -(pos_weight * y * log_p + (1 - y) * log_1mp)
z = np.array([-40.0, 0.0, 40.0]); y = np.array([1.0, 1.0, 0.0])
print("naive BCE: ", bce_naive(z, y).round(4).tolist())
print("from logits:", bce_logits(z, y).round(4).tolist(), " d/dz = sigmoid(z) - y:", (sigmoid(z) - y).round(4).tolist())
# multi-class vs multi-label for the same logits: one photo, tags [cat, dog, outdoor]
logits = np.array([2.0, 1.5, 1.0])
soft = np.exp(logits - logits.max()); soft /= soft.sum()
print("softmax (exactly one class):", soft.round(3).tolist(), "sum", round(float(soft.sum()), 3))
print("sigmoids (any subset): ", sigmoid(logits).round(3).tolist(), "-> tags", (sigmoid(logits) > 0.5).astype(int).tolist())
# pos_weight: 1 positive per 9 negatives; weighting positives by 9 balances the two loss terms
rng = np.random.default_rng(0)
t = (rng.random(1000) < 0.1).astype(float)
z0 = np.zeros(1000) # a model that always says p = 0.5
for pw in [1.0, 9.0]:
l = bce_logits(z0, t, pw)
print(f"pos_weight {pw:3.0f}: mean loss {l.mean():.4f}, share of loss from positives {l[t == 1].sum() / l.sum():.3f}")naive BCE: [40.0, 0.6931, inf]
from logits: [40.0, 0.6931, 40.0] d/dz = sigmoid(z) - y: [-1.0, -0.5, 1.0]
softmax (exactly one class): [0.506, 0.307, 0.186] sum 1.0
sigmoids (any subset): [0.881, 0.818, 0.731] -> tags [1, 1, 1]
pos_weight 1: mean loss 0.6931, share of loss from positives 0.089
pos_weight 9: mean loss 1.1867, share of loss from positives 0.468
The naive binary cross-entropy for logit 40 with label 0 is inf: rounds to exactly 0 in float64, and . The logit form gives the correct 40.0. Its gradient is , and , never larger than 1 in magnitude.
The same three logits read as a multi-class head become probabilities 0.506, 0.307, 0.186 that sum to 1: the classes compete, and only one can win. Read as a multi-label head they become three independent probabilities, 0.881, 0.818, 0.731, and the photo gets all three tags. Choosing between the two is a modelling decision about the labels, not about the network: "which digit is this?" is multi-class, "which objects are in this photo?" is multi-label.
The last lines show pos_weight. With 1 positive per 9 negatives, a model that always predicts 0.5 gets only 8.9 % of its loss from the positives, so the gradient mostly says "predict negative". With pos_weight 9 their share is 46.8 %, close to balanced. The usual choice is the ratio of negatives to positives per tag; focal loss is the alternative when the imbalance is extreme.
What PyTorch expects
nn.CrossEntropyLoss takes logits of shape (n, C) and either int64 class indices of shape (n,) or float class probabilities of shape (n, C). Three options matter in practice:
label_smoothingreplaces the one-hot target by on the true class plus on every class, so the loss is . It stops the model from pushing logits to infinity and often improves calibration.ignore_index(default ) drops targets with that value from the loss and from the mean, used for padding tokens and unlabelled pixels.weightgives each class a weight; with the defaultreduction='mean'the result is a weighted mean, , not a plain mean of weighted terms.
The recorded example checks each against the NumPy formula, shows two common target mistakes, and runs a multi-label BCEWithLogitsLoss with one pos_weight per tag:
import numpy as np
import torch
from torch import nn
def log_softmax(Z):
m = Z.max(1, keepdims=True); return Z - m - np.log(np.exp(Z - m).sum(1, keepdims=True))
rng = np.random.default_rng(0)
Z = rng.normal(0, 2, (4, 3)); y = np.array([0, 2, 1, 2])
logits, target = torch.tensor(Z), torch.tensor(y) # float64 logits, int64 class indices
L = -log_softmax(Z) # (4, 3) per-class losses in NumPy
ce = nn.CrossEntropyLoss()
print("CE torch", round(ce(logits, target).item(), 4), " numpy", round(float(L[range(4), y].mean()), 4))
eps = 0.1 # label smoothing: target (1 - eps) on the true class + eps / C on every class
smooth = (1 - eps) * L[range(4), y] + eps * L.mean(1)
print("label_smoothing=0.1 torch", round(nn.CrossEntropyLoss(label_smoothing=eps)(logits, target).item(), 4),
" numpy", round(float(smooth.mean()), 4))
t2 = target.clone(); t2[1] = -100 # e.g. padding or an unlabelled pixel
print("ignore_index torch", round(ce(logits, t2).item(), 4),
" numpy (mean over 3 kept)", round(float(L[[0, 2, 3], [0, 1, 2]].mean()), 4))
w = np.array([1.0, 2.0, 0.5]) # class weights
print("weight torch", round(nn.CrossEntropyLoss(weight=torch.tensor(w))(logits, target).item(), 4),
" numpy sum(w_y l)/sum(w_y)", round(float((w[y] * L[range(4), y]).sum() / w[y].sum()), 4))
soft = torch.tensor(np.eye(3)[y] * 0.9 + 0.1 / 3) # probability targets (n, C), float
print("probability targets", round(ce(logits, soft).item(), 4))
for bad in [target.float(), target[:, None]]:
try:
ce(logits, bad)
except Exception as e:
print("target", tuple(bad.shape), bad.dtype, "->", type(e).__name__)
seg = ce(torch.zeros(2, 3, 4, 4), torch.zeros(2, 4, 4, dtype=torch.long))
print("segmentation shapes (2,3,4,4) logits + (2,4,4) targets ->", round(seg.item(), 4))
# multi-label: BCEWithLogitsLoss wants float targets of the same shape as the logits
Zm = torch.tensor([[2.0, -1.0, 0.5], [-3.0, 0.2, 4.0]], dtype=torch.float64)
Ym = torch.tensor([[1.0, 0.0, 1.0], [0.0, 0.0, 1.0]], dtype=torch.float64)
pw = torch.tensor([3.0, 1.0, 1.0], dtype=torch.float64) # one weight per label
bce = nn.BCEWithLogitsLoss(pos_weight=pw, reduction="none")(Zm, Ym)
zn, yn, pn = Zm.numpy(), Ym.numpy(), pw.numpy()
ref = -(pn * yn * np.log(1 / (1 + np.exp(-zn))) + (1 - yn) * np.log(1 - 1 / (1 + np.exp(-zn))))
print("BCEWithLogits pos_weight: per element", np.round(bce.numpy(), 4).tolist())
print("matches numpy:", bool(np.allclose(bce.numpy(), ref)))CE torch 0.8661 numpy 0.8661
label_smoothing=0.1 torch 0.9355 numpy 0.9355
ignore_index torch 0.9655 numpy (mean over 3 kept) 0.9655
weight torch 1.0398 numpy sum(w_y l)/sum(w_y) 1.0398
probability targets 0.9355
target (4,) torch.float32 -> RuntimeError
target (4, 1) torch.int64 -> RuntimeError
segmentation shapes (2,3,4,4) logits + (2,4,4) targets -> 1.0986
BCEWithLogits pos_weight: per element [[0.3808, 0.3133, 0.4741], [0.0486, 0.7981, 0.0181]]
matches numpy: True
Every PyTorch value equals its NumPy formula: 0.8661 for the plain loss (the same as the NumPy example), 0.9355 with label smoothing 0.1, 0.9655 when example 1 is ignored (the mean over the 3 remaining), and 1.0398 with class weights. Passing smoothed probabilities as targets gives exactly the label-smoothing value 0.9355, which shows that label smoothing is nothing more than a soft target. A float target of shape (4,) and an int target of shape (4, 1) both raise a RuntimeError; the second is the classic result of keeping a column vector of labels from pandas. For dense prediction the class axis stays second: logits (2, 3, 4, 4) with targets (2, 4, 4) work, and all-zero logits give per pixel.
Pitfalls
- Softmax in the model and in the loss.
CrossEntropyLossapplies log-softmax itself. A model ending innn.Softmaxtrains, but its logits are squashed into and gradients shrink. End the model withnn.Linear; applysoftmaxonly for reporting probabilities. BCELosson probabilities instead ofBCEWithLogitsLosson logits. The sigmoid-then-log path overflows toinfexactly as in the NumPy example; the logits version is stable and is the one to use.- Wrong target dtype or shape. Class indices must be int64 of shape
(n,); BCE targets must be float and the same shape as the logits.(n, 1)logits against(n,)targets inBCEWithLogitsLossraise an error, and withMSELossthe same mismatch silently broadcasts to(n, n)with only a warning. - Multi-class head for multi-label data. Softmax forces the probabilities to compete; an image with a cat and a dog cannot get high probability for both. Use independent sigmoids.
- Forgetting that
weightchanges the mean. Loss values with and without class weights are not comparable, and neither is a weighted loss across batches with different class mixes. Compare models with a metric, not the weighted loss.
Practice
- A model predicts 5 tags per image with logits of shape
(32, 5). Which loss, and what targets?
Answer
nn.BCEWithLogitsLoss() with a float tensor of 0s and 1s of shape (32, 5). Optionally pos_weight of shape (5,) with the negatives-to-positives ratio of each tag.
- Show that the cross-entropy gradient for one example sums to zero across classes, and explain what that means for the logits.
Answer
. Adding the same constant to all logits does not change the softmax, so the loss has no gradient in that direction; gradient descent only changes the differences between logits.
- Compute by hand the label-smoothed loss for , , when the model gives the true class probability 0.8 and the others 0.1 each.
Answer
; the average of over the three classes is . The smoothed loss is . Note that it is larger than the plain loss: smoothing penalises over-confidence.
- Why does
ignore_indexmatter for language models trained on padded batches?
Answer
Sentences of different lengths are padded to the same length. Without ignore_index, the model would be trained to predict padding tokens, and the mean would be diluted by positions with no real target. Setting the padded targets to removes them from both the sum and the count.
Test yourself
What must the targets of nn.CrossEntropyLoss look like for logits of shape (64, 10) with one true class per example?
- Float one-hot of shape
(64,) - Int64 class indices of shape
(64,) - Int64 of shape
(64, 1) - Float probabilities of shape
(10,)
What is the gradient of softmax cross-entropy with respect to the logits, for one example?
- with one-hot
Why should a classifier end in nn.Linear rather than nn.Softmax when trained with nn.CrossEntropyLoss?
- Softmax has no gradient
- The loss applies log-softmax itself; an extra softmax squashes the logits and slows training
nn.Softmaxdoes not exist- Softmax outputs must be integers
A photo can contain any combination of 20 object types. Which head fits?
- 20 logits with softmax and
CrossEntropyLoss - 20 logits with independent sigmoids and
BCEWithLogitsLoss - One logit with
BCEWithLogitsLoss - 20 outputs with
MSELoss
With nn.CrossEntropyLoss(weight=w) and the default reduction, how is the batch loss computed?
- The weights are ignored for the mean