average_meter.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Union
  18. from kornia.core import Tensor
  19. class AverageMeter:
  20. """Computes and stores the average and current value.
  21. Example:
  22. >>> stats = AverageMeter()
  23. >>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy
  24. >>> stats.update(acc1, n=1) # where n is batch size usually
  25. >>> round(stats.avg, 2)
  26. 0.99
  27. """
  28. val: Union[float, bool, Tensor]
  29. _avg: Union[float, Tensor]
  30. sum: Union[float, Tensor]
  31. count: int
  32. def __init__(self) -> None:
  33. self.reset()
  34. def reset(self) -> None:
  35. self.val = 0
  36. self._avg = 0
  37. self.sum = 0
  38. self.count = 0
  39. def update(self, val: Union[float, bool, Tensor], n: int = 1) -> None:
  40. self.val = val
  41. self.sum += val * n
  42. self.count += n
  43. self._avg = self.sum / self.count
  44. @property
  45. def avg(self) -> float:
  46. if isinstance(self._avg, Tensor):
  47. return float(self._avg.item())
  48. return self._avg