test_detection_map_op.py 11.2 KB
Newer Older
W
wanghaox 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16
from __future__ import print_function

W
wanghaox 已提交
17 18
import unittest
import numpy as np
19
import six
W
wanghaox 已提交
20 21 22
import sys
import collections
import math
23
import paddle.fluid as fluid
24
from op_test import OpTest
W
wanghaox 已提交
25 26 27 28


class TestDetectionMAPOp(OpTest):
    def set_data(self):
29
        self.class_num = 4
W
wanghaox 已提交
30
        self.init_test_case()
W
wanghaox 已提交
31
        self.mAP = [self.calc_map(self.tf_pos, self.tf_pos_lod)]
W
wanghaox 已提交
32 33 34 35
        self.label = np.array(self.label).astype('float32')
        self.detect = np.array(self.detect).astype('float32')
        self.mAP = np.array(self.mAP).astype('float32')

36
        if len(self.class_pos_count) > 0:
W
wanghaox 已提交
37 38 39 40
            self.class_pos_count = np.array(self.class_pos_count).astype(
                'int32')
            self.true_pos = np.array(self.true_pos).astype('float32')
            self.false_pos = np.array(self.false_pos).astype('float32')
41
            self.has_state = np.array([1]).astype('int32')
W
wanghaox 已提交
42 43 44

            self.inputs = {
                'Label': (self.label, self.label_lod),
W
wanghaox 已提交
45
                'DetectRes': (self.detect, self.detect_lod),
46
                'HasState': self.has_state,
W
wanghaox 已提交
47 48 49 50 51 52 53
                'PosCount': self.class_pos_count,
                'TruePos': (self.true_pos, self.true_pos_lod),
                'FalsePos': (self.false_pos, self.false_pos_lod)
            }
        else:
            self.inputs = {
                'Label': (self.label, self.label_lod),
W
wanghaox 已提交
54
                'DetectRes': (self.detect, self.detect_lod),
W
wanghaox 已提交
55
            }
W
wanghaox 已提交
56 57 58 59

        self.attrs = {
            'overlap_threshold': self.overlap_threshold,
            'evaluate_difficult': self.evaluate_difficult,
60 61
            'ap_type': self.ap_type,
            'class_num': self.class_num
W
wanghaox 已提交
62 63
        }

W
wanghaox 已提交
64 65 66 67 68 69 70
        self.out_class_pos_count = np.array(self.out_class_pos_count).astype(
            'int')
        self.out_true_pos = np.array(self.out_true_pos).astype('float32')
        self.out_false_pos = np.array(self.out_false_pos).astype('float32')

        self.outputs = {
            'MAP': self.mAP,
W
wanghaox 已提交
71 72 73
            'AccumPosCount': self.out_class_pos_count,
            'AccumTruePos': (self.out_true_pos, self.out_true_pos_lod),
            'AccumFalsePos': (self.out_false_pos, self.out_false_pos_lod)
W
wanghaox 已提交
74
        }
W
wanghaox 已提交
75 76 77 78

    def init_test_case(self):
        self.overlap_threshold = 0.3
        self.evaluate_difficult = True
W
wanghaox 已提交
79
        self.ap_type = "integral"
W
wanghaox 已提交
80

81
        self.label_lod = [[2, 2]]
W
wanghaox 已提交
82 83 84
        # label difficult xmin ymin xmax ymax
        self.label = [[1, 0, 0.1, 0.1, 0.3, 0.3], [1, 1, 0.6, 0.6, 0.8, 0.8],
                      [2, 0, 0.3, 0.3, 0.6, 0.5], [1, 0, 0.7, 0.1, 0.9, 0.3]]
W
wanghaox 已提交
85

W
wanghaox 已提交
86
        # label score xmin ymin xmax ymax difficult
87
        self.detect_lod = [[3, 4]]
W
wanghaox 已提交
88
        self.detect = [
W
wanghaox 已提交
89 90 91 92
            [1, 0.3, 0.1, 0.0, 0.4, 0.3], [1, 0.7, 0.0, 0.1, 0.2, 0.3],
            [1, 0.9, 0.7, 0.6, 0.8, 0.8], [2, 0.8, 0.2, 0.1, 0.4, 0.4],
            [2, 0.1, 0.4, 0.3, 0.7, 0.5], [1, 0.2, 0.8, 0.1, 1.0, 0.3],
            [3, 0.2, 0.8, 0.1, 1.0, 0.3]
W
wanghaox 已提交
93 94
        ]

W
wanghaox 已提交
95
        # label score true_pos false_pos
96
        self.tf_pos_lod = [[3, 4]]
W
wanghaox 已提交
97 98 99
        self.tf_pos = [[1, 0.9, 1, 0], [1, 0.7, 1, 0], [1, 0.3, 0, 1],
                       [1, 0.2, 1, 0], [2, 0.8, 0, 1], [2, 0.1, 1, 0],
                       [3, 0.2, 0, 1]]
