infer.py 3.5 KB
Newer Older
R
root 已提交
1 2 3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
4 5
import os
import numpy as np
6 7
import time
import sys
8 9 10
import paddle
import paddle.fluid as fluid
import reader
11 12 13 14
import argparse
import functools
from utility import add_arguments, print_arguments
import math
15 16 17

parser = argparse.ArgumentParser(description=__doc__)
# yapf: disable
18 19 20 21 22 23 24
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.")
25
add_arg('model_category',   str,  "models_name",        "Whether to use models_name or not, valid value:'models','models_name'." )
26 27
# yapf: enable

28 29 30 31 32 33 34 35 36 37

def set_models(model_category):
    global models
    assert model_category in ["models", "models_name"
                              ], "{} is not in lists: {}".format(
                                  model_category, ["models", "models_name"])
    if model_category == "models_name":
        import models_name as models
    else:
        import models as models
38

39 40

def infer(args):
41 42 43 44 45 46
    # parameters from arguments
    class_dim = args.class_dim
    model_name = args.model
    pretrained_model = args.pretrained_model
    with_memory_optimization = args.with_mem_opt
    image_shape = [int(m) for m in args.image_shape.split(",")]
47
    model_list = [m for m in dir(models) if "__" not in m]
48 49 50
    assert model_name in model_list, "{} is not in lists: {}".format(args.model,
                                                                     model_list)

51 52
    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')

53 54 55 56 57 58 59 60 61
    # model definition
    model = models.__dict__[model_name]()
    if model_name is "GoogleNet":
        out, _, _ = model.net(input=image, class_dim=class_dim)
    else:
        out = model.net(input=image, class_dim=class_dim)

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

S
shippingwang 已提交
62
    fetch_list = [out.name]
63
    if with_memory_optimization:
S
shippingwang 已提交
64 65
        fluid.memory_optimize(
            fluid.default_main_program(), skip_opt_set=set(fetch_list))
66 67 68

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

71
    if pretrained_model:
72

73 74
        def if_exist(var):
            return os.path.exists(os.path.join(pretrained_model, var.name))
75

76
        fluid.io.load_vars(exe, pretrained_model, predicate=if_exist)
77

78 79
    test_batch_size = 1
    test_reader = paddle.batch(reader.test(), batch_size=test_batch_size)
80 81 82 83
    feeder = fluid.DataFeeder(place=place, feed_list=[image])

    TOPK = 1
    for batch_id, data in enumerate(test_reader()):
84 85 86 87 88 89 90
        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))
91 92 93
        sys.stdout.flush()


94
def main():
95 96
    args = parser.parse_args()
    print_arguments(args)
97
    set_models(args.model_category)
98
    infer(args)
99 100 101 102


if __name__ == '__main__':
    main()