metrics.py 37.1 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2018 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.
"""
Fluid Metrics
"""
17

D
dzhwinter 已提交
18 19 20
import numpy as np
import copy

D
Dang Qingqing 已提交
21 22 23 24 25
from .layer_helper import LayerHelper
from .initializer import Constant
from . import unique_name
from .framework import Program, Variable, program_guard
from . import layers
26
from .layers import detection
D
Dang Qingqing 已提交
27

D
dzhwinter 已提交
28 29 30
__all__ = [
    'MetricBase',
    'CompositeMetric',
31 32
    'Precision',
    'Recall',
D
dzhwinter 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45
    'Accuracy',
    'ChunkEvaluator',
    'EditDistance',
    'DetectionMAP',
    'Auc',
]


def _is_numpy_(var):
    return isinstance(var, (np.ndarray, np.generic))


def _is_number_(var):
46 47 48 49 50 51
    return (
        isinstance(var, int)
        or isinstance(var, np.int64)
        or isinstance(var, float)
        or (isinstance(var, np.ndarray) and var.shape == (1,))
    )
D
dzhwinter 已提交
52 53 54 55 56 57


def _is_number_or_matrix_(var):
    return _is_number_(var) or isinstance(var, np.ndarray)


58
class MetricBase:
D
dzhwinter 已提交
59
    """
60 61 62 63
    In many cases, we usually have to split the test data into mini-batches for evaluating
    deep neural networks, therefore we need to collect the evaluation results of each
    mini-batch and aggregate them into the final result. The paddle.fluid.metrics is
    designed for a convenient way of deep neural network evaluation.
D
dzhwinter 已提交
64

65
    The paddle.fluid.metrics contains serval different evaluation metrics
P
pkpk 已提交
66 67
    like precision and recall, and most of them have the following functions:

68
    1. take the prediction result and the corresponding labels of a mini-batch as input,
P
pkpk 已提交
69 70 71 72 73
    then compute the evaluation result for the input mini-batch.

    2. aggregate the existing evaluation results as the overall performance.

    The class Metric is the base class for all classes in paddle.fluid.metrics, it defines
T
tianshuo78520a 已提交
74
    the fundamental APIs for all metrics classes, including:
P
pkpk 已提交
75 76 77 78 79 80 81 82 83

    1. update(preds, labels): given the prediction results (preds) and the labels (labels)
    of some mini-batch, compute the evaluation result of that mini-batch, and memorize the
    evaluation result.

    2. eval(): aggregate all existing evaluation result in the memory, and return the overall
    performance across different mini-batches.

    3. reset(): empty the memory.
84

D
dzhwinter 已提交
85 86
    """

87
    def __init__(self, name):
P
pkpk 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101
        """
        The constructor of the metric class.

        Args:
            name(str): The name of metric instance. such as, "accuracy".
                  It can be used to distinguish different metric instances in a model.

        Returns:
            The constructed class instance.

        Return types:
            The MetricBase or its succeed classes

        """
102
        self._name = str(name) if name is not None else self.__class__.__name__
D
dzhwinter 已提交
103 104 105 106 107 108

    def __str__(self):
        return self._name

    def reset(self):
        """
109 110
        reset function empties the evaluation memory for previous mini-batches.

P
pkpk 已提交
111 112 113 114 115 116 117 118 119
        Args:
            None

        Returns:
            None

        Return types:
            None

D
dzhwinter 已提交
120 121 122
        """
        states = {
            attr: value
123 124
            for attr, value in self.__dict__.items()
            if not attr.startswith("_")
D
dzhwinter 已提交
125
        }
126
        for attr, value in states.items():
D
dzhwinter 已提交
127 128 129
            if isinstance(value, int):
                setattr(self, attr, 0)
            elif isinstance(value, float):
130
                setattr(self, attr, 0.0)
D
dzhwinter 已提交
131 132 133 134 135 136
            elif isinstance(value, (np.ndarray, np.generic)):
                setattr(self, attr, np.zeros_like(value))
            else:
                setattr(self, attr, None)

    def get_config(self):
137 138 139 140 141 142 143 144
        """
        Get the metric and current states.
        The states are the members who do not has "_" prefix.

        Args:
            None

        Returns:
T
tianshuo78520a 已提交
145
            a python dict, which contains the inner states of the metric instance
P
pkpk 已提交
146 147 148

        Return types:
            a python dict
149
        """
D
dzhwinter 已提交
150 151
        states = {
            attr: value
152 153
            for attr, value in self.__dict__.items()
            if not attr.startswith("_")
D
dzhwinter 已提交
154
        }
155
        config = {}
D
dzhwinter 已提交
156 157 158
        config.update({"name": self._name, "states": copy.deepcopy(states)})
        return config

