PIXELBANKv8.2.1
Menu

Top-K Accuracy Computation

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=1Ni=1N1[yitopk(y^i)]\text{Top-k Acc} = \frac{1}{N} \sum_{i=1}^{N} \mathbf{1}[y_i \in \text{top}_k(\hat{y}_i)]

For ImageNet, top-5 accuracy is standard (correct class in top 5 predictions).

Implementation:

  1. For each sample, get indices of k largest logits (argsort descending)
  2. Check if true label is in these k indices
  3. Average across all samples

Example:

Input:
logits = [[0.1, 0.2, 0.7], [0.8, 0.1, 0.1]]  # 2 samples, 3 classes
labels = [2, 0]  # True classes
k = 2
Output:
1.0
Reasoning:

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

Constraints:

  • logits: Tensor (batch_size, num_classes) - raw model outputs
  • labels: Tensor (batch_size,) - ground truth class indices
  • k: Number of top predictions to consider
  • Return: Top-k accuracy as float (0-1)
Editor

Test Results

0/0
Run code to see test results.