You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

metric.py 2.0 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from typing import Iterable, Union
  10. import numpy as np
  11. from ..tensor import Tensor
  12. from .elemwise import abs, maximum, minimum
  13. from .math import topk as _topk
  14. from .tensor import broadcast_to, transpose
  15. def topk_accuracy(
  16. logits: Tensor, target: Tensor, topk: Union[int, Iterable[int]] = 1
  17. ) -> Union[Tensor, Iterable[Tensor]]:
  18. r"""
  19. Calculates the classification accuracy given predicted logits and ground-truth labels.
  20. :param logits: model predictions of shape `[batch_size, num_classes]`,
  21. representing the probability (likelyhood) of each class.
  22. :param target: ground-truth labels, 1d tensor of int32.
  23. :param topk: specifies the topk values, could be an int or tuple of ints. Default: 1
  24. :return: tensor(s) of classification accuracy between 0.0 and 1.0.
  25. Examples:
  26. .. testcode::
  27. import numpy as np
  28. from megengine import tensor
  29. import megengine.functional as F
  30. logits = tensor(np.arange(80, dtype=np.int32).reshape(8,10))
  31. target = tensor(np.arange(8, dtype=np.int32))
  32. top1, top5 = F.metric.topk_accuracy(logits, target, (1, 5))
  33. print(top1.numpy(), top5.numpy())
  34. Outputs:
  35. .. testoutput::
  36. 0.0 0.375
  37. """
  38. if isinstance(topk, int):
  39. topk = (topk,)
  40. _, pred = _topk(logits, k=max(topk), descending=True)
  41. accs = []
  42. for k in topk:
  43. correct = pred[:, :k].detach() == broadcast_to(
  44. transpose(target, (0, "x")), (target.shape[0], k)
  45. )
  46. accs.append(correct.astype(np.float32).sum() / target.shape[0])
  47. if len(topk) == 1: # type: ignore[arg-type]
  48. accs = accs[0]
  49. return accs

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台