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.7 kB

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

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