BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Evaluation metrics29 of 33 in topic

810. Measure top-1 and top-5 accuracy from logits

EasyEvaluation metrics

Why it matters Top-k accuracy is the headline metric for image classifiers and for next-token prediction checks.

ImageNet results report top-1 and top-5 accuracy: a prediction counts as correct if the true class is among the k highest-scoring classes.

Write top_k_accuracy(logits, labels, k) for logits of shape (n, C) and a length-n list of labels. Return the share of rows whose true label is among the k largest logits. When scores tie at the cut-off, a class with a lower index ranks higher (use a stable sort on -logits).

Functiondef top_k_accuracy(logits, labels, k)

Example 1

Input: top_k_accuracy([[0.1, 0.7, 0.2], [0.5, 0.3, 0.2]], [2, 0], 1)

Output: 0.5

Example 2

Input: logits = [[0.1, 0.7, 0.2], [0.5, 0.3, 0.2]], labels = [2, 0], k = 2

Output: 1.0

Example 3

Input: logits = [[1.0, 1.0, 1.0]], labels = [2], k = 2

Output: 0.0

Constraints

  • logits has shape (n, C)
  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
Hint 1

np.argsort(-logits, axis=1) gives classes from best to worst.

Hint 2

Compare the first k columns with the labels as a column vector and use any(axis=1).

Common mistakes
  • Sorting ascending and taking the first k, which picks the worst classes.
  • Using an unstable sort, which makes ties depend on the platform.
Understand the idea

Sort each row's scores from high to low, keep the first k class ids, and check whether the label is one of them.

Worked example

row 1 has top class 1 but label 2, a miss at k = 1 and a hit at k = 2. Row 2 has top class 0, label 0, a hit. So top-1 = 0.5 and top-2 = 1.0.

correct if label in argsort(-z)[:k]
Topics
Evaluation metrics
Similar questions
  • Compute precision, recall and F1 from predictionsEasy
  • Measure how overconfident a classifier is with expected calibration errorEasy
  • Build a confusion matrixEasy
  • Compute mean reciprocal rankEasy
All Evaluation metrics problems
Report
810 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def top_k_accuracy(logits, labels, k):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS