PyTorch / Training state and architecture interfaces / Lesson 14
Weighted Classification Loss and Reduction
Inspect class-weighted cross-entropy and verify its reduction against a small controlled batch.
On this page
Lesson goals
- Describe why class weights affect training loss.
- Inspect per-example weighted losses.
- Verify the denominator used for a weighted mean.
State the training objective
Class weights change the contribution of examples to a classification loss. They can express a deliberate emphasis, but they do not create new examples or guarantee better performance on a minority class. Choose weights using the task and training data, then evaluate decision metrics and important slices on appropriately held-out data.
Document target encoding, class order, and whether the loss expects raw logits. The example uses integer class indices, two classes, and no ignored targets. Other target forms or ignored labels require checking the installed implementation’s documented reduction rules.
Inspect individual contributions
In a local lab with a compatible PyTorch installation, the example computes unreduced weighted cross-entropy for three synthetic examples. The class-one example uses weight two. The code requires PyTorch and is illustrative, so the public reader does not execute it. Examine the individual losses before reducing them.
import torch
import torch.nn.functional as F
logits = torch.tensor([[2.0, 0.5], [0.2, 1.2], [1.0, 0.1]])
targets = torch.tensor([0, 1, 0])
weights = torch.tensor([1.0, 2.0])
print(F.cross_entropy(logits, targets, weight=weights, reduction="none"))
The weight vector is indexed by each integer target, so the class-one contribution receives twice its unweighted loss.
Check the weighted mean
For this class-index fixture with no ignored targets, the weighted mean divides the sum of weighted losses by the sum of the weights of the observed targets. The second lab makes that denominator explicit. Do not assume that simply averaging the unreduced weighted values reproduces the documented weighted mean.
import torch
import torch.nn.functional as F
logits = torch.tensor([[2.0, 0.5], [0.2, 1.2], [1.0, 0.1]])
targets = torch.tensor([0, 1, 0])
weights = torch.tensor([1.0, 2.0])
losses = F.cross_entropy(logits, targets, weight=weights, reduction="none")
print(losses.sum() / weights[targets].sum())
The target weights are 1, 2, and 1, so their sum is 4 for this fixture.
Consider batches and ignored targets
Different batches can contain different class mixes, changing the sum of target weights. If examples are ignored, exclude them according to the loss contract and define behavior when no eligible targets remain. For accumulated microbatches, ensure scaling reproduces the intended combined objective rather than averaging incompatible batch means.
Evaluate the decision impact
Compare a weighted and unweighted baseline using the same splits and evaluation procedure. Review per-class error counts, calibration where relevant, and operational costs; select any decision threshold separately from the final test. Log the weights and reduction with the model so another reviewer can reconstruct the training objective.
Common errors and fixes
A manually averaged loss differs from the library result.
- Why it happens
- The denominator ignored the sum of observed class weights.
- How to fix it
- Reconstruct the documented reduction for the exact target form.
- Prevent it next time
- Test a tiny batch with unequal weights.
The intended minority class receives the wrong weight.
- Why it happens
- Weight order does not match target class indices.
- How to fix it
- Map class names to indices explicitly and inspect examples.
- Prevent it next time
- Version the label mapping and weight vector together.
A weighted model is assumed to solve deployment imbalance.
- Why it happens
- Training objective changes were treated as proof of operational performance.
- How to fix it
- Evaluate held-out class metrics and decision costs.
- Prevent it next time
- Define acceptance criteria before comparing models.
2 practice exercises
1. Targets are 0, 1, 0 and class weights are 1 and 2. What denominator is used in the illustrated weighted mean?
Show worked solution
The observed target weights are 1, 2, and 1, summing to 4. This answer applies to the stated class-index example without ignored targets.
2. Why is a lower weighted training loss not enough to approve a model?
Show worked solution
It measures the selected training objective, not the full operational outcome. Compare held-out error counts, relevant slices, decision costs, and uncertainty against a baseline.
Key takeaways
- Class weights modify loss contributions, not data coverage.
- Check the documented reduction for the exact target representation.
- Evaluate operational effects on held-out data.