classification.py 521 B

12345678910111213141516171819
  1. from __future__ import absolute_import
  2. from ..utils import to_torch
  3. def accuracy(output, target, topk=(1,)):
  4. output, target = to_torch(output), to_torch(target)
  5. maxk = max(topk)
  6. batch_size = target.size(0)
  7. _, pred = output.topk(maxk, 1, True, True)
  8. pred = pred.t()
  9. correct = pred.eq(target.view(1, -1).expand_as(pred))
  10. ret = []
  11. for k in topk:
  12. correct_k = correct[:k].view(-1).float().sum(dim=0, keepdim=True)
  13. ret.append(correct_k.mul_(1. / batch_size))
  14. return ret