Skip to content

Instantly share code, notes, and snippets.

@ashok-arjun
Forked from weiaicunzai/accuracy.py
Created December 28, 2021 08:01
Show Gist options
  • Save ashok-arjun/650bcd142884e95e2f632bff47e96a99 to your computer and use it in GitHub Desktop.
Save ashok-arjun/650bcd142884e95e2f632bff47e96a99 to your computer and use it in GitHub Desktop.
compute top1, top5 error using pytorch
from __future__ import print_function, absolute_import
__all__ = ['accuracy']
def accuracy(output, target, topk=(1,)):
"""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)
res.append(correct_k.mul_(100.0 / batch_size))
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment