v9.1.1
Menu

Top-K Accuracy Computation

hardPROImage ClassificationMetricsCV: Recognition

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
  • Inputs: logits is a 2×32 \times 3 grid of raw scores (rows = samples, columns = classes); labels gives each sample's true class index (y1=2y_1 = 2, y2=0y_2 = 0); k =2= 2 means a sample is a hit if its true class has one of its 2 highest scores.
  • Sample 1: scores (0.1,0.2,0.7)(0.1, 0.2, 0.7). Ranked by score: 22 (0.70.7), then 11 (0.20.2), so top2={2,1}\text{top}_2 = \{2, 1\}. The true class 22 is in the set, so the indicator is 11.
  • Sample 2: scores (0.8,0.1,0.1)(0.8, 0.1, 0.1). Class 00 leads with 0.80.8; the second slot goes to one of the tied classes 11 or 22. Either way top2\text{top}_2 contains 00, so the indicator is 11.
  • Average: 12(1+1)=1.0\frac{1}{2}(1 + 1) = 1.0, the output 1.0 (a fraction between 0 and 1).
  • Notice that only the ranking of scores matters, and a tie at the cut-off matters only if the true class is one of the tied ones. With k=3k = 3 (every class), any label would be a hit and the accuracy would always be 1.01.0.

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)

More from CV: Recognition

PRO

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

Sign in to run your code against the test cases.