metrics.py 31.7 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 18 19

from __future__ import print_function

D
dzhwinter 已提交
20 21 22
import numpy as np
import copy
import warnings
23
import six
D
dzhwinter 已提交
24

D
Dang Qingqing 已提交
25 26 27 28 29 30
from .layer_helper import LayerHelper
from .initializer import Constant
from . import unique_name
from .framework import Program, Variable, program_guard
from . import layers

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


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


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


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


class MetricBase(object):
    """
59 60 61 62 63 64 65 66 67
    Base Class for all Metrics.
    MetricBase define a group of interfaces for the
    model evaluation methods. Metrics accumulate metric states between
    consecutive minibatches, at every minibatch, use update
    interface to add current minibatch value to global states.
    Use eval to compute accumative metric value from last reset()
    or from scratch on.
    If you need to custom a new metric, please inherit from MetricBase and
    custom implementation.
D
dzhwinter 已提交
68 69

    Args:
70 71 72
        name(str): The name of metric instance. such as, "accuracy".
                  It needed if you want to distinct different metrics in a model.

D
dzhwinter 已提交
73 74
    """

75
    def __init__(self, name):
D
dzhwinter 已提交
76 77 78 79 80 81 82
        self._name = str(name) if name != None else self.__class__.__name__

    def __str__(self):
        return self._name

    def reset(self):
        """
83 84 85 86
        reset clear the states of metrics. By default, the states
        are the members who do not has _ prefix, reset set them to inital states.
        If you violate the implicit name rule, please also custom the reset
        interface.
D
dzhwinter 已提交
87 88 89
        """
        states = {
            attr: value
M
minqiyang 已提交
90
            for attr, value in six.iteritems(self.__dict__)
D
dzhwinter 已提交
91 92
            if not attr.startswith("_")
        }
M
minqiyang 已提交
93
        for attr, value in six.iteritems(states):
D
dzhwinter 已提交
94 95 96 97 98 99 100 101 102 103
            if isinstance(value, int):
                setattr(self, attr, 0)
            elif isinstance(value, float):
                setattr(self, attr, .0)
            elif isinstance(value, (np.ndarray, np.generic)):
                setattr(self, attr, np.zeros_like(value))
            else:
                setattr(self, attr, None)

    def get_config(self):
104 105 106 107 108 109 110 111 112 113
        """
        Get the metric and current states.
        The states are the members who do not has "_" prefix.

        Args:
            None

        Returns:
            dict: a dict of metric and states
        """
D
dzhwinter 已提交
114 115
        states = {
            attr: value
M
minqiyang 已提交
116
            for attr, value in six.iteritems(self.__dict__)
D
dzhwinter 已提交
117 118
            if not attr.startswith("_")
        }
119
        config = {}
D
dzhwinter 已提交
120 121 122
        config.update({"name": self._name, "states": copy.deepcopy(states)})
        return config

123 124 125 126 127 128 129 130 131 132 133 134 135
    def update(self, preds, labels):
        """
        Updates the metric states at every minibatch.
        One user can compute the minibatch metric via pure Python, or
        via a c++ operator.

        Args:
            preds(numpy.array): the predictions of current minibatch
            labels(numpy.array): the labels of current minibatch, if the label is one-hot
                               or soft-label, should custom the corresponding update rule.
        """
        raise NotImplementedError(
            "Should not use it directly, please extend it.")
D
dzhwinter 已提交
136 137

    def eval(self):
138 139 140 141 142 143 144 145
        """
        Evalute the current metrics based the accumulated states.

        Returns:
            float|list(float)|numpy.array: the metrics via Python.
        """
        raise NotImplementedError(
            "Should not use it directly, please extend it.")
D
dzhwinter 已提交
146 147 148 149


class CompositeMetric(MetricBase):
    """
150
    Composite multiple metrics in one instance.
D
dzhwinter 已提交
151
    for example, merge F1, accuracy, recall into one Metric.
152

153 154
    Examples:
        .. code-block:: python
155

156
            import paddle.fluid as fluid
P
pkpk 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170
            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)

171
            comp.update(preds=preds, labels=labels)
P
pkpk 已提交
172 173 174 175
            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 已提交
176 177
    """

