accuracy.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import torch.nn as nn
  3. def accuracy(pred, target, topk=1, thresh=None):
  4. """Calculate accuracy according to the prediction and target.
  5. Args:
  6. pred (torch.Tensor): The model prediction, shape (N, num_class)
  7. target (torch.Tensor): The target of each prediction, shape (N, )
  8. topk (int | tuple[int], optional): If the predictions in ``topk``
  9. matches the target, the predictions will be regarded as
  10. correct ones. Defaults to 1.
  11. thresh (float, optional): If not None, predictions with scores under
  12. this threshold are considered incorrect. Default to None.
  13. Returns:
  14. float | tuple[float]: If the input ``topk`` is a single integer,
  15. the function will return a single float as accuracy. If
  16. ``topk`` is a tuple containing multiple integers, the
  17. function will return a tuple containing accuracies of
  18. each ``topk`` number.
  19. """
  20. assert isinstance(topk, (int, tuple))
  21. if isinstance(topk, int):
  22. topk = (topk, )
  23. return_single = True
  24. else:
  25. return_single = False
  26. maxk = max(topk)
  27. if pred.size(0) == 0:
  28. accu = [pred.new_tensor(0.) for i in range(len(topk))]
  29. return accu[0] if return_single else accu
  30. assert pred.ndim == 2 and target.ndim == 1
  31. assert pred.size(0) == target.size(0)
  32. assert maxk <= pred.size(1), \
  33. f'maxk {maxk} exceeds pred dimension {pred.size(1)}'
  34. pred_value, pred_label = pred.topk(maxk, dim=1)
  35. pred_label = pred_label.t() # transpose to shape (maxk, N)
  36. correct = pred_label.eq(target.view(1, -1).expand_as(pred_label))
  37. if thresh is not None:
  38. # Only prediction values larger than thresh are counted as correct
  39. correct = correct & (pred_value > thresh).t()
  40. res = []
  41. for k in topk:
  42. correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
  43. res.append(correct_k.mul_(100.0 / pred.size(0)))
  44. return res[0] if return_single else res
  45. class Accuracy(nn.Module):
  46. def __init__(self, topk=(1, ), thresh=None):
  47. """Module to calculate the accuracy.
  48. Args:
  49. topk (tuple, optional): The criterion used to calculate the
  50. accuracy. Defaults to (1,).
  51. thresh (float, optional): If not None, predictions with scores
  52. under this threshold are considered incorrect. Default to None.
  53. """
  54. super().__init__()
  55. self.topk = topk
  56. self.thresh = thresh
  57. def forward(self, pred, target):
  58. """Forward function to calculate accuracy.
  59. Args:
  60. pred (torch.Tensor): Prediction of models.
  61. target (torch.Tensor): Target for each prediction.
  62. Returns:
  63. tuple[float]: The accuracies under different topk criterions.
  64. """
  65. return accuracy(pred, target, self.topk, self.thresh)