evaluator.py 17.1 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 26
__all__ = [
    'ChunkEvaluator',
27
    'EditDistance',
28
    'DetectionMAP',
29
]
Y
Yu Yang 已提交
30 31 32


def _clone_var_(block, var):
D
Dong Zhihong 已提交
33
    assert isinstance(var, Variable)
34 35 36 37 38 39 40 41
    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 已提交
42 43


D
Dong Zhihong 已提交
44 45
class Evaluator(object):
    """
46 47 48 49 50 51
    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.
52

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

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

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

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

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

89 90 91 92
        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)
93 94 95
                layers.fill_constant(
                    shape=g_var.shape, value=0.0, dtype=g_var.dtype, out=g_var
                )
D
Dong Zhihong 已提交
96

Y
Yu Yang 已提交
97
        executor.run(reset_program)
98

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

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

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

        Returns: State variable
武毅 已提交
118

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

D
Dong Zhihong 已提交
129

G
guosheng 已提交
130 131
class ChunkEvaluator(Evaluator):
    """
132
    Warning: This would be deprecated in the future. Please use fluid.metrics.ChunkEvaluator
133 134
    instead.

135 136
    Accumulate counter numbers output by chunk_eval from mini-batches and
    compute the precision recall and F1-score using the accumulated counter
G
guosheng 已提交
137
    numbers.
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    For some basics of chunking, please refer to
    'Chunking with Support Vector Machines <https://aclanthology.info/pdf/N/N01/N01-1025.pdf>'.

    Args:
        input (Variable): prediction output of the network.
        label (Variable): label of the test data set.
        chunk_scheme (str): can be IOB/IOE/IOBES and IO. See the chunk_eval op for details.
        num_chunk_types (int): the number of chunk type.
        excluded_chunk_types (list): A list including chunk type ids, indicating chunk types that are not counted.

    Returns:
        tuple: tuple containing: precision, recall, f1_score

    Examples:
        .. code-block:: python

            exe = fluid.executor(place)
            evaluator = fluid.Evaluator.ChunkEvaluator(input, label)
            for epoch in PASS_NUM:
                evaluator.reset(exe)
                for data in batches:
                    loss = exe.run(fetch_list=[cost])
                distance, instance_error = distance_evaluator.eval(exe)
G
guosheng 已提交
161 162
    """

163
    def __init__(
164 165 166 167 168 169 170
        self,
        input,
        label,
        chunk_scheme,
        num_chunk_types,
        excluded_chunk_types=None,
    ):
171
        super(ChunkEvaluator, self).__init__("chunk_eval")
G
guosheng 已提交
172 173 174 175
        main_program = self.helper.main_program
        if main_program.current_block().idx != 0:
            raise ValueError("You can only invoke Evaluator in root block")

176 177 178 179 180 181
        self.num_infer_chunks = self._create_state(
            dtype='int64', shape=[1], suffix='num_infer_chunks'
        )
        self.num_label_chunks = self._create_state(
            dtype='int64', shape=[1], suffix='num_label_chunks'
        )
182
        self.num_correct_chunks = self._create_state(
183 184 185 186 187 188 189 190 191 192
            dtype='int64', shape=[1], suffix='num_correct_chunks'
        )
        (
            precision,
            recall,
            f1_score,
            num_infer_chunks,
            num_label_chunks,
            num_correct_chunks,
        ) = layers.chunk_eval(
G
guosheng 已提交
193 194 195 196
            input=input,
            label=label,
            chunk_scheme=chunk_scheme,
            num_chunk_types=num_chunk_types,
197 198
            excluded_chunk_types=excluded_chunk_types,
        )
199 200 201 202 203 204 205 206 207 208 209 210
        layers.sums(
            input=[self.num_infer_chunks, num_infer_chunks],
            out=self.num_infer_chunks,
        )
        layers.sums(
            input=[self.num_label_chunks, num_label_chunks],
            out=self.num_label_chunks,
        )
        layers.sums(
            input=[self.num_correct_chunks, num_correct_chunks],
            out=self.num_correct_chunks,
        )
G
guosheng 已提交
211 212 213 214 215 216 217 218 219

        self.metrics.extend([precision, recall, f1_score])

    def eval(self, executor, eval_program=None):
        if eval_program is None:
            eval_program = Program()
        block = eval_program.current_block()
        num_infer_chunks, num_label_chunks, num_correct_chunks = executor.run(
            eval_program,
220 221
            fetch_list=[_clone_var_(block, state) for state in self.states],
        )
G
guosheng 已提交
222 223 224
        num_infer_chunks = num_infer_chunks[0]
        num_label_chunks = num_label_chunks[0]
        num_correct_chunks = num_correct_chunks[0]
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        precision = (
            float(num_correct_chunks) / num_infer_chunks
            if num_infer_chunks
            else 0
        )
        recall = (
            float(num_correct_chunks) / num_label_chunks
            if num_label_chunks
            else 0
        )
        f1_score = (
            float(2 * precision * recall) / (precision + recall)
            if num_correct_chunks
            else 0
        )
        return (
            np.array([precision], dtype='float32'),
            np.array([recall], dtype='float32'),
            np.array([f1_score], dtype='float32'),
        )
245 246 247 248


class EditDistance(Evaluator):
    """
