metrics_util.py 20.2 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#  Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#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 17 18 19 20 21 22
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division

import logging

import numpy as np
23
import json
24 25
from metrics.youtube8m import eval_util as youtube8m_metrics
from metrics.kinetics import accuracy_metrics as kinetics_metrics
26
from metrics.multicrop_test import multicrop_test_metrics as multicrop_test_metrics
27
from metrics.detections import detection_metrics as detection_metrics
28 29 30
from metrics.bmn_metrics import bmn_proposal_metrics as bmn_proposal_metrics
from metrics.bsn_metrics import bsn_tem_metrics as bsn_tem_metrics
from metrics.bsn_metrics import bsn_pem_metrics as bsn_pem_metrics
S
shippingwang 已提交
31 32 33 34
from metrics.tall import accuracy_metrics as tall_metrics



35 36 37 38 39

logger = logging.getLogger(__name__)


class Metrics(object):
40
    def __init__(self, name, mode, metrics_args):
41 42 43
        """Not implemented"""
        pass

44
    def calculate_and_log_out(self, fetch_list, info=''):
45 46 47
        """Not implemented"""
        pass

48
    def accumulate(self, fetch_list, info=''):
49 50 51
        """Not implemented"""
        pass

52
    def finalize_and_log_out(self, info='', savedir='./'):
53 54 55 56 57 58 59 60 61
        """Not implemented"""
        pass

    def reset(self):
        """Not implemented"""
        pass


class Youtube8mMetrics(Metrics):
62
    def __init__(self, name, mode, metrics_args):
63
        self.name = name
D
dengkaipeng 已提交
64
        self.mode = mode
65 66
        self.num_classes = metrics_args['MODEL']['num_classes']
        self.topk = metrics_args['MODEL']['topk']
67 68
        self.calculator = youtube8m_metrics.EvaluationMetrics(self.num_classes,
                                                              self.topk)
69 70
        if self.mode == 'infer':
            self.infer_results = []
71

72 73 74 75
    def calculate_and_log_out(self, fetch_list, info=''):
        loss = np.mean(np.array(fetch_list[0]))
        pred = np.array(fetch_list[1])
        label = np.array(fetch_list[2])
76 77 78 79 80 81 82
        hit_at_one = youtube8m_metrics.calculate_hit_at_one(pred, label)
        perr = youtube8m_metrics.calculate_precision_at_equal_recall_rate(pred,
                                                                          label)
        gap = youtube8m_metrics.calculate_gap(pred, label)
        logger.info(info + ' , loss = {0}, Hit@1 = {1}, PERR = {2}, GAP = {3}'.format(\
                     '%.6f' % loss, '%.2f' % hit_at_one, '%.2f' % perr, '%.2f' % gap))

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    def accumulate(self, fetch_list, info=''):
        if self.mode == 'infer':
            predictions = np.array(fetch_list[0])
            video_id = fetch_list[1]
            for i in range(len(predictions)):
                topk_inds = predictions[i].argsort()[0 - self.topk:]
                topk_inds = topk_inds[::-1]
                preds = predictions[i][topk_inds]
                self.infer_results.append(
                    (video_id[i], topk_inds.tolist(), preds.tolist()))
        else:
            loss = np.array(fetch_list[0])
            pred = np.array(fetch_list[1])
            label = np.array(fetch_list[2])
            self.calculator.accumulate(loss, pred, label)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            for item in self.infer_results:
                logger.info('video_id {} , topk({}) preds: \n'.format(item[
                    0], self.topk))
                for i in range(len(item[1])):
                    logger.info('\t    class: {},  probability  {} \n'.format(
                        item[1][i], item[2][i]))
            # save infer result into output dir
            #json.dump(self.infer_results, xxxx)
109

110 111 112
        else:
            epoch_info_dict = self.calculator.get()
            logger.info(info + '\tavg_hit_at_one: {0},\tavg_perr: {1},\tavg_loss :{2},\taps: {3},\tgap:{4}'\
113 114 115 116 117
                     .format(epoch_info_dict['avg_hit_at_one'], epoch_info_dict['avg_perr'], \
                             epoch_info_dict['avg_loss'], epoch_info_dict['aps'], epoch_info_dict['gap']))

    def reset(self):
        self.calculator.clear()
118 119
        if self.mode == 'infer':
            self.infer_results = []
120 121 122


