stats.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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__ = ['SmoothedValue', 'TrainingStats']
  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=20, fmt=None):
  23. if fmt is None:
  24. fmt = "{median:.4f} ({avg:.4f})"
  25. self.deque = collections.deque(maxlen=window_size)
  26. self.fmt = fmt
  27. self.total = 0.
  28. self.count = 0
  29. def update(self, value, n=1):
  30. self.deque.append(value)
  31. self.count += n
  32. self.total += value * n
  33. @property
  34. def median(self):
  35. return np.median(self.deque)
  36. @property
  37. def avg(self):
  38. return np.mean(self.deque)
  39. @property
  40. def max(self):
  41. return np.max(self.deque)
  42. @property
  43. def value(self):
  44. return self.deque[-1]
  45. @property
  46. def global_avg(self):
  47. return self.total / self.count
  48. def __str__(self):
  49. return self.fmt.format(
  50. median=self.median, avg=self.avg, max=self.max, value=self.value)
  51. class TrainingStats(object):
  52. def __init__(self, window_size, delimiter=' '):
  53. self.meters = None
  54. self.window_size = window_size
  55. self.delimiter = delimiter
  56. def update(self, stats):
  57. if self.meters is None:
  58. self.meters = {
  59. k: SmoothedValue(self.window_size)
  60. for k in stats.keys()
  61. }
  62. for k, v in self.meters.items():
  63. v.update(stats[k].numpy())
  64. def get(self, extras=None):
  65. stats = collections.OrderedDict()
  66. if extras:
  67. for k, v in extras.items():
  68. stats[k] = v
  69. for k, v in self.meters.items():
  70. stats[k] = format(v.median, '.6f')
  71. return stats
  72. def log(self, extras=None):
  73. d = self.get(extras)
  74. strs = []
  75. for k, v in d.items():
  76. strs.append("{}: {}".format(k, str(v)))
  77. return self.delimiter.join(strs)