misc.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. __all__ = ['AverageMeter']
  15. class AverageMeter(object):
  16. """
  17. Computes and stores the average and current value
  18. Code was based on https://github.com/pytorch/examples/blob/master/imagenet/main.py
  19. """
  20. def __init__(self, name='', fmt='f', postfix="", need_avg=True):
  21. self.name = name
  22. self.fmt = fmt
  23. self.postfix = postfix
  24. self.need_avg = need_avg
  25. self.reset()
  26. def reset(self):
  27. """ reset """
  28. self.val = 0
  29. self.avg = 0
  30. self.sum = 0
  31. self.count = 0
  32. def update(self, val, n=1):
  33. """ update """
  34. self.val = val
  35. self.sum += val * n
  36. self.count += n
  37. self.avg = self.sum / self.count
  38. @property
  39. def total(self):
  40. return '{self.name}_sum: {self.sum:{self.fmt}}{self.postfix}'.format(
  41. self=self)
  42. @property
  43. def total_minute(self):
  44. return '{self.name} {s:{self.fmt}}{self.postfix} min'.format(
  45. s=self.sum / 60, self=self)
  46. @property
  47. def mean(self):
  48. return '{self.name}: {self.avg:{self.fmt}}{self.postfix}'.format(
  49. self=self) if self.need_avg else ''
  50. @property
  51. def value(self):
  52. return '{self.name}: {self.val:{self.fmt}}{self.postfix}'.format(
  53. self=self)