class Kinetics400Metrics(Metrics):
123
    def __init__(self, name, mode, metrics_args):
124
        self.name = name
D
dengkaipeng 已提交
125
        self.mode = mode
126
        self.topk = metrics_args['MODEL']['topk']
127
        self.calculator = kinetics_metrics.MetricsCalculator(name, mode.lower())
128 129 130 131 132 133 134 135
        if self.mode == 'infer':
            self.infer_results = []
            self.kinetics_labels = metrics_args['INFER']['kinetics_labels']
            self.labels_list = json.load(open(self.kinetics_labels))

    def calculate_and_log_out(self, fetch_list, info=''):
        if len(fetch_list) == 3:
            loss = fetch_list[0]
136
            loss = np.mean(np.array(loss))
137 138
            pred = np.array(fetch_list[1])
            label = np.array(fetch_list[2])
139 140
        else:
            loss = 0.
141 142
            pred = np.array(fetch_list[0])
            label = np.array(fetch_list[1])
143 144 145
        acc1, acc5 = self.calculator.calculate_metrics(loss, pred, label)
        logger.info(info + '\tLoss: {},\ttop1_acc: {}, \ttop5_acc: {}'.format('%.6f' % loss, \
                       '%.2f' % acc1, '%.2f' % acc5))
X
xiegegege 已提交
146
        return loss
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    def accumulate(self, fetch_list, info=''):
        if self.mode == 'infer':
            predictions = np.array(fetch_list[0])
            video_id = fetch_list[1]
            for i in range(len(predictions)):
                topk_inds = predictions[i].argsort()[0 - self.topk:]
                topk_inds = topk_inds[::-1]
                preds = predictions[i][topk_inds]
                self.infer_results.append(
                    (video_id[i], topk_inds.tolist(), preds.tolist()))
        else:
            if len(fetch_list) == 3:
                loss = fetch_list[0]
                loss = np.mean(np.array(loss))
                pred = np.array(fetch_list[1])
                label = np.array(fetch_list[2])
            else:
                loss = 0.
                pred = np.array(fetch_list[0])
                label = np.array(fetch_list[1])
            self.calculator.accumulate(loss, pred, label)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            for item in self.infer_results:
                logger.info('video_id {} , topk({}) preds: \n'.format(item[
                    0], self.topk))
                for i in range(len(item[1])):
                    logger.info('\t    class: {},  probability:  {} \n'.format(
                        self.labels_list[item[1][i]], item[2][i]))
            # save infer results
        else:
            self.calculator.finalize_metrics()
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            acc1 = metrics_dict['avg_acc1']
            acc5 = metrics_dict['avg_acc5']
            logger.info(info + '\tLoss: {},\ttop1_acc: {}, \ttop5_acc: {}'.format('%.6f' % loss, \
186 187 188 189
                       '%.2f' % acc1, '%.2f' % acc5))

    def reset(self):
        self.calculator.reset()
190 191
        if self.mode == 'infer':
            self.infer_results = []
192 193


194 195
class MulticropMetrics(Metrics):
    def __init__(self, name, mode, metrics_args):
196
        self.name = name
D
dengkaipeng 已提交
197
        self.mode = mode
198
        if (mode == 'test') or (mode == 'infer'):
199
            args = {}
200 201
            args['num_test_clips'] = metrics_args[mode.upper()][
                'num_test_clips']
202 203
            args['dataset_size'] = metrics_args.TEST.dataset_size
            args['filename_gt'] = metrics_args.TEST.filename_gt
204 205
            args['checkpoint_dir'] = metrics_args[mode.upper()][
                'checkpoint_dir']
206
            args['num_classes'] = metrics_args.MODEL.num_classes
207
            args['labels_list'] = metrics_args.INFER.kinetics_labels
208 209
            self.calculator = multicrop_test_metrics.MetricsCalculator(
                name, mode.lower(), **args)
210 211
        else:
            self.calculator = kinetics_metrics.MetricsCalculator(name,
D
dengkaipeng 已提交
212
                                                                 mode.lower())
213

214 215
    def calculate_and_log_out(self, fetch_list, info=''):
        if (self.mode == 'test') or (self.mode == 'infer'):
216 217
            pass
        else:
218 219
            if len(fetch_list) == 3:
                loss = fetch_list[0]
220
                loss = np.mean(np.array(loss))
