Computes the accuracy over the k top predictions for the specified values of k
(output, target, topk=(1,))
| 510 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' |
| 511 | |
| 512 | def accuracy(output, target, topk=(1,)): |
| 513 | """Computes the accuracy over the k top predictions for the specified values of k""" |
| 514 | with torch.no_grad(): |
| 515 | maxk = max(topk) |
| 516 | batch_size = target.size(0) |
| 517 | |
| 518 | _, pred = output.topk(maxk, 1, True, True) |
| 519 | pred = pred.t() |
| 520 | correct = pred.eq(target.view(1, -1).expand_as(pred)) |
| 521 | |
| 522 | res = [] |
| 523 | for k in topk: |
| 524 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) |
| 525 | res.append(correct_k.mul_(100.0 / batch_size)) |
| 526 | return res |
| 527 | |
| 528 | |
| 529 | if __name__ == '__main__': |
no outgoing calls
no test coverage detected