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.

utils.py 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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. import collections
  10. from typing import Iterable, Union
  11. import numpy as np
  12. from ..core.ops.builtin import Copy
  13. from ..core.tensor import Tensor
  14. from ..core.tensor.core import apply
  15. from .math import topk as _topk
  16. from .tensor import broadcast_to, transpose
  17. def accuracy(
  18. logits: Tensor, target: Tensor, topk: Union[int, Iterable[int]] = 1
  19. ) -> Union[Tensor, Iterable[Tensor]]:
  20. r"""
  21. Calculates the classification accuracy given predicted logits and ground-truth labels.
  22. :param logits: model predictions of shape `[batch_size, num_classes]`,
  23. representing the probability (likelyhood) of each class.
  24. :param target: ground-truth labels, 1d tensor of int32.
  25. :param topk: specifies the topk values, could be an int or tuple of ints. Default: 1
  26. :return: tensor(s) of classification accuracy between 0.0 and 1.0.
  27. Examples:
  28. .. testcode::
  29. import numpy as np
  30. from megengine import tensor
  31. import megengine.functional as F
  32. logits = tensor(np.arange(80, dtype=np.int32).reshape(8,10))
  33. target = tensor(np.arange(8, dtype=np.int32))
  34. top1, top5 = F.accuracy(logits, target, (1, 5))
  35. print(top1.numpy(), top5.numpy())
  36. Outputs:
  37. .. testoutput::
  38. [0.] [0.375]
  39. """
  40. if isinstance(topk, int):
  41. topk = (topk,)
  42. _, pred = _topk(logits, k=max(topk), descending=True)
  43. accs = []
  44. for k in topk:
  45. correct = pred[:, :k].detach() == broadcast_to(
  46. transpose(target, (0, "x")), (target.shape[0], k)
  47. )
  48. accs.append(correct.astype(np.float32).sum() / target.shape[0])
  49. if len(topk) == 1: # type: ignore[arg-type]
  50. accs = accs[0]
  51. return accs
  52. def copy(inp, cn):
  53. r"""
  54. Copies tensor to another device.
  55. :param inp: input tensor.
  56. :param cn: destination device.
  57. Examples:
  58. .. testcode::
  59. import numpy as np
  60. from megengine import tensor
  61. import megengine.functional as F
  62. x = tensor([1, 2, 3], np.int32)
  63. y = F.copy(x, "xpu1")
  64. print(y.numpy())
  65. Outputs:
  66. .. testoutput::
  67. [1 2 3]
  68. """
  69. return apply(Copy(comp_node=cn), inp)[0]

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