misc.py 1.9 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

__all__ = ['AverageMeter']


class AverageMeter(object):
    """
    Computes and stores the average and current value
littletomatodonkey's avatar
littletomatodonkey 已提交
21
    Code was based on https://github.com/pytorch/examples/blob/master/imagenet/main.py
W
WuHaobo 已提交
22 23
    """

L
littletomatodonkey 已提交
24
    def __init__(self, name='', fmt='f', postfix="", need_avg=True):
W
WuHaobo 已提交
25 26
        self.name = name
        self.fmt = fmt
L
littletomatodonkey 已提交
27
        self.postfix = postfix
28
        self.need_avg = need_avg
W
WuHaobo 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        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

45 46
    @property
    def total(self):
L
littletomatodonkey 已提交
47 48
        return '{self.name}_sum: {self.sum:{self.fmt}}{self.postfix}'.format(
            self=self)
49

50 51
    @property
    def total_minute(self):
L
littletomatodonkey 已提交
52
        return '{self.name} {s:{self.fmt}}{self.postfix} min'.format(
53 54
            s=self.sum / 60, self=self)

55 56
    @property
    def mean(self):
L
littletomatodonkey 已提交
57
        return '{self.name}: {self.avg:{self.fmt}}{self.postfix}'.format(
58 59 60 61
            self=self) if self.need_avg else ''

    @property
    def value(self):
L
littletomatodonkey 已提交
62 63
        return '{self.name}: {self.val:{self.fmt}}{self.postfix}'.format(
            self=self)