infer.py 5.0 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
R
ruri 已提交
29
import reader
30
import models
R
ruri 已提交
31
from utils import *
32 33 34

parser = argparse.ArgumentParser(description=__doc__)
# yapf: disable
35
add_arg = functools.partial(add_arguments, argparser=parser)
R
ruri 已提交
36
add_arg('data_dir',         str,  "./data/ILSVRC2012/", "The ImageNet data")
37 38 39
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")
R
ruri 已提交
40 41 42 43 44 45 46 47 48 49 50
parser.add_argument("--pretrained_model", default=None, required=True, type=str, help="The path to load pretrained model")
add_arg('model',            str,  "ResNet50",            "Set the network to use.")
add_arg('save_inference',   bool, False,                "Whether to save inference model or not")
add_arg('resize_short_size',int,  256,                  "Set resize short size")
add_arg('reader_thread',    int,  1,                    "The number of multi thread reader")
add_arg('reader_buf_size',  int,  2048,                 "The buf size of multi thread reader")
parser.add_argument('--image_mean', nargs='+', type=float, default=[0.485, 0.456, 0.406], help="The mean of input image data")
parser.add_argument('--image_std', nargs='+', type=float, default=[0.229, 0.224, 0.225], help="The std of input image data")
add_arg('crop_size',        int,  224,                  "The value of crop size")
add_arg('topk',             int,  1,                    "topk")
add_arg('label_path',            str,  "./utils/tools/readable_label.txt", "readable label filepath")
51 52
# yapf: enable

53

54
def infer(args):
55
    image_shape = [int(m) for m in args.image_shape.split(",")]
56
    model_list = [m for m in dir(models) if "__" not in m]
R
ruri 已提交
57
    assert args.model in model_list, "{} is not in lists: {}".format(args.model,
58
                                                                     model_list)
R
ruri 已提交
59 60
    assert os.path.isdir(args.pretrained_model
                         ), "please load right pretrained model path for infer"
61
    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')
R
ruri 已提交
62 63 64
    model = models.__dict__[args.model]()
    if args.model == "GoogLeNet":
        out, _, _ = model.net(input=image, class_dim=args.class_dim)
65
    else:
R
ruri 已提交
66
        out = model.net(input=image, class_dim=args.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 73 74

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

R
ruri 已提交
77 78
    fluid.io.load_persistables(exe, args.pretrained_model)
    if args.save_inference:
79
        fluid.io.save_inference_model(
R
ruri 已提交
80
            dirname=args.model,
81 82 83 84 85 86
            feeded_var_names=['image'],
            main_program=test_program,
            target_vars=out,
            executor=exe,
            model_filename='model',
            params_filename='params')
R
ruri 已提交
87
        print("model: ", args.model, " is already saved")
88
        exit(0)
89

R
ruri 已提交
90 91 92
    test_batch_size = 1
    test_reader = paddle.batch(
        reader.test(settings=args), batch_size=test_batch_size)
93 94
    feeder = fluid.DataFeeder(place=place, feed_list=[image])

R
ruri 已提交
95 96 97 98 99 100 101 102 103
    TOPK = args.topk
    assert os.path.exists(args.label_path), "Index file doesn't exist!"
    f = open(args.label_path)
    label_dict = {}
    for item in f.readlines():
        key = item.split(" ")[0]
        value = [l.replace("\n", "") for l in item.split(" ")[1:]]
        label_dict[key] = value

104
    for batch_id, data in enumerate(test_reader()):
105 106 107 108 109
        result = exe.run(test_program,
                         fetch_list=fetch_list,
                         feed=feeder.feed(data))
        result = result[0][0]
        pred_label = np.argsort(result)[::-1][:TOPK]
R
ruri 已提交
110 111 112 113 114
        readable_pred_label = []
        for label in pred_label:
            readable_pred_label.append(label_dict[str(label)])
        print("Test-{0}-score: {1}, class{2} {3}".format(batch_id, result[
            pred_label], pred_label, readable_pred_label))
115 116 117
        sys.stdout.flush()


118
def main():
119 120
    args = parser.parse_args()
    print_arguments(args)
R
ruri 已提交
121
    check_gpu()
122
    infer(args)
123 124 125 126


if __name__ == '__main__':
    main()