stats.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (c) 2019 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.smoothed_losses_and_metrics = {
  33. key: SmoothedValue(window_size)
  34. for key in stats_keys
  35. }
  36. def update(self, stats):
  37. for k, v in self.smoothed_losses_and_metrics.items():
  38. v.add_value(stats[k])
  39. def get(self, extras=None):
  40. stats = collections.OrderedDict()
  41. if extras:
  42. for k, v in extras.items():
  43. stats[k] = v
  44. for k, v in self.smoothed_losses_and_metrics.items():
  45. stats[k] = format(v.get_median_value(), '.6f')
  46. return stats
  47. def log(self, extras=None):
  48. d = self.get(extras)
  49. strs = ', '.join(str(dict({x: y})).strip('{}') for x, y in d.items())
  50. return strs