v9.1.1
Menu

Top-K Accuracy Check

easyFREEImage ClassificationMetricsCV: Recognition

You are given a list of prediction scores for each class and need to determine if the true class is among the top-k highest-scoring predictions.

Top-k accuracy is a relaxed metric commonly used in image classification benchmarks like ImageNet, where top-5 accuracy is reported alongside top-1.

The algorithm:

  1. Rank all classes by their prediction scores (descending)
  2. Take the top k classes with highest scores
  3. Check if the true class is in this top-k set

This is more forgiving than top-1 accuracy, especially for fine-grained classification where similar classes may be confused.

Example

Input
scores = [0.1, 0.5, 0.3, 0.1]
true_class = 2
k = 2
Output
True
Reasoning
  • Inputs: scores holds one confidence per class, so class ii has score sis_i: s0=0.1s_0 = 0.1, s1=0.5s_1 = 0.5, s2=0.3s_2 = 0.3, s3=0.1s_3 = 0.1. true_class =2= 2 is the correct label, and k =2= 2 means the model gets credit if the label is among its 2 best guesses.
  • Ranking: ordering the scores from highest to lowest gives 0.5>0.3>0.1=0.10.5 > 0.3 > 0.1 = 0.1, so class 1 is rank 1, class 2 is rank 2, and classes 0 and 3 share the remaining places.
  • Top-2 set: the two highest-ranked classes are {1,2}\{1, 2\}.
  • Check: 2∈{1,2}2 \in \{1, 2\}, so the output is True. Under top-1 the set would be just {1}\{1\} and the answer would be False: the model's best guess is wrong, but its second guess is right.
  • Notice: classes 0 and 3 tie at 0.10.1, but both fall outside the top 2, so the tie cannot change the result here. Asking about true_class =0= 0 with the same scores gives False.

Constraints

  • scores is a list of prediction scores for each class (higher = more likely)
  • true_class is the index of the correct class
  • k is a positive integer (1 <= k <= len(scores))
  • Return True if true_class is in top-k predictions, False otherwise

Learn this in

More from CV: Recognition

solution.py

Test results

Sign in to run your code against the test cases.