test_auc_op.py 3.0 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
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.

T
typhoonzero 已提交
15 16 17 18 19 20 21 22
import unittest
import numpy as np
from op_test import OpTest


class TestAucOp(OpTest):
    def setUp(self):
        self.op_type = "auc"
武毅 已提交
23 24 25
        pred = np.random.random((128, 2)).astype("float32")
        indices = np.random.randint(0, 2, (128, 2))
        labels = np.random.randint(0, 2, (128, 1))
T
typhoonzero 已提交
26
        num_thresholds = 200
武毅 已提交
27
        self.inputs = {'Out': pred, 'Indices': indices, 'Label': labels}
T
typhoonzero 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
        self.attrs = {'curve': 'ROC', 'num_thresholds': num_thresholds}
        # NOTE: sklearn use a different way to generate thresholds
        #       which will cause the result differs slightly:
        # from sklearn.metrics import roc_curve, auc
        # fpr, tpr, thresholds = roc_curve(labels, pred)
        # auc_value = auc(fpr, tpr)
        # we caculate AUC again using numpy for testing
        kepsilon = 1e-7  # to account for floating point imprecisions
        thresholds = [(i + 1) * 1.0 / (num_thresholds - 1)
                      for i in range(num_thresholds - 2)]
        thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon]

        # caculate TP, FN, TN, FP count
        tp_list = np.ndarray((num_thresholds, ))
        fn_list = np.ndarray((num_thresholds, ))
        tn_list = np.ndarray((num_thresholds, ))
        fp_list = np.ndarray((num_thresholds, ))
        for idx_thresh, thresh in enumerate(thresholds):
            tp, fn, tn, fp = 0, 0, 0, 0
            for i, lbl in enumerate(labels):
                if lbl:
武毅 已提交
49
                    if pred[i, 0] >= thresh:
T
typhoonzero 已提交
50 51 52 53
                        tp += 1
                    else:
                        fn += 1
                else:
武毅 已提交
54
                    if pred[i, 0] >= thresh:
T
typhoonzero 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
                        fp += 1
                    else:
                        tn += 1
            tp_list[idx_thresh] = tp
            fn_list[idx_thresh] = fn
            tn_list[idx_thresh] = tn
            fp_list[idx_thresh] = fp

        epsilon = 1e-6
        tpr = (tp_list.astype("float32") + epsilon) / (
            tp_list + fn_list + epsilon)
        fpr = fp_list.astype("float32") / (fp_list + tn_list + epsilon)
        rec = (tp_list.astype("float32") + epsilon) / (
            tp_list + fp_list + epsilon)

        x = fpr[:num_thresholds - 1] - fpr[1:]
        y = (tpr[:num_thresholds - 1] + tpr[1:]) / 2.0
        auc_value = np.sum(x * y)

        self.outputs = {'AUC': auc_value}

    def test_check_output(self):
        self.check_output()


武毅 已提交
80 81
if __name__ == "__main__":
    unittest.main()