810. Measure top-1 and top-5 accuracy from logits
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).
def 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
logitshas 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.
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]