159 160
    def update(self, preds, labels):
        """
P
pkpk 已提交
161
        Given the prediction results (preds) and the labels (labels)
162
        of some mini-batch, compute the evaluation result of that mini-batch,
P
pkpk 已提交
163
        and memorize the evaluation result. Please notice that the update function only
164
        memorizes the evaluation result but would not return the score. If you want to
P
pkpk 已提交
165
        get the evaluation result, please call eval() function.
166 167 168

        Args:
            preds(numpy.array): the predictions of current minibatch
P
pkpk 已提交
169 170 171 172 173 174
            labels(numpy.array): the labels of current minibatch.

        Returns:
            None

        Return types:
175
            None
P
pkpk 已提交
176

177 178
        """
        raise NotImplementedError(
179 180
            "Should not use it directly, please extend it."
        )
D
dzhwinter 已提交
181 182

    def eval(self):
183
        """
P
pkpk 已提交
184 185 186 187 188
        Aggregate all existing evaluation results in the memory, and return the overall
        performance across different mini-batches.

        Args:
            None
189 190

        Returns:
P
pkpk 已提交
191 192 193
            The overall performance across different mini-batches.

        Return types:
194 195 196
            float|list(float)|numpy.array: the metrics via Python.
        """
        raise NotImplementedError(
197 198
            "Should not use it directly, please extend it."
        )
D
dzhwinter 已提交
199 200 201 202


class CompositeMetric(MetricBase):
    """
203
    This op creates a container that contains the union of all the added metrics.
P
pkpk 已提交
204 205 206
    After the metrics added in, calling eval() method will compute all the contained metrics automatically.
    CAUTION: only metrics with the SAME argument list can be added in a CompositeMetric instance.

207
    Inherit from: `MetricBase <https://www.paddlepaddle.org.cn/documentation/docs/zh/1.5/api_cn/metrics_cn.html#paddle.fluid.metrics.MetricBase>`_
P
pkpk 已提交
208 209 210

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
211

212 213
    Examples:
        .. code-block:: python
214
            import paddle.fluid as fluid
P
pkpk 已提交
215 216 217 218 219 220 221 222 223 224 225 226
            import numpy as np
            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]
            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]
            preds = np.array(preds)
            labels = np.array(labels)
            comp = fluid.metrics.CompositeMetric()
            precision = fluid.metrics.Precision()
            recall = fluid.metrics.Recall()
            comp.add_metric(precision)
            comp.add_metric(recall)
227
            comp.update(preds=preds, labels=labels)
P
pkpk 已提交
228 229 230
            numpy_precision, numpy_recall = comp.eval()
            print("expect precision: %.2f, got %.2f" % ( 3. / 5, numpy_precision ) )
            print("expect recall: %.2f, got %.2f" % (3. / 4, numpy_recall ) )
D
dzhwinter 已提交
231 232
    """

233
    def __init__(self, name=None):
234
        super().__init__(name)
D
dzhwinter 已提交
235 236
        self._metrics = []

Q
qiaolongfei 已提交
237
    def add_metric(self, metric):
238
        """
239 240
        Add a new metric to container. Noted that the argument list
        of the added one should be consistent with existed ones.
241 242

        Args:
P
pkpk 已提交
243
            metric(MetricBase): a instance of MetricBase
244
        """
D
dzhwinter 已提交
245 246 247 248
        if not isinstance(metric, MetricBase):
            raise ValueError("SubMetric should be inherit from MetricBase.")
        self._metrics.append(metric)

249 250
    def update(self, preds, labels):
        """
P
pkpk 已提交
251
        Update the metrics of this container.
252 253

        Args:
P
pkpk 已提交
254
            preds(numpy.array): predicted results of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric.
255
            labels(numpy.array): ground truth of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric.
256 257
        """
        for m in self._metrics:
D
dzhwinter 已提交
258
            m.update(preds, labels)
259

D
dzhwinter 已提交
260
    def eval(self):
261
        """
P
pkpk 已提交
262
        Calculate the results of all metrics sequentially.
263 264

        Returns:
265
            list: results of all added metrics.
T
tianshuo78520a 已提交
266
            The shape and dtype of each result depend on the definition of its metric.
267
        """
D
dzhwinter 已提交
268 269 270 271 272 273
        ans = []
        for m in self._metrics:
            ans.append(m.eval())
        return ans


274 275 276
class Precision(MetricBase):
    """
    Precision (also called positive predictive value) is the fraction of
P
pkpk 已提交
277
    relevant instances among the retrieved instances. Refer to
278 279
    https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers

T
tianshuo78520a 已提交
280
    Noted that this class manages the precision score only for binary classification task.
P
pkpk 已提交
281 282 283

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
284 285 286 287

    Examples:
        .. code-block:: python

288
            import paddle.fluid as fluid
P
pkpk 已提交
289 290
            import numpy as np

T
Tink_Y 已提交
291
            metric = fluid.metrics.Precision()
P
pkpk 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

            # generate the preds and labels

            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]

            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]

            preds = np.array(preds)
            labels = np.array(labels)

            metric.update(preds=preds, labels=labels)
            numpy_precision = metric.eval()

P
pkpk 已提交
307
            print("expect precision: %.2f and got %.2f" % ( 3.0 / 5.0, numpy_precision))
308 309 310
    """

    def __init__(self, name=None):
