Loading...
Implement top-k accuracy metric used for evaluating classification models.
Top-k accuracy checks if the correct class is among the k highest-probability predictions:
Top-k Acc=N1∑i=1N1[yi∈topk(y^i)]
For ImageNet, top-5 accuracy is standard (correct class in top 5 predictions).
Implementation:
logits = [[0.1, 0.2, 0.7], [0.8, 0.1, 0.1]] # 2 samples, 3 classes labels = [2, 0] # True classes k = 2
1.0
Sample 1: Top-2 predictions are classes [2, 1], true label 2 ✓ Sample 2: Top-2 predictions are classes [0, 1], true label 0 ✓
Both correct → 2/2 = 1.0 accuracy