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

W
wangguanzhong 已提交
21

22 23 24 25 26
def set_paddle_flags(**kwargs):
    for key, value in kwargs.items():
        if os.environ.get(key, None) is None:
            os.environ[key] = str(value)

W
wangguanzhong 已提交
27

28 29 30 31 32 33
# NOTE(paddle-dev): All of these flags should be set before
# `import paddle`. Otherwise, it would not take any effect.
set_paddle_flags(
    FLAGS_eager_delete_tensor_gb=0,  # enable GC to save memory
)

34 35
import paddle.fluid as fluid

36
from ppdet.utils.eval_utils import parse_fetches, eval_run, eval_results, json_eval_results
37
import ppdet.utils.checkpoint as checkpoint
W
wangguanzhong 已提交
38
from ppdet.utils.check import check_gpu, check_version
39 40 41

from ppdet.data.reader import create_reader

42
from ppdet.core.workspace import load_config, merge_config, create
Y
Yang Zhang 已提交
43
from ppdet.utils.cli import ArgsParser
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

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
    """
    cfg = load_config(FLAGS.config)
    if 'architecture' in cfg:
        main_arch = cfg.architecture
    else:
        raise ValueError("'architecture' not specified in config file.")

    merge_config(FLAGS.opt)
62 63
    # check if set use_gpu=True in paddlepaddle cpu version
    check_gpu(cfg.use_gpu)
W
wangguanzhong 已提交
64 65
    # check if paddlepaddle version is satisfied
    check_version()
66

W
wangguanzhong 已提交
67 68
    multi_scale_test = getattr(cfg, 'MultiScaleTEST', None)

69 70 71 72 73 74 75 76 77 78
    # define executor
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
    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():
79 80
            inputs_def = cfg['EvalReader']['inputs_def']
            feed_vars, loader = model.build_inputs(**inputs_def)
81 82 83 84
            if multi_scale_test is None:
                fetches = model.eval(feed_vars)
            else:
                fetches = model.eval(feed_vars, multi_scale_test)
85
    eval_prog = eval_prog.clone(True)
86 87

    reader = create_reader(cfg.EvalReader)
W
wangguanzhong 已提交
88
    loader.set_sample_list_generator(reader, place)
89

littletomatodonkey's avatar
littletomatodonkey 已提交
90 91
    dataset = cfg['EvalReader']['dataset']

92 93
    # eval already exists json file
    if FLAGS.json_eval:
94 95 96 97
        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 已提交
98
        json_eval_results(
99
            cfg.metric, json_directory=FLAGS.output_eval, dataset=dataset)
100
        return
101 102 103

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

105 106
    assert cfg.metric != 'OID', "eval process of OID dataset \
                          is not supported."
107

W
wangguanzhong 已提交
108 109 110
    if cfg.metric == "WIDERFACE":
        raise ValueError("metric type {} does not support in tools/eval.py, "
                         "please use tools/face_eval.py".format(cfg.metric))
111 112
    assert cfg.metric in ['COCO', 'VOC'], \
            "unknown metric type {}".format(cfg.metric)
113
    extra_keys = []
114

115
    if cfg.metric == 'COCO':
116
        extra_keys = ['im_info', 'im_id', 'im_shape']
117
    if cfg.metric == 'VOC':
118
        extra_keys = ['gt_bbox', 'gt_class', 'is_difficult']
119 120 121

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

122 123 124 125 126 127
    # 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 已提交
128 129 130 131 132 133 134 135
    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():
136 137 138
                inputs_def = cfg['EvalReader']['inputs_def']
                inputs_def['mask_branch'] = True
                feed_vars, eval_loader = model.build_inputs(**inputs_def)
W
wangguanzhong 已提交
139 140
                sub_fetches = model.eval(
                    feed_vars, multi_scale_test, mask_branch=True)
141 142
                assert cfg.metric == 'COCO'
                extra_keys = ['im_id', 'im_shape']
W
wangguanzhong 已提交
143 144 145 146
        sub_keys, sub_values, _ = parse_fetches(sub_fetches, sub_eval_prog,
                                                extra_keys)
        sub_eval_prog = sub_eval_prog.clone(True)

147 148 149 150 151 152 153
    #if 'weights' in cfg:
    #    checkpoint.load_params(exe, sub_eval_prog, cfg.weights)

    # load model
    exe.run(startup_prog)
    if 'weights' in cfg:
        checkpoint.load_params(exe, startup_prog, cfg.weights)
W
wangguanzhong 已提交
154

W
wangguanzhong 已提交
155 156 157
    resolution = None
    if 'Mask' in cfg.architecture:
        resolution = model.mask_head.resolution
W
wangguanzhong 已提交
158
    results = eval_run(exe, compile_program, loader, keys, values, cls, cfg,
W
wangguanzhong 已提交
159
                       sub_eval_prog, sub_keys, sub_values, resolution)
160

161
    #print(cfg['EvalReader']['dataset'].__dict__)
162
    # evaluation
K
Kaipeng Deng 已提交
163 164
    # 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'
165 166 167 168 169 170 171 172 173
    eval_results(
        results,
        cfg.metric,
        cfg.num_classes,
        resolution,
        is_bbox_normalized,
        FLAGS.output_eval,
        map_type,
        dataset=dataset)
174

W
wangguanzhong 已提交
175

176 177 178
if __name__ == '__main__':
    parser = ArgsParser()
    parser.add_argument(
179 180 181 182 183
        "--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 已提交
184
        "-f",
185 186 187 188
        "--output_eval",
        default=None,
        type=str,
        help="Evaluation file directory, default is current directory.")
189 190
    FLAGS = parser.parse_args()
    main()