311
        super().__init__(name)
312 313 314 315
        self.tp = 0  # true positive
        self.fp = 0  # false positive

    def update(self, preds, labels):
P
pkpk 已提交
316 317 318 319
        """
        Update the precision based on the current mini-batch prediction results .

        Args:
320 321
            preds(numpy.ndarray): prediction results of current mini-batch,
                                the output of two-class sigmoid function.
P
pkpk 已提交
322
                                Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'.
323 324
            labels(numpy.ndarray): ground truth (labels) of current mini-batch,
                                 the shape should keep the same as preds.
P
pkpk 已提交
325 326
                                 Shape: [batch_size, 1], Dtype: 'int32' or 'int64'.
        """
327 328 329 330
        if not _is_numpy_(preds):
            raise ValueError("The 'preds' must be a numpy ndarray.")
        if not _is_numpy_(labels):
            raise ValueError("The 'labels' must be a numpy ndarray.")
331 332
        sample_num = labels.shape[0]
        preds = np.rint(preds).astype("int32")
G
Genieliu 已提交
333

334
        for i in range(sample_num):
335
            pred = preds[i]
336
            label = labels[i]
P
pkpk 已提交
337
            if pred == 1:
338 339 340 341 342 343
                if pred == label:
                    self.tp += 1
                else:
                    self.fp += 1

    def eval(self):
P
pkpk 已提交
344 345 346 347 348 349
        """
        Calculate the final precision.

        Returns:
            float: Results of the calculated Precision. Scalar output with float dtype.
        """
350
        ap = self.tp + self.fp
351
        return float(self.tp) / ap if ap != 0 else 0.0
352 353 354 355 356 357 358 359


class Recall(MetricBase):
    """
    Recall (also known as sensitivity) is the fraction of
    relevant instances that have been retrieved over the
    total amount of relevant instances

P
pkpk 已提交
360
    Refer to:
361 362
    https://en.wikipedia.org/wiki/Precision_and_recall

T
tianshuo78520a 已提交
363
    Noted that this class manages the recall score only for binary classification task.
P
pkpk 已提交
364 365 366

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
P
pkpk 已提交
367

368 369 370
    Examples:
        .. code-block:: python

371
            import paddle.fluid as fluid
P
pkpk 已提交
372 373
            import numpy as np

T
Tink_Y 已提交
374
            metric = fluid.metrics.Recall()
P
pkpk 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387

            # generate the preds and labels

            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]

            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]

            preds = np.array(preds)
            labels = np.array(labels)

            metric.update(preds=preds, labels=labels)
P
pkpk 已提交
388
            numpy_recall = metric.eval()
P
pkpk 已提交
389

P
pkpk 已提交
390
            print("expect recall: %.2f and got %.2f" % ( 3.0 / 4.0, numpy_recall))
391 392 393
    """

    def __init__(self, name=None):
394
        super().__init__(name)
395
        self.tp = 0  # true positive
T
tianshuo78520a 已提交
396
        self.fn = 0  # false negative
397 398

    def update(self, preds, labels):
P
pkpk 已提交
399 400 401 402
        """
        Update the recall based on the current mini-batch prediction results.

        Args:
403 404
            preds(numpy.array): prediction results of current mini-batch,
                              the output of two-class sigmoid function.
P
pkpk 已提交
405
                              Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'.
406 407
            labels(numpy.array): ground truth (labels) of current mini-batch,
                               the shape should keep the same as preds.
P
pkpk 已提交
408 409
                               Shape: [batch_size, 1], Dtype: 'int32' or 'int64'.
        """
410 411 412 413
        if not _is_numpy_(preds):
            raise ValueError("The 'preds' must be a numpy ndarray.")
        if not _is_numpy_(labels):
            raise ValueError("The 'labels' must be a numpy ndarray.")
P
pkpk 已提交
414 415 416
        sample_num = labels.shape[0]
        preds = np.rint(preds).astype("int32")

417
        for i in range(sample_num):
P
pkpk 已提交
418
            pred = preds[i]
419 420 421 422
            label = labels[i]
            if label == 1:
                if pred == label:
                    self.tp += 1
P
pkpk 已提交
423
                else:
424 425 426
                    self.fn += 1

    def eval(self):
P
pkpk 已提交
427 428 429 430 431 432
        """
        Calculate the final recall.

        Returns:
            float: results of the calculated Recall. Scalar output with float dtype.
        """
433
        recall = self.tp + self.fn
434
        return float(self.tp) / recall if recall != 0 else 0.0