W
wanghaox 已提交
100

W
wanghaox 已提交
101 102 103 104 105 106
        self.class_pos_count = []
        self.true_pos_lod = [[]]
        self.true_pos = [[]]
        self.false_pos_lod = [[]]
        self.false_pos = [[]]

W
wanghaox 已提交
107
    def calc_map(self, tf_pos, tf_pos_lod):
W
wanghaox 已提交
108 109 110
        mAP = 0.0
        count = 0

W
wanghaox 已提交
111 112 113 114 115 116 117 118
        def get_input_pos(class_pos_count, true_pos, true_pos_lod, false_pos,
                          false_pos_lod):
            class_pos_count_dict = collections.Counter()
            true_pos_dict = collections.defaultdict(list)
            false_pos_dict = collections.defaultdict(list)
            for i, count in enumerate(class_pos_count):
                class_pos_count_dict[i] = count

119 120 121 122 123
            cur_pos = 0
            for i in range(len(true_pos_lod[0])):
                start = cur_pos
                cur_pos += true_pos_lod[0][i]
                end = cur_pos
W
wanghaox 已提交
124 125 126
                for j in range(start, end):
                    true_pos_dict[i].append(true_pos[j])

127 128 129 130 131
            cur_pos = 0
            for i in range(len(false_pos_lod[0])):
                start = cur_pos
                cur_pos += false_pos_lod[0][i]
                end = cur_pos
W
wanghaox 已提交
132 133 134 135 136 137
                for j in range(start, end):
                    false_pos_dict[i].append(false_pos[j])

            return class_pos_count_dict, true_pos_dict, false_pos_dict

        def get_output_pos(label_count, true_pos, false_pos):
138
            label_number = self.class_num
W
wanghaox 已提交
139 140

            out_class_pos_count = []
141
            out_true_pos_lod = []
W
wanghaox 已提交
142
            out_true_pos = []
143
            out_false_pos_lod = []
W
wanghaox 已提交
144 145 146 147 148 149
            out_false_pos = []

            for i in range(label_number):
                out_class_pos_count.append([label_count[i]])
                true_pos_list = true_pos[i]
                out_true_pos += true_pos_list
150
                out_true_pos_lod.append(len(true_pos_list))
W
wanghaox 已提交
151 152
                false_pos_list = false_pos[i]
                out_false_pos += false_pos_list
153
                out_false_pos_lod.append(len(false_pos_list))
W
wanghaox 已提交
154 155 156 157

            return out_class_pos_count, out_true_pos, [
                out_true_pos_lod
            ], out_false_pos, [out_false_pos_lod]
W
wanghaox 已提交
158 159 160 161 162 163 164 165 166 167

        def get_accumulation(pos_list):
            sorted_list = sorted(pos_list, key=lambda pos: pos[0], reverse=True)
            sum = 0
            accu_list = []
            for (score, count) in sorted_list:
                sum += count
                accu_list.append(sum)
            return accu_list

W
wanghaox 已提交
168 169 170
        label_count, true_pos, false_pos = get_input_pos(
            self.class_pos_count, self.true_pos, self.true_pos_lod,
            self.false_pos, self.false_pos_lod)
171 172 173
        for v in self.label:
            label = v[0]
            difficult = False if len(v) == 5 else v[1]
W
wanghaox 已提交
174 175 176 177 178
            if self.evaluate_difficult:
                label_count[label] += 1
            elif not difficult:
                label_count[label] += 1

W
wanghaox 已提交
179
        for (label, score, tp, fp) in tf_pos:
W
wanghaox 已提交
180 181 182
            true_pos[label].append([score, tp])
            false_pos[label].append([score, fp])

M
minqiyang 已提交
183
        for (label, label_pos_num) in six.iteritems(label_count):
184 185 186 187
            if label_pos_num == 0: continue
            if label not in true_pos:
                count += 1
                continue
W
wanghaox 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            label_true_pos = true_pos[label]
            label_false_pos = false_pos[label]

            accu_tp_sum = get_accumulation(label_true_pos)
            accu_fp_sum = get_accumulation(label_false_pos)

            precision = []
            recall = []

            for i in range(len(accu_tp_sum)):
                precision.append(
                    float(accu_tp_sum[i]) /
                    float(accu_tp_sum[i] + accu_fp_sum[i]))
                recall.append(float(accu_tp_sum[i]) / label_pos_num)

            if self.ap_type == "11point":
W
wanghaox 已提交
204
                max_precisions = [0.0] * 11
W
wanghaox 已提交
205
                start_idx = len(accu_tp_sum) - 1
W
wanghaox 已提交
206 207 208
                for j in range(10, -1, -1):
                    for i in range(start_idx, -1, -1):
                        if recall[i] < float(j) / 10.0:
