eval.py 7.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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

Q
qingqing01 已提交
19
import os, sys
20 21 22 23
# add python path of PadleDetection to sys.path
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
if parent_path not in sys.path:
    sys.path.append(parent_path)
24

25
import paddle
26 27 28 29 30 31 32
import paddle.fluid as fluid

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

K
Kaipeng Deng 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
try:
    from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
    import ppdet.utils.checkpoint as checkpoint
    from ppdet.utils.check import check_gpu, check_xpu, check_version, check_config, enable_static_mode

    from ppdet.data.reader import create_reader

    from ppdet.core.workspace import load_config, merge_config, create
    from ppdet.utils.cli import ArgsParser
except ImportError as e:
    if sys.argv[0].find('static') >= 0:
        logger.error("Importing ppdet failed when running static model "
                     "with error: {}\n"
                     "please try:\n"
                     "\t1. run static model under PaddleDetection/static "
                     "directory\n"
                     "\t2. run 'pip uninstall ppdet' to uninstall ppdet "
                     "dynamic version firstly.".format(e))
        sys.exit(-1)
    else:
        raise e

55 56 57 58 59 60 61

def main():
    """
    Main evaluate function
    """
    cfg = load_config(FLAGS.config)
    merge_config(FLAGS.opt)
62
    check_config(cfg)
63 64
    # check if set use_gpu=True in paddlepaddle cpu version
    check_gpu(cfg.use_gpu)
Q
QingshuChen 已提交
65 66 67 68
    use_xpu = False
    if hasattr(cfg, 'use_xpu'):
        check_xpu(cfg.use_xpu)
        use_xpu = cfg.use_xpu
W
wangguanzhong 已提交
69 70
    # check if paddlepaddle version is satisfied
    check_version()
71

Q
QingshuChen 已提交
72 73 74
    assert not (use_xpu and cfg.use_gpu), \
            'Can not run on both XPU and GPU'

75 76
    main_arch = cfg.architecture

W
wangguanzhong 已提交
77 78
    multi_scale_test = getattr(cfg, 'MultiScaleTEST', None)

79
    # define executor
Q
QingshuChen 已提交
80 81 82 83 84
    if cfg.use_gpu:
        place = fluid.CUDAPlace(0)
    elif use_xpu:
        place = fluid.XPUPlace(0)
    else:
85
        place = fluid.CPUPlace()
86 87 88 89 90 91 92 93
    exe = fluid.Executor(place)

    # build program
    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():
94 95
            inputs_def = cfg['EvalReader']['inputs_def']
            feed_vars, loader = model.build_inputs(**inputs_def)
96 97 98 99
            if multi_scale_test is None:
                fetches = model.eval(feed_vars)
            else:
                fetches = model.eval(feed_vars, multi_scale_test)
100
    eval_prog = eval_prog.clone(True)
101

102
    reader = create_reader(cfg.EvalReader, devices_num=1)
103 104
    # When iterable mode, set set_sample_list_generator(reader, place)
    loader.set_sample_list_generator(reader)
105

littletomatodonkey's avatar
littletomatodonkey 已提交
106 107
    dataset = cfg['EvalReader']['dataset']

108 109
    # eval already exists json file
    if FLAGS.json_eval:
110 111 112 113
        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 已提交
114
        json_eval_results(
115
            cfg.metric, json_directory=FLAGS.output_eval, dataset=dataset)
116
        return
117

118
    compile_program = fluid.CompiledProgram(eval_prog).with_data_parallel()
Q
QingshuChen 已提交
119 120
    if use_xpu:
        compile_program = eval_prog
121

122 123
    assert cfg.metric != 'OID', "eval process of OID dataset \
                          is not supported."
124

W
wangguanzhong 已提交
125 126 127
    if cfg.metric == "WIDERFACE":
        raise ValueError("metric type {} does not support in tools/eval.py, "
                         "please use tools/face_eval.py".format(cfg.metric))
128 129
    assert cfg.metric in ['COCO', 'VOC'], \
            "unknown metric type {}".format(cfg.metric)
130
    extra_keys = []
131

132
    if cfg.metric == 'COCO':
W
wangguanzhong 已提交
133
        extra_keys = ['im_info', 'im_id', 'im_shape']
134
    if cfg.metric == 'VOC':
135
        extra_keys = ['gt_bbox', 'gt_class', 'is_difficult']
136 137 138

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

139 140 141 142 143 144
    # 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()

W
wangguanzhong 已提交
145 146 147 148 149 150 151 152
    sub_eval_prog = None
    sub_keys = None
    sub_values = None
    # build sub-program
    if 'Mask' in main_arch and multi_scale_test:
        sub_eval_prog = fluid.Program()
        with fluid.program_guard(sub_eval_prog, startup_prog):
            with fluid.unique_name.guard():
153 154 155
                inputs_def = cfg['EvalReader']['inputs_def']
                inputs_def['mask_branch'] = True
                feed_vars, eval_loader = model.build_inputs(**inputs_def)
W
wangguanzhong 已提交
156 157
                sub_fetches = model.eval(
                    feed_vars, multi_scale_test, mask_branch=True)
158 159
                assert cfg.metric == 'COCO'
                extra_keys = ['im_id', 'im_shape']
W
wangguanzhong 已提交
160 161 162 163
        sub_keys, sub_values, _ = parse_fetches(sub_fetches, sub_eval_prog,
                                                extra_keys)
        sub_eval_prog = sub_eval_prog.clone(True)

164 165 166 167
    # load model
    exe.run(startup_prog)
    if 'weights' in cfg:
        checkpoint.load_params(exe, startup_prog, cfg.weights)
W
wangguanzhong 已提交
168

W
wangguanzhong 已提交
169
    resolution = None
S
sunxl1988 已提交
170
    if 'Mask' in cfg.architecture or cfg.architecture == 'HybridTaskCascade':
W
wangguanzhong 已提交
171
        resolution = model.mask_head.resolution
W
wangguanzhong 已提交
172
    results = eval_run(exe, compile_program, loader, keys, values, cls, cfg,
W
wangguanzhong 已提交
173
                       sub_eval_prog, sub_keys, sub_values, resolution)
174

175
    # evaluation
K
Kaipeng Deng 已提交
176 177
    # 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 已提交
178
    save_only = getattr(cfg, 'save_prediction_only', False)
179 180 181 182 183 184 185 186
    eval_results(
        results,
        cfg.metric,
        cfg.num_classes,
        resolution,
        is_bbox_normalized,
        FLAGS.output_eval,
        map_type,
W
wangguanzhong 已提交
187 188
        dataset=dataset,
        save_only=save_only)
189

W
wangguanzhong 已提交
190

191
if __name__ == '__main__':
192
    enable_static_mode()
193 194
    parser = ArgsParser()
    parser.add_argument(
195 196 197 198 199
        "--json_eval",
        action='store_true',
        default=False,
        help="Whether to re eval with already exists bbox.json or mask.json")
    parser.add_argument(
W
wangguanzhong 已提交
200
        "-f",
201 202 203 204
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation file directory, default is current directory.")
205 206
    FLAGS = parser.parse_args()
    main()