accuracy.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import List, Tuple
  18. from kornia.core import Tensor
  19. def accuracy(pred: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
  20. """Compute the accuracy over the k top predictions for the specified values of k.
  21. Args:
  22. pred: the input tensor with the logits to evaluate.
  23. target: the tensor containing the ground truth.
  24. topk: the expected topk ranking.
  25. Example:
  26. >>> logits = torch.tensor([[0, 1, 0]])
  27. >>> target = torch.tensor([[1]])
  28. >>> accuracy(logits, target)
  29. [tensor(100.)]
  30. """
  31. maxk = min(max(topk), pred.size()[1])
  32. batch_size = target.size(0)
  33. _, pred = pred.topk(maxk, 1, True, True)
  34. pred = pred.t()
  35. correct = pred.eq(target.reshape(1, -1).expand_as(pred))
  36. return [correct[: min(k, maxk)].reshape(-1).float().sum(0) * 100.0 / batch_size for k in topk]