435 436


D
dzhwinter 已提交
437 438
class Accuracy(MetricBase):
    """
P
pkpk 已提交
439
    This interface is used to calculate the mean accuracy over multiple batches.
440
    Accuracy object has two state: value and weight. The definition of Accuracy is available at
441
    https://en.wikipedia.org/wiki/Accuracy_and_precision
D
dzhwinter 已提交
442 443

    Args:
P
pkpk 已提交
444
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
D
dzhwinter 已提交
445

446 447 448
    Examples:
        .. code-block:: python

449
            import paddle.fluid as fluid
P
pkpk 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
            #suppose we have batch_size = 128
            batch_size=128
            accuracy_manager = fluid.metrics.Accuracy()

            #suppose the accuracy is 0.9 for the 1st batch
            batch1_acc = 0.9
            accuracy_manager.update(value = batch1_acc, weight = batch_size)
            print("expect accuracy: %.2f, get accuracy: %.2f" % (batch1_acc, accuracy_manager.eval()))

            #suppose the accuracy is 0.8 for the 2nd batch
            batch2_acc = 0.8

            accuracy_manager.update(value = batch2_acc, weight = batch_size)
            #the joint acc for batch1 and batch2 is (batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2
            print("expect accuracy: %.2f, get accuracy: %.2f" % ((batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2, accuracy_manager.eval()))

            #reset the accuracy_manager
            accuracy_manager.reset()
            #suppose the accuracy is 0.8 for the 3rd batch
            batch3_acc = 0.8
            accuracy_manager.update(value = batch3_acc, weight = batch_size)
            print("expect accuracy: %.2f, get accuracy: %.2f" % (batch3_acc, accuracy_manager.eval()))
D
dzhwinter 已提交
472 473 474
    """

    def __init__(self, name=None):
475
        super().__init__(name)
476 477
        self.value = 0.0
        self.weight = 0.0
D
dzhwinter 已提交
478 479

    def update(self, value, weight):
480
        r"""
P
pkpk 已提交
481 482 483 484 485
        This function takes the minibatch states (value, weight) as input,
        to accumulate and update the corresponding status of the Accuracy object. The update method is as follows:

        .. math::
            \\\\ \\begin{array}{l}{\\text { self. value }+=\\text { value } * \\text { weight }} \\\\ {\\text { self. weight }+=\\text { weight }}\\end{array} \\\\
486 487 488

        Args:
            value(float|numpy.array): accuracy of one minibatch.
P
pkpk 已提交
489
            weight(int|float): minibatch size.
490
        """
D
dzhwinter 已提交
491 492
        if not _is_number_or_matrix_(value):
            raise ValueError(
493 494
                "The 'value' must be a number(int, float) or a numpy ndarray."
            )
D
dzhwinter 已提交
495 496
        if not _is_number_(weight):
            raise ValueError("The 'weight' must be a number(int, float).")
P
pkpk 已提交
497 498
        if _is_number_(weight) and weight < 0:
            raise ValueError("The 'weight' can not be negative")
D
dzhwinter 已提交
499 500 501 502
        self.value += value * weight
        self.weight += weight

    def eval(self):
P
pkpk 已提交
503
        """
P
pkpk 已提交
504 505
        This function returns the mean accuracy (float or numpy.array) for all accumulated minibatches.

506
        Returns:
P
pkpk 已提交
507 508
            float or numpy.array: mean accuracy for all accumulated minibatches.

P
pkpk 已提交
509
        """
D
dzhwinter 已提交
510
        if self.weight == 0:
511 512 513 514
            raise ValueError(
                "There is no data in Accuracy Metrics. \
                Please check layers.accuracy output has added to Accuracy."
            )
D
dzhwinter 已提交
515 516 517
        return self.value / self.weight


518
class ChunkEvaluator(MetricBase):
D
dzhwinter 已提交
519 520 521 522
    """
    Accumulate counter numbers output by chunk_eval from mini-batches and
    compute the precision recall and F1-score using the accumulated counter
    numbers.
523
    ChunkEvaluator has three states: num_infer_chunks, num_label_chunks and num_correct_chunks,
P
pkpk 已提交
524
    which correspond to the number of chunks, the number of labeled chunks, and the number of correctly identified chunks.
525
    For some basics of chunking, please refer to
P
pkpk 已提交
526
    `Chunking with Support Vector Machines <https://www.aclweb.org/anthology/N01-1025>`_ .
527 528 529
    ChunkEvalEvaluator computes the precision, recall, and F1-score of chunk detection,
    and supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes.

P
pkpk 已提交
530 531 532
    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

533 534 535
    Examples:
        .. code-block:: python

536
            import paddle.fluid as fluid
T
tianshuo78520a 已提交
537
            # init the chunk-level evaluation manager
538
            metric = fluid.metrics.ChunkEvaluator()
P
pkpk 已提交
539

T
tianshuo78520a 已提交
540
            # suppose the model predict 10 chucks, while 8 ones are correct and the ground truth has 9 chucks.
P
pkpk 已提交
541
            num_infer_chunks = 10
542
            num_label_chunks = 9
P
pkpk 已提交
543 544 545 546 547 548 549
            num_correct_chunks = 8

            metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks)
            numpy_precision, numpy_recall, numpy_f1 = metric.eval()

            print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1))

T
tianshuo78520a 已提交
550
            # the next batch, predicting 3 perfectly correct chucks.
P
pkpk 已提交
551 552 553 554 555 556 557 558 559
            num_infer_chunks = 3
            num_label_chunks = 3
            num_correct_chunks = 3

            metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks)
            numpy_precision, numpy_recall, numpy_f1 = metric.eval()

            print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1))

D
dzhwinter 已提交
560 561 562
    """

    def __init__(self, name=None):
