PIXELBANKv9.1.0
Menu

Top-K Accuracy Check

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:
  1. Sort classes by score (descending):
    • Class 1: 0.5 (rank 1)
    • Class 2: 0.3 (rank 2)
    • Class 0: 0.1 (rank 3)
    • Class 3: 0.1 (rank 4)
  2. Top-2 classes are: [1, 2]
  3. true_class = 2 is in the top-2 set
  4. Return True

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
solution.py

Test Results

0/0
Run code to see test results.
Top-K Accuracy Check - Easy | PixelBank