evaluator.py 9.4 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

D
dzhwinter 已提交
15
import warnings
D
Dong Zhihong 已提交
16
import numpy as np
武毅 已提交
17

18 19 20 21 22
from . import layers
from .framework import Program, Variable, program_guard
from . import unique_name
from .layer_helper import LayerHelper
from .initializer import Constant
23
from .layers import detection
武毅 已提交
24

25
__all__ = [
26
    'DetectionMAP',
27
]
Y
Yu Yang 已提交
28 29 30


def _clone_var_(block, var):
D
Dong Zhihong 已提交
31
    assert isinstance(var, Variable)
32 33 34 35 36 37 38 39
    return block.create_var(
        name=var.name,
        shape=var.shape,
        dtype=var.dtype,
        type=var.type,
        lod_level=var.lod_level,
        persistable=True,
    )
D
Dong Zhihong 已提交
40 41


42
class Evaluator:
D
Dong Zhihong 已提交
43
    """
44 45 46 47 48 49
    Warning: better to use the fluid.metrics.* things, more
    flexible support via pure Python and Operator, and decoupled
    with executor. Short doc are intended to urge new user
    start from Metrics.

    Base Class for all evaluators.
50

Y
Yu Yang 已提交
51
    Args:
52
        name(str): The name of evaluator. such as, "accuracy". Used for generate
Y
Yu Yang 已提交
53
            temporary variable name.
54
        main_program(Program, optional): The evaluator should be added to this
Y
Yu Yang 已提交
55
            main_program. Default default_main_program()
56
        startup_program(Program, optional):The parameter should be added to this
Y
Yu Yang 已提交
57
            startup_program. Default default_startup_program()
58

Y
Yu Yang 已提交
59
    Attributes:
60
        states(list): The list of state variables. states will be reset to zero
Y
Yu Yang 已提交
61
            when `reset` is invoked.
62
        metrics(list): The list of metrics variables. They will be calculate
Y
Yu Yang 已提交
63
            every mini-batch
D
Dong Zhihong 已提交
64
    """
武毅 已提交
65

D
Dong Zhihong 已提交
66
    def __init__(self, name, **kwargs):
D
dzhwinter 已提交
67 68
        warnings.warn(
            "The %s is deprecated, because maintain a modified program inside evaluator cause bug easily, please use fluid.metrics.%s instead."
69 70 71
            % (self.__class__.__name__, self.__class__.__name__),
            Warning,
        )
Y
Yu Yang 已提交
72 73 74 75 76
        self.states = []
        self.metrics = []
        self.helper = LayerHelper(name, **kwargs)

    def reset(self, executor, reset_program=None):
D
Dong Zhihong 已提交
77
        """
Y
Yu Yang 已提交
78
        reset metric states at the begin of each pass/user specified batch
79 80 81 82

        Args:
            executor(Executor|ParallelExecutor): a executor for executing the reset_program
            reset_program(Program): a single Program for reset process
D
Dong Zhihong 已提交
83
        """
Y
Yu Yang 已提交
84 85 86
        if reset_program is None:
            reset_program = Program()

87 88 89 90
        with program_guard(main_program=reset_program):
            for var in self.states:
                assert isinstance(var, Variable)
                g_var = _clone_var_(reset_program.current_block(), var)
91 92 93
                layers.fill_constant(
                    shape=g_var.shape, value=0.0, dtype=g_var.dtype, out=g_var
                )
D
Dong Zhihong 已提交
94

Y
Yu Yang 已提交
95
        executor.run(reset_program)
96

Y
Yu Yang 已提交
97
    def eval(self, executor, eval_program=None):
D
Dong Zhihong 已提交
98
        """
Y
Yu Yang 已提交
99
        Evaluate the statistics merged by multiple mini-batches.
100 101 102
        Args:
            executor(Executor|ParallelExecutor): a executor for executing the eval_program
            eval_program(Program): a single Program for eval process
D
Dong Zhihong 已提交
103 104
        """
        raise NotImplementedError()
D
Dong Zhihong 已提交
105

106
    def _create_state(self, suffix, dtype, shape):
武毅 已提交
107
        """
108 109
        Create state variable.

Y
Yu Yang 已提交
110
        Args:
111
            suffix(str): the state suffix.
112
            dtype(str|core.VarDesc.VarType): the state data type
113
            shape(tuple|list): the shape of state
Y
Yu Yang 已提交
114 115

        Returns: State variable
武毅 已提交
116

D
Dong Zhihong 已提交
117
        """
118 119 120 121 122 123
        state = self.helper.create_variable(
            name="_".join([unique_name.generate(self.helper.name), suffix]),
            persistable=True,
            dtype=dtype,
            shape=shape,
        )
Y
Yu Yang 已提交
124 125
        self.states.append(state)
        return state
D
Dong Zhihong 已提交
126

D
Dong Zhihong 已提交
127

