Why a classifier learns from logits, not argmax
Softmax, cross entropy and a gradient you can calculate
Argmax loses the score differences needed for ordinary gradient training. Softmax and cross entropy preserve a useful signal.
A classifier for mutually exclusive cat, dog and bird labels returns three raw scores: logits. They may be negative and need not sum to one.
If the truth is cat, predicting dog by a narrow margin and predicting dog with overwhelming confidence are different errors. argmax discards that difference. Small score changes usually leave the winning index unchanged, so it supplies no useful gradient for ordinary gradient-based training.
Prerequisite: forward, loss and backward.
Softmax preserves a distribution over classes
For scores z:
Take z=[ln(2),ln(3),ln(5)]. The exponentials sum to ten:
| Label | Probability assigned by model | |---|---:| | Cat | 0.2 | | Dog | 0.3 | | Bird | 0.5 |
These are normalized model outputs, not evidence of real-world calibration.
Cross entropy keeps the correct label's score
With one true label, no class weighting and no label smoothing:
L = -ln(p_correct)
For cat, -ln(0.2) ≈ 1.609. Assigning it 0.8 gives about 0.223; assigning 0.01 gives about 4.605.
For this loss, the derivative with respect to a logit is pi-yi, where y is the one-hot target. The cat target [1,0,0] therefore gives [-0.8,0.3,0.5].
A direct gradient-descent step on the scores with rate 0.1 would change them by [+0.08,-0.03,-0.05]. In a real network the optimizer changes weights through the chain rule, not a stored score per image.
Give PyTorch raw logits
For index targets, CrossEntropyLoss combines LogSoftmax with NLLLoss. Do not add Softmax first:
Here logits have shape [N,3] and targets [N]. Passing probabilities to a function expecting logits computes a different function and may produce no type error.
Stable arithmetic is a separate requirement
Adding the same constant to all logits leaves mathematical Softmax unchanged. A naive exponential implementation can still overflow. Subtracting the largest score before exponentiation avoids producing enormous intermediate values; use a stable LogSoftmax-based loss rather than separate Softmax and log.
The output contract also matters: mutually exclusive labels differ from a multilabel image that may contain both cat and dog.
Check yourself
If bird is the true label, loss is -ln(0.5) ≈ 0.693 and the gradient is [0.2,0.3,-0.5]. Even a correct argmax prediction still has a gradient because the loss also responds to how much weight the correct class received.