Top-K Accuracy Computation
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:
For ImageNet, top-5 accuracy is standard (correct class in top 5 predictions).
Implementation:
- For each sample, get indices of k largest logits (argsort descending)
- Check if true label is in these k indices
- Average across all samples
Example
logits = [[0.1, 0.2, 0.7], [0.8, 0.1, 0.1]] # 2 samples, 3 classes labels = [2, 0] # True classes k = 2
1.0
- Inputs:
logitsis a grid of raw scores (rows = samples, columns = classes);labelsgives each sample's true class index (, );kmeans a sample is a hit if its true class has one of its 2 highest scores. - Sample 1: scores . Ranked by score: (), then (), so . The true class is in the set, so the indicator is .
- Sample 2: scores . Class leads with ; the second slot goes to one of the tied classes or . Either way contains , so the indicator is .
- Average: , 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 (every class), any label would be a hit and the accuracy would always be .
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)