cls_metric.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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.reset()
  18. def __call__(self, pred_label, *args, **kwargs):
  19. preds, labels = pred_label
  20. correct_num = 0
  21. all_num = 0
  22. for (pred, pred_conf), (target, _) in zip(preds, labels):
  23. if pred == target:
  24. correct_num += 1
  25. all_num += 1
  26. self.correct_num += correct_num
  27. self.all_num += all_num
  28. return {'acc': correct_num / all_num, }
  29. def get_metric(self):
  30. """
  31. return metrics {
  32. 'acc': 0
  33. }
  34. """
  35. acc = self.correct_num / self.all_num
  36. self.reset()
  37. return {'acc': acc}
  38. def reset(self):
  39. self.correct_num = 0
  40. self.all_num = 0