infer.py 4.2 KB
Newer Older
R
ruri 已提交
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.

R
root 已提交
15 16 17
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
R
ruri 已提交
18

19
import os
20 21
import time
import sys
R
ruri 已提交
22 23 24 25 26
import math
import numpy as np
import argparse
import functools

27 28
import paddle
import paddle.fluid as fluid
29
import reader_cv2 as reader
30 31
import models
import utils
R
ruri 已提交
32
from utils.utility import add_arguments,print_arguments, check_gpu
33 34 35

parser = argparse.ArgumentParser(description=__doc__)
# yapf: disable
36 37 38 39 40 41 42
add_arg = functools.partial(add_arguments, argparser=parser)
add_arg('use_gpu',          bool, True,                 "Whether to use GPU or not.")
add_arg('class_dim',        int,  1000,                 "Class number.")
add_arg('image_shape',      str,  "3,224,224",          "Input image size")
add_arg('with_mem_opt',     bool, True,                 "Whether to use memory optimization or not.")
add_arg('pretrained_model', str,  None,                 "Whether to use pretrained model.")
add_arg('model',            str,  "SE_ResNeXt50_32x4d", "Set the network to use.")
43
add_arg('save_inference',   bool, False,                 "Whether to save inference model or not")
44
add_arg('resize_short_size', int, 256,                  "Set resize short size")
45 46 47
# yapf: enable

def infer(args):
48 49 50
    # parameters from arguments
    class_dim = args.class_dim
    model_name = args.model
51
    save_inference = args.save_inference
52 53 54
    pretrained_model = args.pretrained_model
    with_memory_optimization = args.with_mem_opt
    image_shape = [int(m) for m in args.image_shape.split(",")]
55
    model_list = [m for m in dir(models) if "__" not in m]
56 57 58
    assert model_name in model_list, "{} is not in lists: {}".format(args.model,
                                                                     model_list)

59 60
    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')

61 62
    # model definition
    model = models.__dict__[model_name]()
63
    if model_name == "GoogleNet":
64 65 66
        out, _, _ = model.net(input=image, class_dim=class_dim)
    else:
        out = model.net(input=image, class_dim=class_dim)
R
ruri 已提交
67
        out = fluid.layers.softmax(out)
68 69 70

    test_program = fluid.default_main_program().clone(for_test=True)

S
shippingwang 已提交
71
    fetch_list = [out.name]
72
    if with_memory_optimization and not save_inference:
S
shippingwang 已提交
73 74
        fluid.memory_optimize(
            fluid.default_main_program(), skip_opt_set=set(fetch_list))
75 76 77

    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
78
    exe.run(fluid.default_startup_program())
79

R
ruri 已提交
80
    fluid.io.load_persistables(exe, pretrained_model)
81 82 83 84 85 86 87 88 89 90 91
    if save_inference:
        fluid.io.save_inference_model(
                dirname=model_name,
                feeded_var_names=['image'],
                main_program=test_program,
                target_vars=out,
                executor=exe,
                model_filename='model',
                params_filename='params')
        print("model: ",model_name," is already saved")
        exit(0)
92
    test_batch_size = 1
93
    test_reader = paddle.batch(reader.test(settings=args), batch_size=test_batch_size)
94 95 96 97
    feeder = fluid.DataFeeder(place=place, feed_list=[image])

    TOPK = 1
    for batch_id, data in enumerate(test_reader()):
98 99 100 101 102 103 104
        result = exe.run(test_program,
                         fetch_list=fetch_list,
                         feed=feeder.feed(data))
        result = result[0][0]
        pred_label = np.argsort(result)[::-1][:TOPK]
        print("Test-{0}-score: {1}, class {2}"
              .format(batch_id, result[pred_label], pred_label))
105 106 107
        sys.stdout.flush()


108
def main():
109 110
    args = parser.parse_args()
    print_arguments(args)
R
ruri 已提交
111
    check_gpu(args.use_gpu)
112
    infer(args)
113 114 115 116


if __name__ == '__main__':
    main()