stats.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import collections
  15. import numpy as np
  16. import datetime
  17. __all__ = ['TrainingStats', 'Time']
  18. class SmoothedValue(object):
  19. """Track a series of values and provide access to smoothed values over a
  20. window or the global series average.
  21. """
  22. def __init__(self, window_size):
  23. self.deque = collections.deque(maxlen=window_size)
  24. def add_value(self, value):
  25. self.deque.append(value)
  26. def get_median_value(self):
  27. return np.median(self.deque)
  28. def Time():
  29. return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
  30. class TrainingStats(object):
  31. def __init__(self, window_size, stats_keys):
  32. self.window_size = window_size
  33. self.smoothed_losses_and_metrics = {
  34. key: SmoothedValue(window_size)
  35. for key in stats_keys
  36. }
  37. def update(self, stats):
  38. for k, v in stats.items():
  39. if k not in self.smoothed_losses_and_metrics:
  40. self.smoothed_losses_and_metrics[k] = SmoothedValue(
  41. self.window_size)
  42. self.smoothed_losses_and_metrics[k].add_value(v)
  43. def get(self, extras=None):
  44. stats = collections.OrderedDict()
  45. if extras:
  46. for k, v in extras.items():
  47. stats[k] = v
  48. for k, v in self.smoothed_losses_and_metrics.items():
  49. stats[k] = round(v.get_median_value(), 6)
  50. return stats
  51. def log(self, extras=None):
  52. d = self.get(extras)
  53. strs = []
  54. for k, v in d.items():
  55. strs.append('{}: {:x<6f}'.format(k, v))
  56. strs = ', '.join(strs)
  57. return strs