178 179
    def __init__(self, name=None):
        super(CompositeMetric, self).__init__(name)
D
dzhwinter 已提交
180 181
        self._metrics = []

Q
qiaolongfei 已提交
182
    def add_metric(self, metric):
183 184 185 186 187 188
        """
        add one metric instance to CompositeMetric.

        Args:
            metric: a instance of MetricBase.
        """
D
dzhwinter 已提交
189 190 191 192
        if not isinstance(metric, MetricBase):
            raise ValueError("SubMetric should be inherit from MetricBase.")
        self._metrics.append(metric)

193 194 195 196 197 198 199 200 201 202
    def update(self, preds, labels):
        """
        Update every metrics in sequence.

        Args:
            preds(numpy.array): the predictions of current minibatch
            labels(numpy.array): the labels of current minibatch, if the label is one-hot
                               or soft-label, should custom the corresponding update rule.
        """
        for m in self._metrics:
D
dzhwinter 已提交
203
            m.update(preds, labels)
204

D
dzhwinter 已提交
205
    def eval(self):
206 207 208 209 210 211
        """
        Evaluate every metrics in sequence.

        Returns:
            list(float|numpy.array): a list of metrics value in Python.
        """
D
dzhwinter 已提交
212 213 214 215 216 217
        ans = []
        for m in self._metrics:
            ans.append(m.eval())
        return ans


218 219 220 221 222 223
class Precision(MetricBase):
    """
    Precision (also called positive predictive value) is the fraction of
    relevant instances among the retrieved instances.
    https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers

P
pkpk 已提交
224
    This class mangages the precision score for binary classification task.
225 226 227 228

    Examples:
        .. code-block:: python

229
            import paddle.fluid as fluid
P
pkpk 已提交
230 231
            import numpy as np

T
Tink_Y 已提交
232
            metric = fluid.metrics.Precision()
P
pkpk 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

            # 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()

            print("expct precision: %.2f and got %.2f" % ( 3.0 / 5.0, numpy_precision))
249 250 251 252 253 254 255 256 257 258 259 260
    """

    def __init__(self, name=None):
        super(Precision, self).__init__(name)
        self.tp = 0  # true positive
        self.fp = 0  # false positive

    def update(self, preds, labels):
        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.")
261 262
        sample_num = labels.shape[0]
        preds = np.rint(preds).astype("int32")
G
Genieliu 已提交
263

264
        for i in range(sample_num):
265
            pred = preds[i]
266
            label = labels[i]
P
pkpk 已提交
267
            if pred == 1:
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                if pred == label:
                    self.tp += 1
                else:
                    self.fp += 1

    def eval(self):
        ap = self.tp + self.fp
        return float(self.tp) / ap if ap != 0 else .0


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

    https://en.wikipedia.org/wiki/Precision_and_recall

P
pkpk 已提交
286 287
    This class mangages the recall score for binary classification task.

288 289 290
    Examples:
        .. code-block:: python

291
            import paddle.fluid as fluid
P
pkpk 已提交
292 293
            import numpy as np

T
Tink_Y 已提交
294
            metric = fluid.metrics.Recall()
P
pkpk 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

            # 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()

            print("expct precision: %.2f and got %.2f" % ( 3.0 / 4.0, numpy_precision))
311 312 313 314 315 316 317 318 319 320 321 322
    """

    def __init__(self, name=None):
        super(Recall, self).__init__(name)
        self.tp = 0  # true positive
        self.fn = 0  # false negtive

    def update(self, preds, labels):
        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 已提交
323 324 325
        sample_num = labels.shape[0]
        preds = np.rint(preds).astype("int32")

326
        for i in range(sample_num):
P
pkpk 已提交
327
            pred = preds[i]
328 329 330 331
            label = labels[i]
            if label == 1:
                if pred == label:
                    self.tp += 1
P
pkpk 已提交
332
                else:
333 334 335 336 337 338 339
                    self.fn += 1

    def eval(self):
        recall = self.tp + self.fn
        return float(self.tp) / recall if recall != 0 else .0


D
dzhwinter 已提交
340 341
class Accuracy(MetricBase):
    """