249 250
    Warning: This would be deprecated in the future. Please use fluid.metrics.EditDistance
    instead.
W
wanghaoshuang 已提交
251
    Accumulate edit distance sum and sequence number from mini-batches and
252
    compute the average edit_distance and instance error of all batches.
W
wanghaoshuang 已提交
253 254

    Args:
W
wanghaoshuang 已提交
255
        input: the sequences predicted by network.
Z
zhangchunle 已提交
256
        label: the target sequences which must have same sequence count
W
wanghaoshuang 已提交
257 258 259 260
        with input.
        ignored_tokens(list of int): Tokens that should be removed before
        calculating edit distance.

261 262
    Examples:
        .. code-block:: python
W
wanghaoshuang 已提交
263

264 265 266 267 268 269 270
            exe = fluid.executor(place)
            distance_evaluator = fluid.Evaluator.EditDistance(input, label)
            for epoch in PASS_NUM:
                distance_evaluator.reset(exe)
                for data in batches:
                    loss = exe.run(fetch_list=[cost])
                distance, instance_error = distance_evaluator.eval(exe)
W
wanghaoshuang 已提交
271 272

        In the above example:
273
        'distance' is the average of the edit distance in a pass.
274
        'instance_error' is the instance error rate in a pass.
W
wanghaoshuang 已提交
275

276 277
    """

W
wanghaoshuang 已提交
278
    def __init__(self, input, label, ignored_tokens=None, **kwargs):
279 280 281 282 283
        super(EditDistance, self).__init__("edit_distance", **kwargs)
        main_program = self.helper.main_program
        if main_program.current_block().idx != 0:
            raise ValueError("You can only invoke Evaluator in root block")

284 285 286 287 288 289 290 291 292 293 294 295
        self.total_distance = self._create_state(
            dtype='float32', shape=[1], suffix='total_distance'
        )
        self.seq_num = self._create_state(
            dtype='int64', shape=[1], suffix='seq_num'
        )
        self.instance_error = self._create_state(
            dtype='int64', shape=[1], suffix='instance_error'
        )
        distances, seq_num = layers.edit_distance(
            input=input, label=label, ignored_tokens=ignored_tokens
        )
296 297 298

        zero = layers.fill_constant(shape=[1], value=0.0, dtype='float32')
        compare_result = layers.equal(distances, zero)
299
        compare_result_int = layers.cast(x=compare_result, dtype='int64')
300
        seq_right_count = layers.reduce_sum(compare_result_int)
301 302 303
        instance_error_count = layers.elementwise_sub(
            x=seq_num, y=seq_right_count
        )
304
        total_distance = layers.reduce_sum(distances)
305 306 307
        layers.sums(
            input=[self.total_distance, total_distance], out=self.total_distance
        )
308
        layers.sums(input=[self.seq_num, seq_num], out=self.seq_num)
309 310 311 312
        layers.sums(
            input=[self.instance_error, instance_error_count],
            out=self.instance_error,
        )
313
        self.metrics.append(total_distance)
314
        self.metrics.append(instance_error_count)
315 316 317 318 319 320

    def eval(self, executor, eval_program=None):
        if eval_program is None:
            eval_program = Program()
        block = eval_program.current_block()
        with program_guard(main_program=eval_program):
321
            total_distance = _clone_var_(block, self.total_distance)
322
            seq_num = _clone_var_(block, self.seq_num)
323
            instance_error = _clone_var_(block, self.instance_error)
324
            seq_num = layers.cast(x=seq_num, dtype='float32')
325
            instance_error = layers.cast(x=instance_error, dtype='float32')
326
            avg_distance = layers.elementwise_div(x=total_distance, y=seq_num)
327 328 329 330 331 332
            avg_instance_error = layers.elementwise_div(
                x=instance_error, y=seq_num
            )
            result = executor.run(
                eval_program, fetch_list=[avg_distance, avg_instance_error]
            )
333
        return np.array(result[0]), np.array(result[1])
334 335 336 337


class DetectionMAP(Evaluator):
    """
