Pytorch Image label
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In PyTorch image classification, model output is usually a numeric class index, not a human readable label. The missing piece is a stable mapping between class ids and label names during both training and inference. If that mapping is not saved and reused, predictions can look correct numerically but wrong semantically.
Build a Stable Label Mapping During Training
When using torchvision.datasets.ImageFolder, class names are derived from folder names and sorted alphabetically. This creates a deterministic class_to_idx dictionary that should be saved with the model checkpoint.
Saving both model weights and label mapping ensures inference code can decode predictions consistently.
Decode Predicted Label at Inference Time
At inference, invert class_to_idx so predicted index maps back to label text. Then report probabilities for debugging and threshold tuning.
If labels look swapped, the first thing to verify is that inference used the same mapping generated during training.
Multi Label Versus Single Label Clarification
CrossEntropyLoss with one class index per image solves single label classification. For multi label tasks, each image can have several labels and needs a different output and loss setup.
Use this rule:
- Single label: final layer size equals class count, target is one index, loss is
CrossEntropyLoss - Multi label: final layer size equals label count, target is multi hot vector, loss is
BCEWithLogitsLoss
Choosing the wrong formulation leads to confusing label outputs even when training appears stable.
Persist Metadata for Deployment
Model files alone are not enough for production. Store preprocessing settings, image size, normalization values, and label map version in one metadata object.
This prevents silent drift between training and serving environments.
Common Pitfalls
A common mistake is rebuilding labels manually in inference code. Even one ordering difference can map class index zero to the wrong class name.
Another issue is applying different preprocessing between training and prediction. If resize and normalization differ, confidence and label quality can degrade sharply.
A third issue is treating a multi label dataset as single label and forcing one class output. The model then predicts the most dominant class and misses secondary labels.
Finally, avoid overwriting checkpoints without versioned metadata. Label map drift is hard to debug once historical artifacts are lost.
Summary
- Save
class_to_idxduring training and reuse it for every inference path - Invert mapping at prediction time to decode class index into readable label
- Match loss function and output layer to single label or multi label task type
- Keep preprocessing identical between training and inference
- Version model metadata so label mappings stay reproducible in production
Related reading
- PyTorch is there a definitive training loop similar to Keras' fit?
- PyTorch model input shape
- pytorch Network.parameters missing 1 required positional argument 'self
- PyTorch predict single example
- PyTorch is there a definitive training loop similar to Keras' fit?
- PyTorch Learning rate scheduler
- R Count objects in a picture
- Read mnist images into Tensorflow
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.