PyTorch CrossEntropyLoss Target Shape: Class Indices vs Soft Labels
Fix PyTorch CrossEntropyLoss target shape and dtype errors. Compare integer class indices, one-hot labels and soft labels in a worked PTCA example.
For PyTorch CrossEntropyLoss with logits shaped [N, C], pass class IDs as a torch.long target shaped [N], or pass class probabilities as a floating-point target shaped [N, C]. A one-hot integer matrix has the right shape for probability targets but the wrong dtype. Leave the model output as logits in both cases.
Match the shape and dtype to the label format
For batch classification, N is the number of examples and C is the number of classes. An index target such as [0, 1] supplies one class ID per row. A probability target supplies a distribution across all C classes for each row. Float targets shaped [N] do not form per-class distributions, and an integer target shaped [N, C] does not follow either contract.
If the labels carry confidence or a mix of classes, keep those probabilities. Taking argmax changes the learning objective by discarding probability assigned to other classes. If the labels are already hard class IDs, keep the vector of IDs.
| Target for two examples and two classes | Shape | Dtype |
|---|---|---|
| Class IDs [0, 1] | [2] | torch.long |
| One-hot rows [[1, 0], [0, 1]] | [2, 2] | Floating point |
| Soft rows [[0.8, 0.2], [0.1, 0.9]] | [2, 2] | Floating point |
Source: PyTorch CrossEntropyLoss reference: target shapes and probability validation ↗
Compute the effect of changing only the target
Take one example with logits [ln(3), 0]. Internally the loss assigns probabilities [0.75, 0.25]. If the hard target is class 0, the unweighted loss is −ln(0.75), or about 0.28768. The same logits with a floating one-hot target [1.0, 0.0] give the same loss in this example.
Switch the target to [0.8, 0.2]. The new loss is −0.8 × ln(0.75) − 0.2 × ln(0.25), or about 0.50740. The target itself changes the objective even though the predicted class stays the same. The expected values above assume no class weighting or label smoothing.
import math
import torch
from torch.nn.functional import cross_entropy
logits = torch.tensor([[math.log(3), 0.0]])
class_id = torch.tensor([0], dtype=torch.long)
one_hot = torch.tensor([[1.0, 0.0]])
soft = torch.tensor([[0.8, 0.2]])
for target in (class_id, one_hot, soft):
print(f'{cross_entropy(logits, target).item():.5f}')
# 0.28768
# 0.28768
# 0.50740Source: PyTorch CrossEntropyLoss reference: target shapes and probability validation ↗
Check soft labels before calling the loss
For probability targets, check that each row has one entry per class, each value is finite and between 0 and 1, and each row sums to 1 within your numerical tolerance. PyTorch does not strictly validate this distribution contract. A target row like [1.0, 1.0] can go through the loss while giving both classes full weight.
If you see a dtype error after converting class IDs to one-hot, inspect target.shape and target.dtype together. Convert valid one-hot rows to floating point when using probability mode, or keep the original integer class IDs. Casting an arbitrary integer matrix to float does not validate its values.
Source: PyTorch CrossEntropyLoss reference: target shapes and probability validation ↗
PTCA practice question: preserve the soft target
Your model returns logits [ln(3), 0] and the target stores [0.8, 0.2]. Which training line keeps both target probabilities? A. Pass logits and the floating target to cross-entropy. B. Pass logits and the target argmax. C. Apply softmax to logits before cross-entropy. D. Cast the target matrix to long.
Choose A. B drops the 20% probability assigned to class 1. C changes the scores fed to the loss, which already applies log-softmax in its calculation. D violates the required dtype for probability targets. Try the linked PTCA sample for a separate question on selecting the correct multiclass loss line.
Source: PyTorch CrossEntropyLoss reference: target shapes and probability validation ↗
Your next steps
- Check target shape and dtype together.
- Keep soft-label probabilities when they define the training objective.
- Pass raw logits to CrossEntropyLoss.
Sources & official resources
Linked resources checked on 2026-12-01. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →