In multi-class classification, the standard accuracy metric only counts a prediction as correct when the highest-scoring class matches the true label. Top-K accuracy generalizes this: a prediction is considered correct if the true label appears among the K classes with the highest predicted scores. This metric is widely used to evaluate classifiers on tasks where the number of classes is large (e.g., ImageNet uses Top-5 accuracy).
Write a function top_k_accuracy(y_scores, y_true, k) that computes the Top-K accuracy.
y_scores: A numpy array of shape (n_samples, n_classes) containing predicted scores (or probabilities) for each class.y_true: A numpy array of shape (n_samples,) containing integer class indices for the true labels.k: A positive integer specifying the number of top predictions to consider.When scores are tied, break ties by lower class index first (i.e., a stable sort of scores in descending order).