eval.py 4.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2019 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import paddle.fluid as fluid

23
from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
24
import ppdet.utils.checkpoint as checkpoint
25
from ppdet.utils.check import check_gpu
26
from ppdet.modeling.model_input import create_feed
27 28
from ppdet.data.data_feed import create_reader
from ppdet.core.workspace import load_config, merge_config, create
Y
Yang Zhang 已提交
29 30
from ppdet.utils.cli import print_total_cfg
from ppdet.utils.cli import ArgsParser
31 32 33 34 35 36 37 38 39 40 41

import logging
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)


def main():
    """
    Main evaluate function
    """
Y
Yang Zhang 已提交
42
    cfg = load_config(FLAGS.config)
43
    if 'architecture' in cfg:
Y
Yang Zhang 已提交
44
        main_arch = cfg.architecture
45 46 47
    else:
        raise ValueError("'architecture' not specified in config file.")

Y
Yang Zhang 已提交
48
    merge_config(FLAGS.opt)
49

50 51
    # check if set use_gpu=True in paddlepaddle cpu version
    check_gpu(cfg.use_gpu)
W
wangguanzhong 已提交
52
    print_total_cfg(cfg)
53

54 55 56
    if 'eval_feed' not in cfg:
        eval_feed = create(main_arch + 'EvalFeed')
    else:
Y
Yang Zhang 已提交
57
        eval_feed = create(cfg.eval_feed)
58 59

    # define executor
Y
Yang Zhang 已提交
60
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
61 62
    exe = fluid.Executor(place)

63
    # build program
64 65 66 67 68
    model = create(main_arch)
    startup_prog = fluid.Program()
    eval_prog = fluid.Program()
    with fluid.program_guard(eval_prog, startup_prog):
        with fluid.unique_name.guard():
69
            pyreader, feed_vars = create_feed(eval_feed)
70
            fetches = model.eval(feed_vars)
71 72
    eval_prog = eval_prog.clone(True)

W
wangguanzhong 已提交
73
    reader = create_reader(eval_feed, args_path=FLAGS.dataset_dir)
74 75
    pyreader.decorate_sample_list_generator(reader, place)

76 77
    # eval already exists json file
    if FLAGS.json_eval:
78 79 80 81
        logger.info(
            "In json_eval mode, PaddleDetection will evaluate json files in "
            "output_eval directly. And proposal.json, bbox.json and mask.json "
            "will be detected by default.")
W
wangguanzhong 已提交
82 83
        json_eval_results(
            eval_feed, cfg.metric, json_directory=FLAGS.output_eval)
84
        return
85 86 87

    compile_program = fluid.compiler.CompiledProgram(
        eval_prog).with_data_parallel()
88

89
    # load model
90
    exe.run(startup_prog)
Y
Yang Zhang 已提交
91
    if 'weights' in cfg:
92
        checkpoint.load_params(exe, eval_prog, cfg.weights)
93

94 95
    assert cfg.metric in ['COCO', 'VOC'], \
            "unknown metric type {}".format(cfg.metric)
96
    extra_keys = []
97
    if cfg.metric == 'COCO':
98
        extra_keys = ['im_info', 'im_id', 'im_shape']
99 100
    if cfg.metric == 'VOC':
        extra_keys = ['gt_box', 'gt_label', 'is_difficult']
101 102 103

    keys, values, cls = parse_fetches(fetches, eval_prog, extra_keys)

104 105 106 107 108 109
    # whether output bbox is normalized in model output layer
    is_bbox_normalized = False
    if hasattr(model, 'is_bbox_normalized') and \
            callable(model.is_bbox_normalized):
        is_bbox_normalized = model.is_bbox_normalized()

110
    results = eval_run(exe, compile_program, pyreader, keys, values, cls)
111

112
    # evaluation
Y
Yang Zhang 已提交
113 114 115
    resolution = None
    if 'mask' in results[0]:
        resolution = model.mask_head.resolution
K
Kaipeng Deng 已提交
116 117
    # if map_type not set, use default 11point, only use in VOC eval
    map_type = cfg.map_type if 'map_type' in cfg else '11point'
W
wangguanzhong 已提交
118
    eval_results(results, eval_feed, cfg.metric, cfg.num_classes, resolution,
K
Kaipeng Deng 已提交
119
                 is_bbox_normalized, FLAGS.output_eval, map_type)
120

W
wangguanzhong 已提交
121

122
if __name__ == '__main__':
Y
Yang Zhang 已提交
123 124
    parser = ArgsParser()
    parser.add_argument(
125 126 127 128
        "--json_eval",
        action='store_true',
        default=False,
        help="Whether to re eval with already exists bbox.json or mask.json")
W
wangguanzhong 已提交
129 130 131 132 133 134
    parser.add_argument(
        "-d",
        "--dataset_dir",
        default=None,
        type=str,
        help="Dataset path, same as DataFeed.dataset.dataset_dir")
135
    parser.add_argument(
W
wangguanzhong 已提交
136
        "-f",
137 138 139 140
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation file directory, default is current directory.")
Y
Yang Zhang 已提交
141
    FLAGS = parser.parse_args()
142
    main()