221 222
                pred = fetch_list[1]
                label = fetch_list[2]
223 224
            else:
                loss = 0.
225 226
                pred = fetch_list[0]
                label = fetch_list[1]
227 228 229 230
            acc1, acc5 = self.calculator.calculate_metrics(loss, pred, label)
            logger.info(info + '\tLoss: {},\ttop1_acc: {}, \ttop5_acc: {}'.format('%.6f' % loss, \
                                   '%.2f' % acc1, '%.2f' % acc5))

231 232 233 234 235 236 237 238 239 240 241 242 243 244
    def accumulate(self, fetch_list):
        if self.mode == 'test':
            pred = fetch_list[0]
            label = fetch_list[1]
            self.calculator.accumulate(pred, label)
        elif self.mode == 'infer':
            pred = fetch_list[0]
            video_id = fetch_list[1]
            self.calculator.accumulate_infer_results(pred, video_id)
        else:
            loss = fetch_list[0]
            pred = fetch_list[1]
            label = fetch_list[2]
            self.calculator.accumulate(loss, pred, label)
245

246
    def finalize_and_log_out(self, info='', savedir='./'):
D
dengkaipeng 已提交
247
        if self.mode == 'test':
248
            self.calculator.finalize_metrics()
249 250
        elif self.mode == 'infer':
            self.calculator.finalize_infer_metrics()
251 252 253 254 255 256 257 258 259 260 261 262 263
        else:
            self.calculator.finalize_metrics()
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            acc1 = metrics_dict['avg_acc1']
            acc5 = metrics_dict['avg_acc5']
            logger.info(info + '\tLoss: {},\ttop1_acc: {}, \ttop5_acc: {}'.format('%.6f' % loss, \
                           '%.2f' % acc1, '%.2f' % acc5))

    def reset(self):
        self.calculator.reset()


264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
class DetectionMetrics(Metrics):
    def __init__(self, name, mode, cfg):
        self.name = name
        self.mode = mode
        args = {}
        args['score_thresh'] = cfg.TEST.score_thresh
        args['nms_thresh'] = cfg.TEST.nms_thresh
        args['sigma_thresh'] = cfg.TEST.sigma_thresh
        args['soft_thresh'] = cfg.TEST.soft_thresh
        args['class_label_file'] = cfg.TEST.class_label_file
        args['video_duration_file'] = cfg.TEST.video_duration_file
        args['gt_label_file'] = cfg.TEST.filelist
        args['mode'] = mode
        args['name'] = name
        self.calculator = detection_metrics.MetricsCalculator(**args)

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    def calculate_and_log_out(self, fetch_list, info=''):
        total_loss = np.array(fetch_list[0])
        loc_loss = np.array(fetch_list[1])
        cls_loss = np.array(fetch_list[2])
        logger.info(
            info + '\tLoss = {}, \tloc_loss = {}, \tcls_loss = {}'.format(
                np.mean(total_loss), np.mean(loc_loss), np.mean(cls_loss)))

    def accumulate(self, fetch_list):
        if self.mode == 'infer':
            self.calculator.accumulate_infer_results(fetch_list)
        else:
            self.calculator.accumulate(fetch_list)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            self.calculator.finalize_infer_metrics(savedir)
            #pass
        else:
            self.calculator.finalize_metrics(savedir)
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            loc_loss = metrics_dict['avg_loc_loss']
            cls_loss = metrics_dict['avg_cls_loss']
            logger.info(info + '\tLoss: {},\tloc_loss: {}, \tcls_loss: {}'.format('%.6f' % loss, \
                           '%.6f' % loc_loss, '%.6f' % cls_loss))
306 307 308 309 310

    def reset(self):
        self.calculator.reset()


