cls_metric.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 {'acc': correct_num / (all_num + self.eps), }
  30. def get_metric(self):
  31. """
  32. return metrics {
  33. 'acc': 0
  34. }
  35. """
  36. acc = self.correct_num / (self.all_num + self.eps)
  37. self.reset()
  38. return {'acc': acc}
  39. def reset(self):
  40. self.correct_num = 0
  41. self.all_num = 0