Feed logits to the correct classification loss
A classifier can produce sensible-looking probabilities while training against the wrong objective. Start by deciding whether each example has exactly one class or several independent labels. That decision determines both the output shape and the loss. A logit is a raw score before a probability transformation, so negative values and values above one are normal.
Establish the label contract
This example uses Python 3.14 and PyTorch 2.15. Install a PyTorch build suitable for your machine, using its official installation selector. CPU execution is sufficient for every calculation here.
For one class out of three, use three logits per example and one integer class index. The labels in a two-example batch might be [0, 2], meaning that the first example belongs to class zero and the second to class two. Class indices must be in the range from zero through the number of classes minus one.
CrossEntropyLoss accepts these raw scores and combines the required normalization with the loss calculation. Do not add a softmax layer immediately before it. Its class-index form expects integer targets with torch.long dtype.
CrossEntropyLoss reference
.
Calculate a multiclass loss
Save the following as classification.py and run python classification.py.
import torch
from torch import nn
logits = torch.tensor(
[[3.0, 1.0, -2.0], [-1.0, 0.0, 2.0]],
requires_grad=True,
)
targets = torch.tensor([0, 2], dtype=torch.long)
loss = nn.CrossEntropyLoss()(logits, targets)
loss.backward()
probabilities = logits.detach().softmax(dim=1)
predictions = logits.detach().argmax(dim=1)
print(f"Loss: {loss.item():.4f}")
print("Predictions:", predictions.tolist())
print("Probability sums:", probabilities.sum(dim=1).tolist())
assert torch.isfinite(logits.grad).all()
assert predictions.tolist() == [0, 2]
The loss is approximately 0.1513, the predictions are [0, 2], and each probability row sums to approximately one. The gradient assertion confirms that the example supports backpropagation. These are checks of the calculation, not evidence that an untrained model generalizes to new data.
Softmax is useful when displaying a distribution over mutually exclusive classes. The class with the highest score remains the same after softmax, so argmax can work directly on logits when only the winning class is needed. Choose the class dimension deliberately. For this two-dimensional batch it is dimension one.
Softmax reference
.
Use an independent loss for multiple labels
Suppose a document can be both technical and urgent. Those labels do not compete for one shared probability total. Give each label its own logit and use floating-point targets with the same shape.
label_logits = torch.tensor([[2.0, -1.0]], requires_grad=True)
label_targets = torch.tensor([[1.0, 0.0]])
label_loss = nn.BCEWithLogitsLoss()(label_logits, label_targets)
label_loss.backward()
print("Label probabilities:", label_logits.detach().sigmoid().tolist())
assert torch.isfinite(label_logits.grad).all()
The probabilities are approximately [0.881, 0.269]. They do not need to sum to one. A binary classifier with one output per example uses the same idea, provided the prediction and target shapes match. The combined loss avoids the numerical weaknesses of calculating sigmoid and logarithms separately.
BCEWithLogitsLoss reference
.
Check mistakes at the boundary
Print the output shape, target shape and dtypes before investigating the optimizer. A batch dimension accidentally removed by squeeze() can break a batch of one. A floating-point class-index vector can select an unintended target interpretation or fail validation. Soft-label cross-entropy is a separate supported contract and should be chosen explicitly.
A prediction threshold such as 0.5 belongs to the decision policy. Tune it against the cost of false positives and false negatives on validation data. It does not change which training loss accepts logits. Both examples above were executed on CPU with PyTorch 2.15. No GPU execution is required.
Question provenance
This article addresses What are logits? What is the difference between softmax and softmax_cross_entropy_with_logits? , asked by Shubhashis on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.
Author: Herman Schoenfeld