P
pkpk 已提交
342
    Calculate the mean accuracy over multiple batches.
343
    https://en.wikipedia.org/wiki/Accuracy_and_precision
D
dzhwinter 已提交
344 345 346 347

    Args:
       name: the metrics name

348 349 350
    Examples:
        .. code-block:: python

351
            import paddle.fluid as fluid
P
pkpk 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
            #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 已提交
374 375 376 377 378 379 380 381
    """

    def __init__(self, name=None):
        super(Accuracy, self).__init__(name)
        self.value = .0
        self.weight = .0

    def update(self, value, weight):
382 383 384 385 386 387 388
        """
        Update minibatch states.

        Args:
            value(float|numpy.array): accuracy of one minibatch.
            weight(int|float): batch size.
        """
D
dzhwinter 已提交
389 390 391 392 393
        if not _is_number_or_matrix_(value):
            raise ValueError(
                "The 'value' must be a number(int, float) or a numpy ndarray.")
        if not _is_number_(weight):
            raise ValueError("The 'weight' must be a number(int, float).")
P
pkpk 已提交
394 395
        if _is_number_(weight) and weight < 0:
            raise ValueError("The 'weight' can not be negative")
D
dzhwinter 已提交
396 397 398 399
        self.value += value * weight
        self.weight += weight

    def eval(self):
P
pkpk 已提交
400 401 402
        """
        Return the mean accuracy (float or numpy.array) for all accumulated batches.
        """
D
dzhwinter 已提交
403
        if self.weight == 0:
404 405
            raise ValueError("There is no data in Accuracy Metrics. \
                Please check layers.accuracy output has added to Accuracy.")
D
dzhwinter 已提交
406 407 408
        return self.value / self.weight


409
class ChunkEvaluator(MetricBase):
D
dzhwinter 已提交
410 411 412 413
    """
    Accumulate counter numbers output by chunk_eval from mini-batches and
    compute the precision recall and F1-score using the accumulated counter
    numbers.
H
haowang101779990 已提交
414 415
    For some basics of chunking, please refer to 
    `Chunking with Support Vector Machines <https://aclanthology.info/pdf/N/N01/N01-1025.pdf>`_ .
416 417 418 419 420 421
    ChunkEvalEvaluator computes the precision, recall, and F1-score of chunk detection,
    and supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes.

    Examples:
        .. code-block:: python

422
            import paddle.fluid as fluid
P
pkpk 已提交
423
            # init the chunck-level evaluation manager
424
            metric = fluid.metrics.ChunkEvaluator()
P
pkpk 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

            # suppose the model predict 10 chuncks, while 8 ones are correct and the ground truth has 9 chuncks.
            num_infer_chunks = 10
            num_label_chunks = 9 
            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))

            # the next batch, predicting 3 prefectly correct chuncks.
            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 已提交
446 447 448
    """

    def __init__(self, name=None):
T
update  
typhoonzero 已提交
449
        super(ChunkEvaluator, self).__init__(name)
D
dzhwinter 已提交
450 451 452 453 454
        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):
455 456
        """
        Update the states based on the layers.chunk_eval() ouputs.
H
haowang101779990 已提交
457

458 459 460 461 462 463
        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 已提交
464 465
        if not _is_number_or_matrix_(num_infer_chunks):
            raise ValueError(
466
                "The 'num_infer_chunks' must be a number(int) or a numpy ndarray."
D
dzhwinter 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            )
        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):
        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
        return precision, recall, f1_score


