[Metrics] Top K Accuracy
🚀 Feature
We currently have accuracy implementation which is top-1 Accuracy to be formal.
Can we provide a generic top-k Accuracy Implementation?
Motivation
Quite often in classification tasks, we need top-3 Accuracy and top-5 Accuracy and so on. It depends on the tasks. These stats are often reported in standard papers for classification tasks be it NLP or Computer Vision.
Pitch
I just checked the implementation of accuracy we have currently, can we add an additional parameter topk = 1.
Here is an implementation of top-k accuracy which I use often. This code is used in imagenet classification tasks, I have no idea if it will work for other cases.
def accuracy(output, target, topk=(1,)):
    """
Computes the accuracy over the k top predictions for the specified values of k
output and targets are just tensors.
"""
    maxk = max(topk)
    batch_size = target.size(0)
    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred))
    return [correct[:k].view(-1).float().sum(0) * 100.0 / batch_size for k in topk]

Alternatives
No currently found, will dig into this if needed. Probably above implementation is not according to API lightning has.