TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Output Layers and Their Losses

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, kk values kk 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, CC classes, exactly one true CC logits softmax cross-entropy nn.CrossEntropyLoss int64 class index, shape (n,)
Multi-label, LL tags, any subset true LL logits LL 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 z∈RCz \in \mathbb{R}^C and true class yy, the loss is the negative log-probability of the true class. Written with log-sum-exp, the softmax never has to be formed:

log⁡softmax⁡(z)y=zy−LSE⁡(z),LSE⁡(z)=m+log⁡∑jezj−m, m=max⁡jzjℓ(z,y)=LSE⁡(z)−zy\begin{aligned} \log \operatorname{softmax}(z)_y &= z_y - \operatorname{LSE}(z), &&\operatorname{LSE}(z) = m + \log \sum_j e^{z_j - m},\ m = \max_j z_j \\ \ell(z, y) &= \operatorname{LSE}(z) - z_y \end{aligned}

Subtracting mm 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 ℓ\ell with respect to the logits is the famous

∂ℓ∂zj=pj−[j=y],p=softmax⁡(z)\frac{\partial \ell}{\partial z_j} = p_j - [j = y], \qquad p = \operatorname{softmax}(z)

and for a batch mean the whole matrix is (P−Y)/n(P - Y)/n, with YY the one-hot targets. It is bounded between −1-1 and 11, which is one reason why softmax with cross-entropy trains well. For the binary head with logit zz the same idea gives

ℓ(z,y)=max⁡(z,0)−zy+log⁡(1+e−∣z∣),∂ℓ∂z=σ(z)−y\ell(z, y) = \max(z, 0) - zy + \log\left(1 + e^{-\lvert z \rvert}\right), \qquad \frac{\partial \ell}{\partial z} = \sigma(z) - y

which is what BCEWithLogitsLoss computes. With pos_weight ww the positive term −ylog⁡σ(z)-y \log \sigma(z) is multiplied by ww, useful when positives are rare. MSE with a linear head, 1n∑(y^−y)2\frac{1}{n}\sum (\hat y - y)^2, has gradient 2n(y^−y)\frac{2}{n}(\hat y - y): 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 (P−Y)/n(P - Y)/n and a numerical check of all 12 entries:

python · try it yourself
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 ∞/∞\infty / \infty), while the stable one gives log-probabilities −2.4076,−1.4076,−0.4076-2.4076, -1.4076, -0.4076: only the differences between logits matter. The batch loss is 0.8661, below the 1.0986 (ln⁡3\ln 3) of a model that guesses uniformly. The first row of the gradient is −0.1931,0.034,0.1592-0.1931, 0.034, 0.1592: negative for the true class 0 (raise its logit), positive for the others. Each row sums to 0, since both pp and the one-hot vector sum to 1, and the analytic gradient agrees with the numerical one.

Binary and multi-label in NumPy

python · try it yourself
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: 1−σ(40)1 - \sigma(40) rounds to exactly 0 in float64, and log⁡0=−∞\log 0 = -\infty. The logit form gives the correct 40.0. Its gradient σ(z)−y\sigma(z) - y is −1.0-1.0, −0.5-0.5 and 1.01.0, never larger than 1 in magnitude.

The same three logits (2.0,1.5,1.0)(2.0, 1.5, 1.0) 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_smoothing ε\varepsilon replaces the one-hot target by (1−ε)(1 - \varepsilon) on the true class plus ε/C\varepsilon / C on every class, so the loss is (1−ε) ℓ(z,y)+ε⋅1C∑j(−log⁡pj)(1 - \varepsilon)\,\ell(z, y) + \varepsilon \cdot \frac{1}{C}\sum_j \left(-\log p_j\right). It stops the model from pushing logits to infinity and often improves calibration.
  • ignore_index (default −100-100) drops targets with that value from the loss and from the mean, used for padding tokens and unlabelled pixels.
  • weight gives each class a weight; with the default reduction='mean' the result is a weighted mean, ∑iwyiℓi/∑iwyi\sum_i w_{y_i} \ell_i / \sum_i w_{y_i}, 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:

python · try it yourself
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 ln⁡3=1.0986\ln 3 = 1.0986 per pixel.

Pitfalls

  • Softmax in the model and in the loss. CrossEntropyLoss applies log-softmax itself. A model ending in nn.Softmax trains, but its logits are squashed into [0,1][0, 1] and gradients shrink. End the model with nn.Linear; apply softmax only for reporting probabilities.
  • BCELoss on probabilities instead of BCEWithLogitsLoss on logits. The sigmoid-then-log path overflows to inf exactly 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 in BCEWithLogitsLoss raise an error, and with MSELoss the 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 weight changes 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

  1. 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.

  1. Show that the cross-entropy gradient for one example sums to zero across classes, and explain what that means for the logits.
Answer

∑j(pj−[j=y])=1−1=0\sum_j (p_j - [j = y]) = 1 - 1 = 0. 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.

  1. Compute by hand the label-smoothed loss for C=3C = 3, ε=0.3\varepsilon = 0.3, when the model gives the true class probability 0.8 and the others 0.1 each.
Answer

ℓ=−log⁡0.8=0.2231\ell = -\log 0.8 = 0.2231; the average of −log⁡pj-\log p_j over the three classes is (0.2231+2.3026+2.3026)/3=1.6094(0.2231 + 2.3026 + 2.3026)/3 = 1.6094. The smoothed loss is 0.7⋅0.2231+0.3⋅1.6094=0.63900.7 \cdot 0.2231 + 0.3 \cdot 1.6094 = 0.6390. Note that it is larger than the plain loss: smoothing penalises over-confidence.

  1. Why does ignore_index matter 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 −100-100 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?

  1. Float one-hot of shape (64,)
  2. Int64 class indices of shape (64,)
  3. Int64 of shape (64, 1)
  4. Float probabilities of shape (10,)

What is the gradient of softmax cross-entropy with respect to the logits, for one example?

  1. p−yp - y with yy one-hot
  2. log⁡p−y\log p - y
  3. p(1−p)p (1 - p)
  4. −1/py-1 / p_y

Why should a classifier end in nn.Linear rather than nn.Softmax when trained with nn.CrossEntropyLoss?

  1. Softmax has no gradient
  2. The loss applies log-softmax itself; an extra softmax squashes the logits and slows training
  3. nn.Softmax does not exist
  4. Softmax outputs must be integers

A photo can contain any combination of 20 object types. Which head fits?

  1. 20 logits with softmax and CrossEntropyLoss
  2. 20 logits with independent sigmoids and BCEWithLogitsLoss
  3. One logit with BCEWithLogitsLoss
  4. 20 outputs with MSELoss

With nn.CrossEntropyLoss(weight=w) and the default reduction, how is the batch loss computed?

  1. 1n∑iwyiℓi\frac{1}{n} \sum_i w_{y_i} \ell_i
  2. ∑iwyiℓi/∑iwyi\sum_i w_{y_i} \ell_i / \sum_i w_{y_i}
  3. ∑iℓi/∑iwyi\sum_i \ell_i / \sum_i w_{y_i}
  4. The weights are ignored for the mean