Model Pipeline - Top-K accuracy
This pipeline shows how a computer vision model learns to recognize images and how Top-K accuracy measures if the correct label is among the model's top K guesses.
Jump into concepts and practice - no test required
This pipeline shows how a computer vision model learns to recognize images and how Top-K accuracy measures if the correct label is among the model's top K guesses.
Loss
2.0 |****
1.5 |***
1.0 |**
0.5 |*
0.0 +----
1 2 3 4 5 Epochs| Epoch | Loss ↓ | Accuracy ↑ | Observation |
|---|---|---|---|
| 1 | 1.8 | 0.35 | Model starts learning, accuracy low |
| 2 | 1.2 | 0.55 | Loss decreases, accuracy improves |
| 3 | 0.9 | 0.68 | Model getting better at classification |
| 4 | 0.7 | 0.75 | Accuracy approaching good performance |
| 5 | 0.6 | 0.80 | Model converging with good accuracy |
Top-K accuracy measure in a classification model?topk method on model outputs outputs and true labels labels?topk(k, dim=1) returns top k values and indices along dimension 1 (classes). We want indices for predictions.eq and sum.import torch
outputs = torch.tensor([[0.1, 0.8, 0.05, 0.05],
[0.4, 0.3, 0.2, 0.1],
[0.25, 0.25, 0.25, 0.25]])
labels = torch.tensor([1, 2, 3])
_, pred = outputs.topk(2, dim=1)
correct = pred.eq(labels.view(-1,1)).sum().item()
print(correct)_, pred = outputs.topk(5) correct = pred.eq(labels).sum().item()
topk(5) without dim defaults to dim=0, which is incorrect for class predictions along dim=1.pred.eq(labels) never matches, resulting in zero correct.topk(5, dim=1) to get top 5 class indices per sample. Labels must be reshaped to compare with these indices.