563
        super().__init__(name)
D
dzhwinter 已提交
564 565 566 567 568
        self.num_infer_chunks = 0
        self.num_label_chunks = 0
        self.num_correct_chunks = 0

    def update(self, num_infer_chunks, num_label_chunks, num_correct_chunks):
569
        r"""
P
pkpk 已提交
570 571
        This function takes (num_infer_chunks, num_label_chunks, num_correct_chunks) as input,
        to accumulate and update the corresponding status of the ChunkEvaluator object. The update method is as follows:
572 573

        .. math::
P
pkpk 已提交
574
                   \\\\ \\begin{array}{l}{\\text { self. num_infer_chunks }+=\\text { num_infer_chunks }} \\\\ {\\text { self. num_Label_chunks }+=\\text { num_label_chunks }} \\\\ {\\text { self. num_correct_chunks }+=\\text { num_correct_chunks }}\\end{array} \\\\
H
haowang101779990 已提交
575

576 577 578 579 580 581
        Args:
            num_infer_chunks(int|numpy.array): The number of chunks in Inference on the given minibatch.
            num_label_chunks(int|numpy.array): The number of chunks in Label on the given mini-batch.
            num_correct_chunks(int|float|numpy.array): The number of chunks both in Inference and Label on the
                                                  given mini-batch.
        """
D
dzhwinter 已提交
582 583
        if not _is_number_or_matrix_(num_infer_chunks):
            raise ValueError(
584
                "The 'num_infer_chunks' must be a number(int) or a numpy ndarray."
D
dzhwinter 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598
            )
        if not _is_number_or_matrix_(num_label_chunks):
            raise ValueError(
                "The 'num_label_chunks' must be a number(int, float) or a numpy ndarray."
            )
        if not _is_number_or_matrix_(num_correct_chunks):
            raise ValueError(
                "The 'num_correct_chunks' must be a number(int, float) or a numpy ndarray."
            )
        self.num_infer_chunks += num_infer_chunks
        self.num_label_chunks += num_label_chunks
        self.num_correct_chunks += num_correct_chunks

    def eval(self):
P
pkpk 已提交
599 600 601
        """
        This function returns the mean precision, recall and f1 score for all accumulated minibatches.

602
        Returns:
P
pkpk 已提交
603 604 605
            float: mean precision, recall and f1 score.

        """
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
        precision = (
            float(self.num_correct_chunks) / self.num_infer_chunks
            if self.num_infer_chunks
            else 0
        )
        recall = (
            float(self.num_correct_chunks) / self.num_label_chunks
            if self.num_label_chunks
            else 0
        )
        f1_score = (
            float(2 * precision * recall) / (precision + recall)
            if self.num_correct_chunks
            else 0
        )
D
dzhwinter 已提交
621 622 623 624 625
        return precision, recall, f1_score


class EditDistance(MetricBase):
    """
P
pkpk 已提交
626
    This API is for the management of edit distances.
627 628 629
    Editing distance is a method to quantify the degree of dissimilarity
    between two strings, such as words, by calculating the minimum editing
    operand (add, delete or replace) required to convert one string into another.
P
pkpk 已提交
630
    Refer to https://en.wikipedia.org/wiki/Edit_distance.
D
dzhwinter 已提交
631 632

    Args:
P
pkpk 已提交
633
        name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
D
dzhwinter 已提交
634

635 636 637
    Examples:
        .. code-block:: python

638
            import paddle.fluid as fluid
P
pkpk 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
            import numpy as np

            # suppose that batch_size is 128
            batch_size = 128

            # init the edit distance manager
            distance_evaluator = fluid.metrics.EditDistance("EditDistance")

            # generate the edit distance across 128 sequence pairs, the max distance is 10 here
            edit_distances_batch0 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch0 = batch_size

            distance_evaluator.update(edit_distances_batch0, seq_num_batch0)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch0 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))
D
dzhwinter 已提交
654

P
pkpk 已提交
655 656
            edit_distances_batch1 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch1 = batch_size
T
Tink_Y 已提交
657

P
pkpk 已提交
658 659 660 661 662 663 664 665 666 667 668 669
            distance_evaluator.update(edit_distances_batch1, seq_num_batch1)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch0 and batch1 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))

            distance_evaluator.reset()

            edit_distances_batch2 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch2 = batch_size

            distance_evaluator.update(edit_distances_batch2, seq_num_batch2)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch2 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))
D
dzhwinter 已提交
670 671 672 673

    """

    def __init__(self, name):
