Note
You are reading the documentation for MMSelfSup 0.x, which will soon be deprecated by the end of 2022. We recommend you upgrade to MMSelfSup 1.0.0rc versions to enjoy fruitful new features and better performance brought by OpenMMLab 2.0. Check out the changelog, code and documentation of MMSelfSup 1.0.0rc for more details.
Source code for mmselfsup.models.utils.accuracy
# Copyright (c) OpenMMLab. All rights reserved.
from mmcv.runner import BaseModule
[docs]def accuracy(pred, target, topk=1):
"""Compute accuracy of predictions.
Args:
pred (Tensor): The output of the model.
target (Tensor): The labels of data.
topk (int | list[int]): Top-k metric selection. Defaults to 1.
"""
assert isinstance(topk, (int, tuple))
if isinstance(topk, int):
topk = (topk, )
return_single = True
else:
return_single = False
maxk = max(topk)
_, pred_label = pred.topk(maxk, dim=1)
pred_label = pred_label.t()
correct = pred_label.eq(target.contiguous().view(1,
-1).expand_as(pred_label))
res = []
for k in topk:
correct_k = correct[:k].contiguous().view(-1).float().sum(
0, keepdim=True)
res.append(correct_k.mul_(100.0 / pred.size(0)))
return res[0] if return_single else res