test_auc_op.py 2.4 KB
Newer Older
T
typhoonzero 已提交
1 2 3 4 5 6 7 8
import unittest
import numpy as np
from op_test import OpTest


class TestAucOp(OpTest):
    def setUp(self):
        self.op_type = "auc"
武毅 已提交
9 10 11
        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 已提交
12
        num_thresholds = 200
武毅 已提交
13
        self.inputs = {'Out': pred, 'Indices': indices, 'Label': labels}
T
typhoonzero 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
        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:
武毅 已提交
35
                    if pred[i, 0] >= thresh:
T
typhoonzero 已提交
36 37 38 39
                        tp += 1
                    else:
                        fn += 1
                else:
武毅 已提交
40
                    if pred[i, 0] >= thresh:
T
typhoonzero 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
                        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()


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