674
        super().__init__(name)
675
        self.total_distance = 0.0
D
dzhwinter 已提交
676 677 678 679
        self.seq_num = 0
        self.instance_error = 0

    def update(self, distances, seq_num):
P
pkpk 已提交
680 681 682 683
        """
        Update the overall edit distance

        Args:
P
pkpk 已提交
684 685
            distances(numpy.array): a (batch_size, 1) numpy.array, each element represents the edit distance between two sequences.
            seq_num(int|float): standing for the number of sequence pairs.
P
pkpk 已提交
686
        """
D
dzhwinter 已提交
687 688 689 690 691 692 693 694 695 696
        if not _is_numpy_(distances):
            raise ValueError("The 'distances' must be a numpy ndarray.")
        if not _is_number_(seq_num):
            raise ValueError("The 'seq_num' must be a number(int, float).")
        seq_right_count = np.sum(distances == 0)
        total_distance = np.sum(distances)
        self.seq_num += seq_num
        self.instance_error += seq_num - seq_right_count
        self.total_distance += total_distance

Q
qiaolongfei 已提交
697
    def eval(self):
P
pkpk 已提交
698 699 700 701 702
        """
        Return two floats:
        avg_distance: the average distance for all sequence pairs updated using the update function.
        avg_instance_error: the ratio of sequence pairs whose edit distance is not zero.
        """
D
dzhwinter 已提交
703 704 705 706 707
        if self.seq_num == 0:
            raise ValueError(
                "There is no data in EditDistance Metric. Please check layers.edit_distance output has been added to EditDistance."
            )
        avg_distance = self.total_distance / self.seq_num
S
sneaxiy 已提交
708
        avg_instance_error = self.instance_error / float(self.seq_num)
D
dzhwinter 已提交
709 710 711 712 713
        return avg_distance, avg_instance_error


class Auc(MetricBase):
    """
P
pkpk 已提交
714
    The auc metric is for binary classification.
P
pkpk 已提交
715
    Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve.
P
pkpk 已提交
716
    Please notice that the auc metric is implemented with python, which may be a little bit slow.
D
dzhwinter 已提交
717 718 719
    If you concern the speed, please use the fluid.layers.auc instead.

    The `auc` function creates four local variables, `true_positives`,
720 721 722 723 724 725
    `true_negatives`, `false_positives` and `false_negatives` that are used to
    compute the AUC. To discretize the AUC curve, a linearly spaced set of
    thresholds is used to compute pairs of recall and precision values. The area
    under the ROC-curve is therefore computed using the height of the recall
    values by the false positive rate, while the area under the PR-curve is the
    computed using the height of the precision values by the recall.
D
dzhwinter 已提交
726 727

    Args:
P
pkpk 已提交
728 729
        name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
        curve (str): Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve.
D
dzhwinter 已提交
730 731

    "NOTE: only implement the ROC curve type via Python now."
732 733 734 735

    Examples:
        .. code-block:: python

736
            import paddle.fluid as fluid
P
pkpk 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
            import numpy as np
            # init the auc metric
            auc_metric = fluid.metrics.Auc("ROC")

            # suppose that batch_size is 128
            batch_num = 100
            batch_size = 128

            for batch_id in range(batch_num):

                class0_preds = np.random.random(size = (batch_size, 1))
                class1_preds = 1 - class0_preds

                preds = np.concatenate((class0_preds, class1_preds), axis=1)

                labels = np.random.randint(2, size = (batch_size, 1))
                auc_metric.update(preds = preds, labels = labels)

                # shall be some score closing to 0.5 as the preds are randomly assigned
                print("auc for iteration %d is %.2f" % (batch_id, auc_metric.eval()))
D
dzhwinter 已提交
757 758
    """

T
tangwei12 已提交
759
    def __init__(self, name, curve='ROC', num_thresholds=4095):
760
        super().__init__(name=name)
D
dzhwinter 已提交
761 762
        self._curve = curve
        self._num_thresholds = num_thresholds
T
tangwei12 已提交
763 764 765 766

        _num_pred_buckets = num_thresholds + 1
        self._stat_pos = [0] * _num_pred_buckets
        self._stat_neg = [0] * _num_pred_buckets
D
dzhwinter 已提交
767

