PIXELBANKv9.1.0
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=1N∑i=1N1[yi∈topk(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 locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Top-K Accuracy Computation - Hard | PixelBank