class EditDistance(MetricBase):
    """
493
    Edit distance is a way of quantifying how dissimilar two strings
P
pkpk 已提交
494 495 496
    (e.g., words) are to each another by counting the minimum number
    of edit operations (add, remove or replace) required to transform
    one string into the other.
497 498
    Refer to https://en.wikipedia.org/wiki/Edit_distance

P
pkpk 已提交
499 500 501 502 503 504
    This EditDistance class takes two inputs by using update function:
    1. distances: a (batch_size, 1) numpy.array, each element represents the
    edit distance between two sequences.
    2. seq_num: a int|float value, standing for the number of sequence pairs.

    and returns the overall edit distance of multiple sequence-pairs.
D
dzhwinter 已提交
505 506 507 508

    Args:
        name: the metrics name

509 510 511
    Examples:
        .. code-block:: python

512
            import paddle.fluid as fluid
P
pkpk 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
            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 已提交
528

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

P
pkpk 已提交
532 533 534 535 536 537 538 539 540 541 542 543
            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 已提交
544 545 546 547 548 549 550 551 552 553

    """

    def __init__(self, name):
        super(EditDistance, self).__init__(name)
        self.total_distance = .0
        self.seq_num = 0
        self.instance_error = 0

    def update(self, distances, seq_num):
P
pkpk 已提交
554 555 556 557 558 559 560 561 562
        """
        Update the overall edit distance

        Args:
            distances: a (batch_size, 1) numpy.array, each element represents the 
            edit distance between two sequences.
            seq_num: a int|float value, standing for the number of sequence pairs.

        """
D
dzhwinter 已提交
563 564 565 566 567 568 569 570 571 572
        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 已提交
573
    def eval(self):
P
pkpk 已提交
574 575 576 577 578
        """
        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 已提交
579 580 581 582 583
        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 已提交
584
        avg_instance_error = self.instance_error / float(self.seq_num)
D
dzhwinter 已提交
585 586 587 588 589
        return avg_distance, avg_instance_error


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

    The `auc` function creates four local variables, `true_positives`,
596 597 598 599 600 601
    `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 已提交
602 603 604 605 606 607 608

    Args:
        name: metric name
        curve: Specifies the name of the curve to be computed, 'ROC' [default] or
          'PR' for the Precision-Recall-curve.

    "NOTE: only implement the ROC curve type via Python now."
609 610 611 612

    Examples:
        .. code-block:: python

613
            import paddle.fluid as fluid
P
pkpk 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
            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 已提交
634 635
    """

T
tangwei12 已提交
636
    def __init__(self, name, curve='ROC', num_thresholds=4095):
Q
fix auc  
qiaolongfei 已提交
637
        super(Auc, self).__init__(name=name)
D
dzhwinter 已提交
638 639
        self._curve = curve
        self._num_thresholds = num_thresholds
T
tangwei12 已提交
640 641 642 643

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

Q
qiaolongfei 已提交
645
    def update(self, preds, labels):
P
pkpk 已提交
646 647 648 649 650 651 652 653 654
        """
        Update the auc curve with the given predictions and labels

        Args:
             preds: 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: an numpy array in the shape of (batch_size, 1), labels[i] is either o or 1, representing
             the label of the instance i.
        """
D
dzhwinter 已提交
655 656
        if not _is_numpy_(labels):
            raise ValueError("The 'labels' must be a numpy ndarray.")
Q
qiaolongfei 已提交
657
        if not _is_numpy_(preds):
D
dzhwinter 已提交
658 659
            raise ValueError("The 'predictions' must be a numpy ndarray.")

T
tangwei12 已提交
660 661 662 663 664 665 666 667 668 669 670 671
        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 已提交
672 673

    def eval(self):
P
pkpk 已提交
674 675 676
        """
        Return the area (a float score) under auc curve
        """
T
tangwei12 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        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]
            auc += self.trapezoid_area(tot_neg, tot_neg_prev, tot_pos,
                                       tot_pos_prev)
            idx -= 1

        return auc / tot_pos / tot_neg if tot_pos > 0.0 and tot_neg > 0.0 else 0.0