Q
qiaolongfei 已提交
768
    def update(self, preds, labels):
P
pkpk 已提交
769
        """
P
pkpk 已提交
770
        Update the auc curve with the given predictions and labels.
P
pkpk 已提交
771 772

        Args:
P
pkpk 已提交
773 774
             preds (numpy.array): an numpy array in the shape of (batch_size, 2), preds[i][j] denotes the probability of classifying the instance i into the class j.
             labels (numpy.array): an numpy array in the shape of (batch_size, 1), labels[i] is either o or 1, representing the label of the instance i.
P
pkpk 已提交
775
        """
D
dzhwinter 已提交
776 777
        if not _is_numpy_(labels):
            raise ValueError("The 'labels' must be a numpy ndarray.")
Q
qiaolongfei 已提交
778
        if not _is_numpy_(preds):
D
dzhwinter 已提交
779 780
            raise ValueError("The 'predictions' must be a numpy ndarray.")

T
tangwei12 已提交
781 782 783 784 785 786 787 788 789 790 791 792
        for i, lbl in enumerate(labels):
            value = preds[i, 1]
            bin_idx = int(value * self._num_thresholds)
            assert bin_idx <= self._num_thresholds
            if lbl:
                self._stat_pos[bin_idx] += 1.0
            else:
                self._stat_neg[bin_idx] += 1.0

    @staticmethod
    def trapezoid_area(x1, x2, y1, y2):
        return abs(x1 - x2) * (y1 + y2) / 2.0
D
dzhwinter 已提交
793 794

    def eval(self):
P
pkpk 已提交
795 796
        """
        Return the area (a float score) under auc curve
P
pkpk 已提交
797 798 799

        Return:
            float: the area under auc curve
P
pkpk 已提交
800
        """
T
tangwei12 已提交
801 802 803 804 805 806 807 808 809 810
        tot_pos = 0.0
        tot_neg = 0.0
        auc = 0.0

        idx = self._num_thresholds
        while idx >= 0:
            tot_pos_prev = tot_pos
            tot_neg_prev = tot_neg
            tot_pos += self._stat_pos[idx]
            tot_neg += self._stat_neg[idx]
811 812 813
            auc += self.trapezoid_area(
                tot_neg, tot_neg_prev, tot_pos, tot_pos_prev
            )
T
tangwei12 已提交
814 815
            idx -= 1

816 817 818
        return (
            auc / tot_pos / tot_neg if tot_pos > 0.0 and tot_neg > 0.0 else 0.0
        )
819 820


821
class DetectionMAP:
822 823 824 825
    """
    Calculate the detection mean average precision (mAP).

    The general steps are as follows:
H
haowang101779990 已提交
826

827
    1. calculate the true positive and false positive according to the input
H
haowang101779990 已提交
828
       of detection and labels.
829
    2. calculate mAP value, support two versions: '11 point' and 'integral'.
830 831
       11point: the 11-point interpolated average precision.
       integral: the natural integral of the precision-recall curve.
832 833

    Please get more information from the following articles:
H
haowang101779990 已提交
834

835
      https://sanchom.wordpress.com/tag/average-precision/
H
haowang101779990 已提交
836

837 838 839
      https://arxiv.org/abs/1512.02325

    Args:
840
        input (Variable): LoDTensor, The detection results, which is a LoDTensor with shape
841
            [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax].
842 843 844 845
            The data type is float32 or float64.
        gt_label (Variable): LoDTensor, The ground truth label index, which is a LoDTensor
            with shape [N, 1].The data type is float32 or float64.
        gt_box (Variable): LoDTensor, The ground truth bounding box (bbox), which is a
846
            LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax].
847 848
            The data type is float32 or float64.
        gt_difficult (Variable|None): LoDTensor, Whether this ground truth is a difficult
849
            bounding bbox, which can be a LoDTensor [N, 1] or not set. If None,
850 851
            it means all the ground truth labels are not difficult bbox.The
            data type is int.
852 853 854
        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
翟飞跃 已提交
855
            considered, 0 by default.
856
        overlap_threshold (float): The threshold for deciding true/false
翟飞跃 已提交
857
            positive, 0.5 by default.
858
        evaluate_difficult (bool): Whether to consider difficult ground truth
翟飞跃 已提交
859
            for evaluation, True by default. This argument does not work when
860
            gt_difficult is None.
861
        ap_version (str): The average precision calculation ways, it must be
862 863 864 865 866 867
            'integral' or '11point'. Please check
            https://sanchom.wordpress.com/tag/average-precision/ for details.

    Examples:
        .. code-block:: python

868
            import paddle.fluid as fluid
869

870 871 872
            import paddle
            paddle.enable_static()

873
            batch_size = None # can be any size
P
pkpk 已提交
874 875 876
            image_boxs_num = 10
            bounding_bboxes_num = 21

877 878
            pb = fluid.data(name='prior_box', shape=[image_boxs_num, 4],
                       dtype='float32')
P
pkpk 已提交
879

880 881
            pbv = fluid.data(name='prior_box_var', shape=[image_boxs_num, 4],
                         dtype='float32')
P
pkpk 已提交
882

883 884
            loc = fluid.data(name='target_box', shape=[batch_size, bounding_bboxes_num, 4],
                        dtype='float32')
P
pkpk 已提交
885

886 887
            scores = fluid.data(name='scores', shape=[batch_size, bounding_bboxes_num, image_boxs_num],
                            dtype='float32')
P
pkpk 已提交
888 889 890 891

            nmsed_outs = fluid.layers.detection_output(scores=scores,
                loc=loc, prior_box=pb, prior_box_var=pbv)

892 893 894
            gt_box = fluid.data(name="gt_box", shape=[batch_size, 4], dtype="float32")
            gt_label = fluid.data(name="gt_label", shape=[batch_size, 1], dtype="float32")
            difficult = fluid.data(name="difficult", shape=[batch_size, 1], dtype="float32")
P
pkpk 已提交
895 896 897 898 899

            exe = fluid.Executor(fluid.CUDAPlace(0))
            map_evaluator = fluid.metrics.DetectionMAP(nmsed_outs, gt_label, gt_box, difficult, class_num = 3)

            cur_map, accum_map = map_evaluator.get_map_var()
H
haowang101779990 已提交
900

901

902 903
    """