311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
class BmnMetrics(Metrics):
    def __init__(self, name, mode, cfg):
        self.name = name
        self.mode = mode
        self.calculator = bmn_proposal_metrics.MetricsCalculator(
            cfg=cfg, name=self.name, mode=self.mode)

    def calculate_and_log_out(self, fetch_list, info=''):
        total_loss = np.array(fetch_list[0])
        tem_loss = np.array(fetch_list[1])
        pem_reg_loss = np.array(fetch_list[2])
        pem_cls_loss = np.array(fetch_list[3])
        logger.info(
            info + '\tLoss = {}, \ttem_loss = {}, \tpem_reg_loss = {}, \tpem_cls_loss = {}'.format(
                '%.04f' % np.mean(total_loss), '%.04f' % np.mean(tem_loss), \
                '%.04f' % np.mean(pem_reg_loss), '%.04f' % np.mean(pem_cls_loss)))

    def accumulate(self, fetch_list):
        if self.mode == 'infer':
            self.calculator.accumulate_infer_results(fetch_list)
        else:
            self.calculator.accumulate(fetch_list)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            self.calculator.finalize_infer_metrics()
        else:
            self.calculator.finalize_metrics()
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            tem_loss = metrics_dict['avg_tem_loss']
            pem_reg_loss = metrics_dict['avg_pem_reg_loss']
            pem_cls_loss = metrics_dict['avg_pem_cls_loss']
            logger.info(
                info +
                '\tLoss = {}, \ttem_loss = {}, \tpem_reg_loss = {}, \tpem_cls_loss = {}'.
                format('%.04f' % loss, '%.04f' % tem_loss, '%.04f' %
                       pem_reg_loss, '%.04f' % pem_cls_loss))

    def reset(self):
        self.calculator.reset()


class BsnTemMetrics(Metrics):
    def __init__(self, name, mode, cfg):
        self.name = name
        self.mode = mode
        self.calculator = bsn_tem_metrics.MetricsCalculator(
            cfg=cfg, name=self.name, mode=self.mode)

    def calculate_and_log_out(self, fetch_list, info=''):
        total_loss = np.array(fetch_list[0])
        start_loss = np.array(fetch_list[1])
        end_loss = np.array(fetch_list[2])
        action_loss = np.array(fetch_list[3])
        logger.info(
            info +
            '\tLoss = {}, \tstart_loss = {}, \tend_loss = {}, \taction_loss = {}'.
            format('%.04f' % np.mean(total_loss), '%.04f' % np.mean(start_loss),
                   '%.04f' % np.mean(end_loss), '%.04f' % np.mean(action_loss)))

    def accumulate(self, fetch_list):
        if self.mode == 'infer':
            self.calculator.accumulate_infer_results(fetch_list)
        else:
            self.calculator.accumulate(fetch_list)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            self.calculator.finalize_infer_metrics()
        else:
            self.calculator.finalize_metrics()
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            start_loss = metrics_dict['avg_start_loss']
            end_loss = metrics_dict['avg_end_loss']
            action_loss = metrics_dict['avg_action_loss']
            logger.info(
                info +
                '\tLoss = {}, \tstart_loss = {}, \tend_loss = {}, \taction_loss = {}'.
                format('%.04f' % loss, '%.04f' % start_loss, '%.04f' % end_loss,
                       '%.04f' % action_loss))

    def reset(self):
        self.calculator.reset()


class BsnPemMetrics(Metrics):
    def __init__(self, name, mode, cfg):
        self.name = name
        self.mode = mode
        self.calculator = bsn_pem_metrics.MetricsCalculator(
            cfg=cfg, name=self.name, mode=self.mode)

    def calculate_and_log_out(self, fetch_list, info=''):
        total_loss = np.array(fetch_list[0])
        logger.info(info + '\tLoss = {}'.format('%.04f' % np.mean(total_loss)))

    def accumulate(self, fetch_list):
        if self.mode == 'infer':
            self.calculator.accumulate_infer_results(fetch_list)
        else:
            self.calculator.accumulate(fetch_list)

    def finalize_and_log_out(self, info='', savedir='./'):
        if self.mode == 'infer':
            self.calculator.finalize_infer_metrics()
        else:
            self.calculator.finalize_metrics()
            metrics_dict = self.calculator.get_computed_metrics()
            loss = metrics_dict['avg_loss']
            logger.info(info + '\tLoss = {}'.format('%.04f' % loss))

    def reset(self):
        self.calculator.reset()

S
shippingwang 已提交
427 428 429 430 431 432 433 434
##shipping
class TallMetrics(Metrics):
    def __init__(self, name, model, cfg):
	self.name =  name
 	self.mode =mode
	self.calculator = tall_metrics.MetricsCalculator(cfg=cfg, name=self.name, mode=self.mode)

    def calculator_and_log_out(self, fetch_list, info=""):
