misc.py 1.5 KB
Newer Older
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
W
WuHaobo 已提交
14 15 16 17 18 19 20 21 22

__all__ = ['AverageMeter']


class AverageMeter(object):
    """
    Computes and stores the average and current value
    """

23
    def __init__(self, name='', fmt='f', need_avg=False):
W
WuHaobo 已提交
24 25
        self.name = name
        self.fmt = fmt
26
        self.need_avg = need_avg
W
WuHaobo 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
        self.reset()

    def reset(self):
        """ reset """
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        """ update """
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

43 44 45 46 47 48 49 50 51 52 53 54
    @property
    def total(self):
        return '[{self.name}_sum: {self.sum:{self.fmt}}]'.format(self=self)

    @property
    def mean(self):
        return '[{self.name}_avg: {self.avg:{self.fmt}}]'.format(
            self=self) if self.need_avg else ''

    @property
    def value(self):
        return '[{self.name}: {self.val:{self.fmt}}]'.format(self=self)