Week 03 · Losses and output layers

Match output shape and loss to the meaning of the target.

← Week 2 · Subject contents · Week 4 →

Match output shape and loss to the meaning of the target.

Work through the problem

A regression head can return any real number, and squared loss compares it with a numeric target. For a binary classification logit z and label y∈{0,1}, binary cross-entropy is log(1+eᶻ)−yz. Use a fused loss to avoid taking logs of rounded probabilities.

For mutually exclusive classes, cross-entropy is log Σⱼeᶻʲ−zₖ for the true class k. With logits [2,0] and true class 0, the loss simplifies to log(1+e⁻²) ≈ 0.127. This matches binary cross-entropy with one logit of 2 and label 1 because softmax over [2,0] and sigmoid(2) assign the same probability to the first class.

Run the Python lab

import torch
from torch.nn import functional as F
z = torch.tensor([2.])
binary = F.binary_cross_entropy_with_logits(z,torch.tensor([1.]))
multi = F.cross_entropy(torch.tensor([[2.,0.]]),torch.tensor([0]))
squared = (torch.sigmoid(z)-1).square()
print("Binary, categorical, squared probability loss:",*[round(t.item(),4) for t in [binary,multi,squared]])
assert torch.allclose(binary,multi)

Output from the lab

Binary, categorical, squared probability loss: 0.1269 0.1269 0.0142

Practice

  1. Why use separate sigmoid heads for tags that can coexist?

Check your reasoning

  1. Each tag needs its own Bernoulli probability. A shared softmax forces their probabilities to compete for a total of one.

← Week 2 · Subject contents · Week 4 →

Further reading · Goodfellow, Bengio, and Courville · Deep Learning