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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. __all__ = [
  16. "topk_accuracy",
  17. ]
  18. def topk_accuracy(
  19. logits: Tensor, target: Tensor, topk: Union[int, Iterable[int]] = 1
  20. ) -> Union[Tensor, Iterable[Tensor]]:
  21. r"""Calculates the classification accuracy given predicted logits and ground-truth labels.
  22. Args:
  23. logits: model predictions of shape `[batch_size, num_classes]`,
  24. representing the probability (likelyhood) of each class.
  25. target: ground-truth labels, 1d tensor of int32.
  26. topk: specifies the topk values, could be an int or tuple of ints. Default: 1
  27. Returns:
  28. tensor(s) of classification accuracy between 0.0 and 1.0.
  29. """
  30. if isinstance(topk, int):
  31. topk = (topk,)
  32. _, pred = _topk(logits, k=max(topk), descending=True)
  33. accs = []
  34. for k in topk:
  35. correct = pred[:, :k].detach() == broadcast_to(
  36. transpose(target, (0, "x")), (target.shape[0], k)
  37. )
  38. accs.append(correct.astype(np.float32).sum() / target.shape[0])
  39. if len(topk) == 1: # type: ignore[arg-type]
  40. accs = accs[0]
  41. return accs