cls_metric.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. class ClsMetric(object):
  15. def __init__(self, main_indicator="acc", **kwargs):
  16. self.main_indicator = main_indicator
  17. self.eps = 1e-5
  18. self.reset()
  19. def __call__(self, pred_label, *args, **kwargs):
  20. preds, labels = pred_label
  21. correct_num = 0
  22. all_num = 0
  23. for (pred, pred_conf), (target, _) in zip(preds, labels):
  24. if pred == target:
  25. correct_num += 1
  26. all_num += 1
  27. self.correct_num += correct_num
  28. self.all_num += all_num
  29. return {
  30. "acc": correct_num / (all_num + self.eps),
  31. }
  32. def get_metric(self):
  33. """
  34. return metrics {
  35. 'acc': 0
  36. }
  37. """
  38. acc = self.correct_num / (self.all_num + self.eps)
  39. self.reset()
  40. return {"acc": acc}
  41. def reset(self):
  42. self.correct_num = 0
  43. self.all_num = 0