stats.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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) for key in stats_keys
  35. }
  36. def update(self, stats):
  37. for k, v in stats.items():
  38. if k not in self.smoothed_losses_and_metrics:
  39. self.smoothed_losses_and_metrics[k] = SmoothedValue(self.window_size)
  40. self.smoothed_losses_and_metrics[k].add_value(v)
  41. def get(self, extras=None):
  42. stats = collections.OrderedDict()
  43. if extras:
  44. for k, v in extras.items():
  45. stats[k] = v
  46. for k, v in self.smoothed_losses_and_metrics.items():
  47. stats[k] = round(v.get_median_value(), 6)
  48. return stats
  49. def log(self, extras=None):
  50. d = self.get(extras)
  51. strs = []
  52. for k, v in d.items():
  53. strs.append("{}: {:x<6f}".format(k, v))
  54. strs = ", ".join(strs)
  55. return strs