Computes the accuracy over the k top predictions for the specified values of k Args output: logits or probs (num of batch, num of classes) target: (num of batch, 1) or (num of batch, ) topk: list of returned k refer: https://github.com/pytorch/examples/
(output, target, topk=(1,))
| 261 | |
| 262 | |
| 263 | def accuracy(output, target, topk=(1,)): |
| 264 | """ |
| 265 | Computes the accuracy over the k top predictions for the specified values of k |
| 266 | |
| 267 | Args |
| 268 | output: logits or probs (num of batch, num of classes) |
| 269 | target: (num of batch, 1) or (num of batch, ) |
| 270 | topk: list of returned k |
| 271 | |
| 272 | refer: https://github.com/pytorch/examples/blob/master/imagenet/main.py |
| 273 | """ |
| 274 | |
| 275 | with torch.no_grad(): |
| 276 | maxk = max(topk) # get k in top-k |
| 277 | batch_size = target.size(0) # get batch size of target |
| 278 | |
| 279 | # torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) |
| 280 | # return: value, index |
| 281 | _, pred = output.topk(k=maxk, dim=1, largest=True, sorted=True) # pred: [num of batch, k] |
| 282 | pred = pred.t() # pred: [k, num of batch] |
| 283 | |
| 284 | # [1, num of batch] -> [k, num_of_batch] : bool |
| 285 | correct = pred.eq(target.view(1, -1).expand_as(pred)) |
| 286 | |
| 287 | res = [] |
| 288 | for k in topk: |
| 289 | correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) |
| 290 | res.append(correct_k.mul_(100.0 / batch_size)) |
| 291 | # np.shape(res): [k, 1] |
| 292 | return res |
| 293 | |
| 294 | |
| 295 | def ce_loss(logits, targets, use_hard_labels=True, reduction='none'): |
nothing calls this directly
no outgoing calls
no test coverage detected