Skip to content

MLDay 33 of 50Deep Learning

Losses, Logits and Softmax

7 min read

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 zz eze^{z} 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 −ln⁡0.67≈0.41-\ln 0.67 \approx 0.41. If it's a coat, the loss is −ln⁡0.09≈2.41-\ln 0.09 \approx 2.41, because the model gave the right answer little chance.

The formula

Softmax turns KK logits into KK probabilities:

pk=ezk∑j=1Kezjp_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}
Symbol Meaning
zkz_k the logit for class kk
KK the number of classes
ee Euler's number, about 2.718
pkp_k the predicted probability of class kk

Worked: logits (2, 1, 0) give p1=7.397.39+2.72+1≈0.67p_1 = \frac{7.39}{7.39 + 2.72 + 1} \approx 0.67.

Cross-entropy scores one prediction against the true class:

L=−ln⁡pyL = -\ln p_y
Symbol Meaning
yy the true class
pyp_y the probability the model gave it
LL the loss: 0 when py=1p_y = 1, growing without limit as pyp_y falls to 0

Worked: the true class is the T-shirt, so L=−ln⁡0.67≈0.41L = -\ln 0.67 \approx 0.41. 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 p=e/(e+9)≈0.23p = e / (e + 9) \approx 0.23, and the loss can never fall below −ln⁡0.23≈1.461-\ln 0.23 \approx 1.461. 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.

Next · Day 34 · 9 minOptimizers and Learning-Rate Schedules← Previous: Day 32 · The Training Loop
Not tapped yet