S
shippingwang 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
	if self.mode == "train":
            loss = np.array(fetch_list[0])
	    logger.info(info +'\tLoss = {}'.format('%.6f' % np.mean(loss)))
	elif self.mode == "valid":
	    outs = fetch_list[0]
	    outputs = np.squeeze(outs)
	    start = fetch_list[1]
	    end = fetch_list[2]
	    k = fetch_list[3]
	    t = fetch_list[4]
	
	    movie_clip_sentences = fetch_list[5]
	    movie_clip_featmaps = fetch_lkist[6]

            sentence_image_mat = np.zeros([len(movie_clip_sentences), len(movie_clip_featmaps)])
	    sentence_image_reg_mat = np.zeros([len(movie_clip_sentences), len(movie_clip_featmaps    ), 2])
	    sentence_image_mat[k, t] = outputs[0]
	    # sentence_image_mat[k, t] = expit(outputs[0]) * conf_score
            reg_end = end + outputs[2]
            reg_start = start + outputs[1]
	    sentence_image_reg_mat[k, t, 0] = reg_start
	    sentence_image_reg_mat[k, t, 1] = reg_end


	    clips = [b[0] for b in movie_clip_featmaps]
	    sclips = [b[0] for b in movie_clip_sentences]

            for i in range(len(IoU_thresh)):
            	IoU = IoU_thresh[i]
            	correct_num_10 = compute_IoU_recall_top_n_forreg(10, IoU, sentence_image_mat, sentence_image_reg_mat, sclips, iclips)
            	correct_num_5 = compute_IoU_recall_top_n_forreg(5, IoU, sentence_image_mat, sentence_image_reg_mat, sclips, iclips)
            	correct_num_1 = compute_IoU_recall_top_n_forreg(1, IoU, sentence_image_mat, sentence_image_reg_mat, sclips, iclips)
            	logger.info(info + " IoU=" + str(IoU) + ", R@10: " + str(correct_num_10 / len(sclips)) + "; IoU=" + str(IoU) + ", R@5: " + str(correct_num_5 / len(sclips)) + "; IoU=" + str(IoU) + ", R@1: " + str(correct_num_1 / len(sclips)))

            	all_correct_num_10[i] += correct_num_10
            	all_correct_num_5[i] += correct_num_5
            	all_correct_num_1[i] += correct_num_1
            all_retrievd += len(sclips)

	else: 
	    pass
S
shippingwang 已提交
476
    
S
shippingwang 已提交
477
    def accumalate():
S
shippingwang 已提交
478 479 480 481 482 483

    def finalize_and_log_out(self, info="", savedir="/"):

    def reset(self):
	self.calculator.clear()

484

485 486 487 488 489 490 491 492 493
class MetricsZoo(object):
    def __init__(self):
        self.metrics_zoo = {}

    def regist(self, name, metrics):
        assert metrics.__base__ == Metrics, "Unknow model type {}".format(
            type(metrics))
        self.metrics_zoo[name] = metrics

494
    def get(self, name, mode, cfg):
495 496
        for k, v in self.metrics_zoo.items():
            if k == name:
497
                return v(name, mode, cfg)
498 499 500 501 502 503 504 505 506 507 508
        raise MetricsNotFoundError(name, self.metrics_zoo.keys())


# singleton metrics_zoo
metrics_zoo = MetricsZoo()


def regist_metrics(name, metrics):
    metrics_zoo.regist(name, metrics)


509 510
def get_metrics(name, mode, cfg):
    return metrics_zoo.get(name, mode, cfg)
511 512


D
dengkaipeng 已提交
513
# sort by alphabet
514
regist_metrics("ATTENTIONCLUSTER", Youtube8mMetrics)
D
dengkaipeng 已提交
515 516 517
regist_metrics("ATTENTIONLSTM", Youtube8mMetrics)
regist_metrics("NEXTVLAD", Youtube8mMetrics)
regist_metrics("NONLOCAL", MulticropMetrics)
518
regist_metrics("TSM", Kinetics400Metrics)
D
dengkaipeng 已提交
519
regist_metrics("TSN", Kinetics400Metrics)
520
regist_metrics("STNET", Kinetics400Metrics)
521
regist_metrics("CTCN", DetectionMetrics)
522 523 524
regist_metrics("BMN", BmnMetrics)
regist_metrics("BSNTEM", BsnTemMetrics)
regist_metrics("BSNPEM", BsnPemMetrics)
S
shippingwang 已提交
525
redist_metrics("TALL", TallMetrics)