3
0

stats.py 2.6 KB

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