338 339
    Warning: This would be deprecated in the future. Please use fluid.metrics.DetectionMAP
    instead.
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    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
355
            with shape [N, 1].
356
        gt_box (Variable): The ground truth bounding box (bbox), which is a
357
            LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax].
358 359 360
        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.
361 362 363
        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
翟飞跃 已提交
364
            considered, 0 by default.
365
        overlap_threshold (float): The threshold for deciding true/false
翟飞跃 已提交
366
            positive, 0.5 by default.
367
        evaluate_difficult (bool): Whether to consider difficult ground truth
翟飞跃 已提交
368
            for evaluation, True by default. This argument does not work when
369
            gt_difficult is None.
370 371 372 373 374 375
        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.

376 377
    Examples:
        .. code-block:: python
378

379 380 381 382 383 384 385 386 387
            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)
388 389 390 391 392 393 394

        In the above example:

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

395 396 397 398 399 400 401 402 403 404 405 406
    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',
    ):
407 408 409
        super(DetectionMAP, self).__init__("map_eval")

        gt_label = layers.cast(x=gt_label, dtype=gt_box.dtype)
410 411 412 413 414
        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)
415 416

        # calculate mean average precision (mAP) of current mini-batch
417 418 419 420 421 422 423 424 425
        map = detection.detection_map(
            input,
            label,
            class_num,
            background_label,
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            ap_version=ap_version,
        )
426

427 428
        self._create_state(dtype='int32', shape=None, suffix='accum_pos_count')
        self._create_state(dtype='float32', shape=None, suffix='accum_true_pos')
429 430 431
        self._create_state(
            dtype='float32', shape=None, suffix='accum_false_pos'
        )
432 433

        self.has_state = None
434 435 436 437 438 439
        var = self.helper.create_variable(
            persistable=True, dtype='int32', shape=[1]
        )
        self.helper.set_variable_initializer(
            var, initializer=Constant(value=int(0))
        )
440 441 442
        self.has_state = var

        # calculate accumulative mAP
443
        accum_map = detection.detection_map(
444 445
            input,
            label,
446 447
            class_num,
            background_label,
448 449 450 451 452
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            has_state=self.has_state,
            input_states=self.states,
            out_states=self.states,
453 454
            ap_version=ap_version,
        )
455

456 457 458 459 460 461
        layers.fill_constant(
            shape=self.has_state.shape,
            value=1,
            dtype=self.has_state.dtype,
            out=self.has_state,
        )
462 463 464 465 466 467 468 469 470 471 472 473

        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)
474 475 476
            layers.fill_constant(
                shape=var.shape, value=0, dtype=var.dtype, out=var
            )
477
        executor.run(reset_program)