MLDay 33 of 50Deep Learning
Losses, Logits and Softmax
A clothing classifier trains without a single error message, yet it scores nearly 7 points less accuracy than it should. The cause is one extra layer at the end. Picking the output layer and the loss is a small choice that can quietly ruin a network.
The idea
A network's last layer outputs logits: raw scores, one per output, that can be any number, like −3.2 or +7. The loss turns logits into a penalty. Match both to the task:
| Task | Output layer | Loss in PyTorch | What the loss does with the logits |
|---|---|---|---|
| Predict a number (rentals) | 1 output | nn.MSELoss |
compares it with the target directly |
| Yes or no (fraud) | 1 logit | nn.BCEWithLogitsLoss |
sigmoid, then log loss, as in D12 |
| One of many classes (10 kinds of clothing) | 1 logit per class | nn.CrossEntropyLoss |
softmax, then −ln of the right class's probability |
The two classification losses apply the squash themselves, in one numerically safe step. So feed the loss
raw logits and leave the model's last layer plain. Apply torch.softmax only when you want to read
probabilities.
Softmax turns a list of logits into probabilities: all positive and adding up to 1. A bigger logit gets a bigger share. Cross-entropy is the loss: the negative log of the probability given to the right class.
A tiny example
A model scores one image as T-shirt, shirt or coat, with logits 2, 1 and 0.
| Class | Logit | Probability | |
|---|---|---|---|
| T-shirt | 2 | 7.39 | 7.39 / 11.11 = 0.67 |
| Shirt | 1 | 2.72 | 2.72 / 11.11 = 0.24 |
| Coat | 0 | 1.00 | 1.00 / 11.11 = 0.09 |
If the image really is a T-shirt, the loss is . If it's a coat, the loss is , because the model gave the right answer little chance.
The formula
Softmax turns logits into probabilities:
| Symbol | Meaning |
|---|---|
| the logit for class | |
| the number of classes | |
| Euler's number, about 2.718 | |
| the predicted probability of class |
Worked: logits (2, 1, 0) give .
Cross-entropy scores one prediction against the true class:
| Symbol | Meaning |
|---|---|
| the true class | |
| the probability the model gave it | |
| the loss: 0 when , growing without limit as falls to 0 |
Worked: the true class is the T-shirt, so . With two classes this is exactly D12's log loss.
Try it
Make the model sure it's a shirt
Move the logits. Softmax turns them into probabilities: each is e to the logit, divided by the sum of them all, so the bars always add up to 1. The right answer is "Shirt".
most likely T-shirt, p = 0.609cross-entropy −ln p(Shirt) = 1.995
The model starts out calling the shirt a T-shirt (p = 0.609), and the cross-entropy is 1.995. Raise the Shirt logit to 3.5: its bar grows to 0.760 and the loss falls to 0.275. Then move every logit up by 1 and notice that no bar changes: only the gaps between logits matter.
In code
The baseline for Days 34–37: a small MLP on the Fashion-MNIST slice, trained with the loop from
D32. Its last layer is a plain Linear(128, 10): 10 logits.
# script_id: day_033_losses_logits_softmax/baseline
import os
from pathlib import Path
import numpy as np
import torch
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
CLASSES = ["T-shirt", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
d = np.load(DATA_DIR / "fashion_mnist" / "fashion_mnist_slice.npz")
X, y = d["X_train"].astype("float32") / 255, d["y_train"].astype("int64")
X_tr, X_va, y_tr, y_va = train_test_split(X, y, test_size=1000, stratify=y, random_state=42)
X_va, y_va = torch.from_numpy(X_va), torch.from_numpy(y_va)
loss_fn = nn.CrossEntropyLoss() # softmax + (-ln p) inside
def train(*extra_layers):
torch.manual_seed(42)
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10), *extra_layers)
loader = DataLoader(TensorDataset(torch.from_numpy(X_tr), torch.from_numpy(y_tr)),
batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42))
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(10):
model.train()
for xb, yb in loader:
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
model.eval()
with torch.no_grad():
return model(X_va) # one output row per validation image
logits = train()
pred = logits.argmax(dim=1)
print(f"val loss {loss_fn(logits, y_va):.3f}, accuracy {(pred == y_va).float().mean():.3f}")
print(f"F1: macro {f1_score(y_va, pred, average='macro'):.3f}, micro {f1_score(y_va, pred, average='micro'):.3f}")
per_class = f1_score(y_va, pred, average=None)
print(f"weakest class: {CLASSES[per_class.argmin()]}, F1 {per_class.min():.2f}")
print("probabilities of image 0 add up to", round(torch.softmax(logits, dim=1)[0].sum().item(), 3))
val loss 0.427, accuracy 0.840
F1: macro 0.839, micro 0.840
weakest class: Shirt, F1 0.67
probabilities of image 0 add up to 1.0
With 10 classes, F1 (D13) needs an average. Micro pools every image; with one label per image it always equals accuracy. Macro averages the 10 per-class scores, so each class counts the same. The validation set has 100 images per class, so the two land close together (0.839 vs. 0.840). On skewed classes, macro exposes a rare class that the model gets wrong. Shirts are the hardest: they look like T-shirts, pullovers and coats.
Now the bug: the same model with nn.Softmax added as its last layer.
# script_id: day_033_losses_logits_softmax/baseline
probs = train(nn.Softmax(dim=1)) # BUG: the loss applies softmax again
print(f"softmax twice: val loss {loss_fn(probs, y_va):.3f}, accuracy {(probs.argmax(dim=1) == y_va).float().mean():.3f}")
perfect = torch.tensor([[1.0] + [0.0] * 9]) # p = 1 for the right class
print(f"lowest loss it can ever reach: {loss_fn(perfect, torch.tensor([0])):.3f}")
softmax twice: val loss 1.692, accuracy 0.774
lowest loss it can ever reach: 1.461
It still trains, but accuracy drops from 0.840 to 0.774. The loss treats probabilities between 0 and 1 as logits, so even a perfect answer only gets , and the loss can never fall below . Its gradients stay weak.
Quick check
Quick check
1. A network has to say whether an email is spam. What should its last layer and loss be?
2. Logits (2, 1, 0) become (3, 2, 1). What happens to the probabilities?
3. The true class gets p = 0.05. What is the cross-entropy?
Next
The baseline used Adam without asking why; D34: Optimizers and Learning-Rate Schedules trains this same model with SGD, momentum and AdamW and compares their loss curves.
Data: Fashion-MNIST (Zalando Research), MIT licence; cite Xiao, H., Rasul, K. and Vollgraf, R. (2017), "Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms", arXiv:1708.07747.