stats.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. # 双向队列,能从头尾拿数据
  24. self.deque = collections.deque(maxlen=window_size)
  25. def add_value(self, value):
  26. self.deque.append(value)
  27. def get_median_value(self):
  28. return np.median(self.deque)
  29. def Time():
  30. return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
  31. class TrainingStats(object):
  32. def __init__(self, window_size, stats_keys):
  33. self.window_size = window_size
  34. self.smoothed_losses_and_metrics = {
  35. key: SmoothedValue(window_size)
  36. for key in stats_keys
  37. }
  38. def update(self, stats):
  39. for k, v in stats.items():
  40. if k not in self.smoothed_losses_and_metrics:
  41. self.smoothed_losses_and_metrics[k] = SmoothedValue(
  42. self.window_size)
  43. self.smoothed_losses_and_metrics[k].add_value(v)
  44. def get(self, extras=None):
  45. stats = collections.OrderedDict()
  46. if extras:
  47. for k, v in extras.items():
  48. stats[k] = v
  49. for k, v in self.smoothed_losses_and_metrics.items():
  50. stats[k] = round(v.get_median_value(), 6)
  51. return stats
  52. def log(self, extras=None):
  53. d = self.get(extras)
  54. strs = []
  55. for k, v in d.items():
  56. strs.append('{}: {:x<6f}'.format(k, v))
  57. strs = ', '.join(strs)
  58. return strs