metrics.py 3.6 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from __future__ import absolute_import

import six
import abc
19
import numpy as np
D
dengkaipeng 已提交
20
import paddle.fluid as fluid
D
dengkaipeng 已提交
21

D
dengkaipeng 已提交
22 23 24 25 26
import logging
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)

27
__all__ = ['Metric', 'Accuracy']
D
dengkaipeng 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41


@six.add_metaclass(abc.ABCMeta)
class Metric(object):
    """
    Base class for metric, encapsulates metric logic and APIs

    Usage:
    m = SomeMetric()
    for prediction, label in ...:
        m.update(prediction, label)
    m.accumulate()
    """

D
dengkaipeng 已提交
42
    @abc.abstractmethod
D
dengkaipeng 已提交
43 44 45 46
    def reset(self):
        """
        Reset states and result
        """
Q
qingqing01 已提交
47 48
        raise NotImplementedError("function 'reset' not implemented in {}.".
                                  format(self.__class__.__name__))
D
dengkaipeng 已提交
49 50 51 52 53 54

    @abc.abstractmethod
    def update(self, *args, **kwargs):
        """
        Update states for metric
        """
Q
qingqing01 已提交
55 56
        raise NotImplementedError("function 'update' not implemented in {}.".
                                  format(self.__class__.__name__))
D
dengkaipeng 已提交
57 58 59 60 61 62

    @abc.abstractmethod
    def accumulate(self):
        """
        Accumulates statistics, computes and returns the metric value
        """
Q
qingqing01 已提交
63 64 65 66 67 68 69 70 71 72 73
        raise NotImplementedError(
            "function 'accumulate' not implemented in {}.".format(
                self.__class__.__name__))

    @abc.abstractmethod
    def name(self):
        """
        Returns metric name
        """
        raise NotImplementedError("function 'name' not implemented in {}.".
                                  format(self.__class__.__name__))
D
dengkaipeng 已提交
74

D
dengkaipeng 已提交
75 76 77 78 79 80
    def add_metric_op(self, pred, label):
        """
        Add process op for metric in program
        """
        return pred, label

81 82 83 84 85 86

class Accuracy(Metric):
    """
    Encapsulates accuracy metric logic
    """

Q
qingqing01 已提交
87 88 89 90 91 92
    def __init__(self, topk=(1, ), name=None, *args, **kwargs):
        super(Accuracy, self).__init__(*args, **kwargs)
        self.topk = topk
        self.maxk = max(topk)
        self._init_name(name)
        self.reset()
93

D
dengkaipeng 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107
    def add_metric_op(self, pred, label, *args, **kwargs):
        pred = fluid.layers.argsort(pred[0], descending=True)[1][:, :self.maxk]
        correct = pred == label[0]
        return correct

    def update(self, correct, *args, **kwargs):
        accs = []
        for i, k in enumerate(self.topk):
            num_corrects = correct[:, :k].sum()
            num_samples = len(correct)
            accs.append(float(num_corrects) / num_samples)
            self.total[i] += num_corrects
            self.count[i] += num_samples
        return accs
108 109

    def reset(self):
D
dengkaipeng 已提交
110 111
        self.total = [0.] * len(self.topk)
        self.count = [0] * len(self.topk)
112 113 114

    def accumulate(self):
        res = []
D
dengkaipeng 已提交
115 116
        for t, c in zip(self.total, self.count):
            res.append(float(t) / c)
117 118
        return res

Q
qingqing01 已提交
119 120 121 122 123 124 125 126 127
    def _init_name(self, name):
        name = name or 'acc'
        if self.maxk != 1:
            self._name = ['{}_top{}'.format(name, k) for k in self.topk]
        else:
            self._name = ['acc']

    def name(self):
        return self._name