692 693 694 695 696 697 698


class DetectionMAP(object):
    """
    Calculate the detection mean average precision (mAP).

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

700
    1. calculate the true positive and false positive according to the input
H
haowang101779990 已提交
701
       of detection and labels.
702 703 704
    2. calculate mAP value, support two versions: '11 point' and 'integral'.

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

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

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
      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
            with shape [N, 1].
        gt_box (Variable): The ground truth bounding box (bbox), which is a
            LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax].
        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.
        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
翟飞跃 已提交
723
            considered, 0 by default.
724
        overlap_threshold (float): The threshold for deciding true/false
翟飞跃 已提交
725
            positive, 0.5 by default.
726
        evaluate_difficult (bool): Whether to consider difficult ground truth
翟飞跃 已提交
727
            for evaluation, True by default. This argument does not work when
728 729 730 731 732 733 734 735 736 737
            gt_difficult is None.
        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.

    Examples:
        .. code-block:: python

738
            import paddle.fluid as fluid
P
pkpk 已提交
739
            import paddle.fluid.layers as layers
740

P
pkpk 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
            batch_size = -1 # can be any size
            image_boxs_num = 10
            bounding_bboxes_num = 21

            pb = layers.data(name='prior_box', shape=[image_boxs_num, 4],
                append_batch_size=False, dtype='float32')

            pbv = layers.data(name='prior_box_var', shape=[image_boxs_num, 4],
                append_batch_size=False, dtype='float32')

            loc = layers.data(name='target_box', shape=[batch_size, bounding_bboxes_num, 4],
                append_batch_size=False, dtype='float32')

            scores = layers.data(name='scores', shape=[batch_size, bounding_bboxes_num, image_boxs_num],
                append_batch_size=False, dtype='float32')

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

            gt_box = fluid.layers.data(name="gt_box", shape=[batch_size, 4], dtype="float32")
            gt_label = fluid.layers.data(name="gt_label", shape=[batch_size, 1], dtype="float32")
            difficult = fluid.layers.data(name="difficult", shape=[batch_size, 1], dtype="float32")

            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 已提交
768

P
pkpk 已提交
769 770
            # see detailed examples at 
            https://github.com/PaddlePaddle/models/blob/43cdafbb97e52e6d93cc5bbdc6e7486f27665fc8/PaddleCV/object_detection
771

H
haowang101779990 已提交
772
 
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    """

    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'):

        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
        map = layers.detection_map(
            input,
            label,
            class_num,
            background_label,
            overlap_threshold=overlap_threshold,
            evaluate_difficult=evaluate_difficult,
            ap_version=ap_version)

        states = []
        states.append(
            self._create_state(
                dtype='int32', shape=None, suffix='accum_pos_count'))
        states.append(
            self._create_state(
                dtype='float32', shape=None, suffix='accum_true_pos'))
        states.append(
            self._create_state(
                dtype='float32', shape=None, suffix='accum_false_pos'))
        var = self._create_state(dtype='int32', shape=[1], suffix='has_state')
        self.helper.set_variable_initializer(
            var, initializer=Constant(value=int(0)))
        self.has_state = var

        # calculate accumulative mAP
        accum_map = layers.detection_map(
            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,
            ap_version=ap_version)

        layers.fill_constant(
            shape=self.has_state.shape,
            value=1,
            dtype=self.has_state.dtype,
            out=self.has_state)

        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
        """
        state = self.helper.create_variable(
            name="_".join([unique_name.generate(self.helper.name), suffix]),
            persistable=True,
            dtype=dtype,
            shape=shape)
        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 已提交
866
        Reset metric states at the begin of each pass/user specified batch.
867 868

        Args:
D
Dang Qingqing 已提交
869
            executor(Executor): a executor for executing
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
                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)
            return block.create_var(
                name=var.name,
                shape=var.shape,
                dtype=var.dtype,
                type=var.type,
                lod_level=var.lod_level,
                persistable=var.persistable)

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