W
wanghaox 已提交
209 210 211 212
                            start_idx = i
                            if j > 0:
                                max_precisions[j - 1] = max_precisions[j]
                                break
W
wanghaox 已提交
213 214 215 216
                        else:
                            if max_precisions[j] < precision[i]:
                                max_precisions[j] = precision[i]
                for j in range(10, -1, -1):
W
wanghaox 已提交
217 218
                    mAP += max_precisions[j] / 11
                count += 1
W
wanghaox 已提交
219
            elif self.ap_type == "integral":
W
wanghaox 已提交
220 221 222 223 224 225 226 227 228 229
                average_precisions = 0.0
                prev_recall = 0.0
                for i in range(len(accu_tp_sum)):
                    if math.fabs(recall[i] - prev_recall) > 1e-6:
                        average_precisions += precision[i] * \
                            math.fabs(recall[i] - prev_recall)
                        prev_recall = recall[i]

                mAP += average_precisions
                count += 1
230 231 232 233 234 235 236
        pcnt, tp, tp_lod, fp, fp_lod = get_output_pos(label_count, true_pos,
                                                      false_pos)
        self.out_class_pos_count = pcnt
        self.out_true_pos = tp
        self.out_true_pos_lod = tp_lod
        self.out_false_pos = fp
        self.out_false_pos_lod = fp_lod
W
wanghaox 已提交
237 238
        if count != 0:
            mAP /= count
239
        return mAP
W
wanghaox 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    def setUp(self):
        self.op_type = "detection_map"
        self.set_data()

    def test_check_output(self):
        self.check_output()


class TestDetectionMAPOpSkipDiff(TestDetectionMAPOp):
    def init_test_case(self):
        super(TestDetectionMAPOpSkipDiff, self).init_test_case()

        self.evaluate_difficult = False

255
        self.tf_pos_lod = [[2, 4]]
W
wanghaox 已提交
256 257 258 259 260
        # label score true_pos false_pos
        self.tf_pos = [[1, 0.7, 1, 0], [1, 0.3, 0, 1], [1, 0.2, 1, 0],
                       [2, 0.8, 0, 1], [2, 0.1, 1, 0], [3, 0.2, 0, 1]]


261 262 263 264 265 266 267 268 269
class TestDetectionMAPOpWithoutDiff(TestDetectionMAPOp):
    def init_test_case(self):
        super(TestDetectionMAPOpWithoutDiff, self).init_test_case()

        # label xmin ymin xmax ymax
        self.label = [[1, 0.1, 0.1, 0.3, 0.3], [1, 0.6, 0.6, 0.8, 0.8],
                      [2, 0.3, 0.3, 0.6, 0.5], [1, 0.7, 0.1, 0.9, 0.3]]


W
wanghaox 已提交
270 271 272 273 274
class TestDetectionMAPOp11Point(TestDetectionMAPOp):
    def init_test_case(self):
        super(TestDetectionMAPOp11Point, self).init_test_case()

        self.ap_type = "11point"
W
wanghaox 已提交
275 276


W
wanghaox 已提交
277 278 279
class TestDetectionMAPOpMultiBatch(TestDetectionMAPOp):
    def init_test_case(self):
        super(TestDetectionMAPOpMultiBatch, self).init_test_case()
280
        self.class_pos_count = [0, 2, 1, 0]
281
        self.true_pos_lod = [[0, 3, 2]]
W
wanghaox 已提交
282
        self.true_pos = [[0.7, 1.], [0.3, 0.], [0.2, 1.], [0.8, 0.], [0.1, 1.]]
283
        self.false_pos_lod = [[0, 3, 2]]
W
wanghaox 已提交
284 285 286
        self.false_pos = [[0.7, 0.], [0.3, 1.], [0.2, 0.], [0.8, 1.], [0.1, 0.]]


287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
class TestDetectionMAPOp11PointWithClassNoTP(TestDetectionMAPOp):
    def init_test_case(self):
        self.overlap_threshold = 0.3
        self.evaluate_difficult = True
        self.ap_type = "11point"

        self.label_lod = [[2]]
        # label difficult xmin ymin xmax ymax
        self.label = [[2, 0, 0.3, 0.3, 0.6, 0.5], [1, 0, 0.7, 0.1, 0.9, 0.3]]

        # label score xmin ymin xmax ymax difficult
        self.detect_lod = [[1]]
        self.detect = [[1, 0.2, 0.8, 0.1, 1.0, 0.3]]

        # label score true_pos false_pos
        self.tf_pos_lod = [[3, 4]]
        self.tf_pos = [[1, 0.2, 1, 0]]

        self.class_pos_count = []
        self.true_pos_lod = [[]]
        self.true_pos = [[]]
        self.false_pos_lod = [[]]
        self.false_pos = [[]]


W
wanghaox 已提交
312 313
if __name__ == '__main__':
    unittest.main()