eval.py 3.1 KB
Newer Older
K
kbChen 已提交
1 2 3 4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

5 6
import os
import sys
K
kbChen 已提交
7 8 9 10 11
import math
import time
import argparse
import functools
import numpy as np
12 13 14
import paddle
import paddle.fluid as fluid
import models
K
kbChen 已提交
15
import reader
16
from utility import add_arguments, print_arguments
K
kbChen 已提交
17
from utility import fmt_time, recall_topk
18 19 20 21

# yapf: disable
parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
K
kbChen 已提交
22 23 24 25 26 27 28
add_arg('model', str, "ResNet50", "Set the network to use.")
add_arg('embedding_size', int, 0, "Embedding size.")
add_arg('batch_size', int, 10, "Minibatch size.")
add_arg('image_shape', str, "3,224,224", "Input image size.")
add_arg('use_gpu', bool, True, "Whether to use GPU or not.")
add_arg('with_mem_opt', bool, False, "Whether to use memory optimization or not.")
add_arg('pretrained_model', str, None, "Whether to use pretrained model.")
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
# yapf: enable

model_list = [m for m in dir(models) if "__" not in m]


def eval(args):
    # parameters from arguments
    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(",")]

    assert model_name in model_list, "{} is not in lists: {}".format(args.model,
                                                                     model_list)

    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')

    # model definition
    model = models.__dict__[model_name]()
K
kbChen 已提交
49 50
    out = model.net(input=image, embedding_size=args.embedding_size)

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    test_program = fluid.default_main_program().clone(for_test=True)

    if with_memory_optimization:
        fluid.memory_optimize(fluid.default_main_program())

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

    if pretrained_model:

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

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

K
kbChen 已提交
67
    test_reader = paddle.batch(reader.test(args), batch_size=args.batch_size, drop_last=False)
68 69
    feeder = fluid.DataFeeder(place=place, feed_list=[image, label])

K
kbChen 已提交
70
    fetch_list = [out.name]
71

K
kbChen 已提交
72
    f, l = [], []
K
kbChen 已提交
73
    for batch_id, data in enumerate(test_reader()):
74
        t1 = time.time()
K
kbChen 已提交
75
        [feas] = exe.run(test_program, fetch_list=fetch_list, feed=feeder.feed(data))
K
kbChen 已提交
76
        label = np.asarray([x[1] for x in data])
77 78 79 80 81
        f.append(feas)
        l.append(label)

        t2 = time.time()
        period = t2 - t1
K
kbChen 已提交
82
        if batch_id % 20 == 0:
K
kbChen 已提交
83 84
            print("[%s] testbatch %d, time %2.2f sec" % \
                    (fmt_time(), batch_id, period))
85 86

    f = np.vstack(f)
K
kbChen 已提交
87
    l = np.hstack(l)
88
    recall = recall_topk(f, l, k=1)
K
kbChen 已提交
89
    print("[%s] End test %d, test_recall %.5f" % (fmt_time(), len(f), recall))
90 91 92 93 94 95 96 97 98 99 100
    sys.stdout.flush()


def main():
    args = parser.parse_args()
    print_arguments(args)
    eval(args)


if __name__ == '__main__':
    main()