128 129
class DetectionMAP(Evaluator):
    """
130 131
    Warning: This would be deprecated in the future. Please use fluid.metrics.DetectionMAP
    instead.
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    Calculate the detection mean average precision (mAP).

    The general steps are as follows:
    1. calculate the true positive and false positive according to the input
        of detection and labels.
    2. calculate mAP value, support two versions: '11 point' and 'integral'.

    Please get more information from the following articles:
      https://sanchom.wordpress.com/tag/average-precision/
      https://arxiv.org/abs/1512.02325

    Args:
        input (Variable): The detection results, which is a LoDTensor with shape
            [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax].
        gt_label (Variable): The ground truth label index, which is a LoDTensor
147
            with shape [N, 1].
148
        gt_box (Variable): The ground truth bounding box (bbox), which is a
149
            LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax].
150 151 152
        gt_difficult (Variable|None): Whether this ground truth is a difficult
            bounding bbox, which can be a LoDTensor [N, 1] or not set. If None,
            it means all the ground truth labels are not difficult bbox.
153 154 155
        class_num (int): The class number.
        background_label (int): The index of background label, the background
            label will be ignored. If set to -1, then all categories will be
翟飞跃 已提交
156
            considered, 0 by default.
157
        overlap_threshold (float): The threshold for deciding true/false
翟飞跃 已提交
158
            positive, 0.5 by default.
159
        evaluate_difficult (bool): Whether to consider difficult ground truth
翟飞跃 已提交
160
            for evaluation, True by default. This argument does not work when
161
            gt_difficult is None.
162 163 164 165 166 167
        ap_version (string): The average precision calculation ways, it must be
            'integral' or '11point'. Please check
            https://sanchom.wordpress.com/tag/average-precision/ for details.
            - 11point: the 11-point interpolated average precision.
            - integral: the natural integral of the precision-recall curve.

168 169
    Examples:
        .. code-block:: python
170

171 172 173 174 175 176 177 178 179
            exe = fluid.executor(place)
            map_evaluator = fluid.Evaluator.DetectionMAP(input,
                gt_label, gt_box, gt_difficult)
            cur_map, accum_map = map_evaluator.get_map_var()
            fetch = [cost, cur_map, accum_map]
            for epoch in PASS_NUM:
                map_evaluator.reset(exe)
                for data in batches:
                    loss, cur_map_v, accum_map_v = exe.run(fetch_list=fetch)
180 181 182 183 184 185 186

        In the above example:

        'cur_map_v' is the mAP of current mini-batch.
        'accum_map_v' is the accumulative mAP of one pass.
    """

187 188 189 190 191 192 193 194 195 196 197 198
    def __init__(
        self,
        input,
        gt_label,
        gt_box,
        gt_difficult=None,
        class_num=None,
        background_label=0,
        overlap_threshold=0.5,
        evaluate_difficult=True,
        ap_version='integral',
    ):
199
        super().__init__("map_eval")
200 201

        gt_label = layers.cast(x=gt_label, dtype=gt_box.dtype)
202 203 204 205 206
        if gt_difficult:
            gt_difficult = layers.cast(x=gt_difficult, dtype=gt_box.dtype)
            label = layers.concat([gt_label, gt_difficult, gt_box], axis=1)
        else:
            label = layers.concat([gt_label, gt_box], axis=1)
207 208

        # calculate mean average precision (mAP) of current mini-batch
209 210 211 212 213 214 215 216 217
        map = detection.detection_map(
            input,
            label,
            class_num,
            background_label,
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            ap_version=ap_version,
        )
218

219 220
        self._create_state(dtype='int32', shape=None, suffix='accum_pos_count')
        self._create_state(dtype='float32', shape=None, suffix='accum_true_pos')
221 222 223
        self._create_state(
            dtype='float32', shape=None, suffix='accum_false_pos'
        )
224 225

        self.has_state = None
226 227 228 229 230 231
        var = self.helper.create_variable(
            persistable=True, dtype='int32', shape=[1]
        )
        self.helper.set_variable_initializer(
            var, initializer=Constant(value=int(0))
        )
232 233 234
        self.has_state = var

        # calculate accumulative mAP
235
        accum_map = detection.detection_map(
236 237
            input,
            label,
238 239
            class_num,
            background_label,
240 241 242 243 244
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            has_state=self.has_state,
            input_states=self.states,
            out_states=self.states,
245 246
            ap_version=ap_version,
        )
247

248 249 250 251 252 253
        layers.fill_constant(
            shape=self.has_state.shape,
            value=1,
            dtype=self.has_state.dtype,
            out=self.has_state,
        )
254 255 256 257 258 259 260 261 262 263 264 265

        self.cur_map = map
        self.accum_map = accum_map

    def get_map_var(self):
        return self.cur_map, self.accum_map

    def reset(self, executor, reset_program=None):
        if reset_program is None:
            reset_program = Program()
        with program_guard(main_program=reset_program):
            var = _clone_var_(reset_program.current_block(), self.has_state)
266 267 268
            layers.fill_constant(
                shape=var.shape, value=0, dtype=var.dtype, out=var
            )
269
        executor.run(reset_program)