Top-K Accuracy
Description
Given a 2D array of class scores (one row of scores per sample), an array of true class indices, and an integer k, return the top-k accuracy: the fraction of samples whose true class is among the k highest-scoring classes. Break score ties toward the lower index. Round the result to 4 decimal places.
Examples
[[1,3,2],[5,1,0]], [1,0], 21A sample counts as correct when its true class appears anywhere among the k highest-scoring predictions, and the correct fraction is reported.
[[1,2,3],[3,2,1]], [0,0], 10.5A sample counts as correct when its true class appears anywhere among the k highest-scoring predictions, and the correct fraction is reported.
[[5,1],[1,5]], [0,1], 11A sample counts as correct when its true class appears anywhere among the k highest-scoring predictions, and the correct fraction is reported.
Constraints
- •
1 ≤ samples ≤ 10³ - •
1 ≤ k ≤ number of classes
Ready to solve this problem?
Practice solo and sharpen your skills for technical interviews.