Lesson 6.4 · 8 min read · about 55 min to master at a very slow pace
Binary, Multi-class and Logits in PyTorch
Which output layer and loss go with which task, binary cross-entropy worked out, why accuracy can't be the training loss, the best accuracy any classifier can reach, and the logits rule that trips people up in PyTorch.
Output layer and loss by task
| Task | Output layer | Loss | PyTorch |
|---|---|---|---|
| Regression | Linear | MSE | nn.MSELoss |
| Binary classification | One sigmoid unit | Binary cross-entropy | nn.BCEWithLogitsLoss |
| Multi-class | Softmax over classes | Categorical cross-entropy | nn.CrossEntropyLoss |
Binary cross-entropy
For it's ; for , . With : costs and costs . A threshold (0.5 by default) turns into a class.
The logits rule in PyTorch
Return logits, not probabilities
nn.CrossEntropyLoss and nn.BCEWithLogitsLoss take raw logits and apply log-softmax or sigmoid internally, in a numerically stable way. If your model also applies a softmax at the end, the loss applies it a second time: training still runs but the gradients are wrong and learning is poor. Leave the final layer linear; apply softmax only when you want probabilities for reporting.
Why not train on accuracy?
Accuracy only changes when a prediction crosses the threshold, so as a function of the weights it's flat almost everywhere: its gradient is zero. Train on cross-entropy, which changes smoothly, and report accuracy.
The best any classifier can do
Worked example: overlapping classes
Class A is uniform on the square ; class B uniform on ; equal priors. Inside the small square the densities are (A) and (B), so . Outside it, only B is possible.
- A point lands in the small square with probability . The best guess there is A, right 80% of the time.
- Outside (probability 0.375) the best guess is B, right every time.
- Best possible accuracy: .
- Lowest possible cross-entropy: nats.
No network, however large, can beat this Bayes-optimal limit, because the classes genuinely overlap.
Stuck? Common doubts
Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.
First passDo I need a sigmoid layer before BCEWithLogitsLoss?
No, and you shouldn't add one. As the name says, it expects logits and applies the sigmoid itself. If you want probabilities at prediction time, apply torch.sigmoid to the logits then.
Going deeperWhy can't my model reach 100% accuracy on overlapping classes?
If the same input can belong to either class, any rule that picks one class for that input must be wrong some of the time. The Bayes-optimal classifier picks the more probable class everywhere, and its accuracy (0.875 in the example) is a ceiling for every model on that data distribution.
Cheatsheet
Task → output → loss
Logits rule
Accuracy as a loss
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.