904 905 906 907 908 909 910 911 912 913 914 915
    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',
    ):
916 917 918 919 920 921 922 923 924 925

        self.helper = LayerHelper('map_eval')
        gt_label = layers.cast(x=gt_label, dtype=gt_box.dtype)
        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)

        # calculate mean average precision (mAP) of current mini-batch
926 927 928 929 930 931 932 933 934
        map = detection.detection_map(
            input,
            label,
            class_num,
            background_label,
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            ap_version=ap_version,
        )
935 936 937

        states = []
        states.append(
938 939 940 941
            self._create_state(
                dtype='int32', shape=None, suffix='accum_pos_count'
            )
        )
942
        states.append(
943 944 945 946
            self._create_state(
                dtype='float32', shape=None, suffix='accum_true_pos'
            )
        )
947
        states.append(
948 949 950 951
            self._create_state(
                dtype='float32', shape=None, suffix='accum_false_pos'
            )
        )
952
        var = self._create_state(dtype='int32', shape=[1], suffix='has_state')
953 954 955
        self.helper.set_variable_initializer(
            var, initializer=Constant(value=int(0))
        )
956 957 958
        self.has_state = var

        # calculate accumulative mAP
959
        accum_map = detection.detection_map(
960 961 962 963 964 965 966 967 968
            input,
            label,
            class_num,
            background_label,
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            has_state=self.has_state,
            input_states=states,
            out_states=states,
969 970
            ap_version=ap_version,
        )
971

972 973 974 975 976 977
        layers.fill_constant(
            shape=self.has_state.shape,
            value=1,
            dtype=self.has_state.dtype,
            out=self.has_state,
        )
978 979 980 981 982 983 984 985 986 987 988 989 990

        self.cur_map = map
        self.accum_map = accum_map

    def _create_state(self, suffix, dtype, shape):
        """
        Create state variable.
        Args:
            suffix(str): the state suffix.
            dtype(str|core.VarDesc.VarType): the state data type
            shape(tuple|list): the shape of state
        Returns: State variable
        """
991 992 993 994 995 996
        state = self.helper.create_variable(
            name="_".join([unique_name.generate(self.helper.name), suffix]),
            persistable=True,
            dtype=dtype,
            shape=shape,
        )
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
        return state

    def get_map_var(self):
        """
        Returns: mAP variable of current mini-batch and
            accumulative mAP variable cross mini-batches.
        """
        return self.cur_map, self.accum_map

    def reset(self, executor, reset_program=None):
        """
D
Dang Qingqing 已提交
1008
        Reset metric states at the begin of each pass/user specified batch.
1009
        Args:
D
Dang Qingqing 已提交
1010
            executor(Executor): a executor for executing
1011 1012 1013 1014 1015 1016 1017
                the reset_program.
            reset_program(Program|None): a single Program for reset process.
                If None, will create a Program.
        """

        def _clone_var_(block, var):
            assert isinstance(var, Variable)
1018 1019 1020 1021 1022 1023 1024 1025
            return block.create_var(
                name=var.name,
                shape=var.shape,
                dtype=var.dtype,
                type=var.type,
                lod_level=var.lod_level,
                persistable=var.persistable,
            )
1026 1027 1028 1029 1030

        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)
1031 1032 1033
            layers.fill_constant(
                shape=var.shape, value=0, dtype=var.dtype, out=var
            )
1034
        executor.run(reset_program)