Return Top K accuracy?

I modified this to work for PyTorch versions before 0.4, but the original version (which I’ve lost track of) actually worked for 0.4. At the very least, it should be a good starting point. You’ll just need to set learn.metrics = [accuracy_topk]

# Note - this is for pytorch versions before 0.4
# This is for accuracy in top 3 - you can change the first line to be whatever accuracy you want
def accuracy_topk(output, target, topk=(3,)):
    """Computes the precision@k for the specified values of k"""
    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))

    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
        res.append(correct_k.mul_(100.0 / batch_size))
    return res
8 Likes