Computes the accuracy over the k top predictions for the specified values of k
(output, target, topk=(1,))
| 182 | |
| 183 | |
| 184 | def accuracy(output, target, topk=(1,)): |
| 185 | """Computes the accuracy over the k top predictions for the specified values of k""" |
| 186 | with torch.no_grad(): |
| 187 | maxk = max(topk) |
| 188 | batch_size = target.size(0) |
| 189 | |
| 190 | _, pred = output.topk(maxk, 1, True, True) |
| 191 | pred = pred.t() |
| 192 | correct = pred.eq(target.view(1, -1).expand_as(pred)) |
| 193 | |
| 194 | res = [] |
| 195 | for k in topk: |
| 196 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) |
| 197 | res.append(correct_k.mul_(100.0 / batch_size)) |
| 198 | return res |
| 199 | |
| 200 | |
| 201 | def str2bool(v): |