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

import os
import sys
import numpy as np
import argparse
import functools

import paddle
W
whs 已提交
22 23
sys.path[0] = os.path.join(
    os.path.dirname("__file__"), os.path.pardir, os.path.pardir)
S
slf12 已提交
24 25 26 27 28 29 30 31 32 33
import imagenet_reader as reader
from utility import add_arguments, print_arguments

parser = argparse.ArgumentParser(description=__doc__)
# yapf: disable
add_arg = functools.partial(add_arguments, argparser=parser)
add_arg('use_gpu',          bool, True,                 "Whether to use GPU or not.")
add_arg('model_path', str,  "./pruning/checkpoints/resnet50/2/eval_model/",                 "Whether to use pretrained model.")
add_arg('model_name', str,  None, "model filename for inference model")
add_arg('params_name', str, None, "params filename for inference model")
G
Guanghua Yu 已提交
34
add_arg('batch_size',       int,  64,                 "Minibatch size.")
S
slf12 已提交
35 36 37 38
# yapf: enable


def eval(args):
B
Bai Yifan 已提交
39 40
    place = paddle.CUDAPlace(0) if args.use_gpu else paddle.CPUPlace()
    exe = paddle.static.Executor(place)
S
slf12 已提交
41

42
    val_program, feed_target_names, fetch_targets = paddle.fluid.io.load_inference_model(
S
slf12 已提交
43 44 45 46
        args.model_path,
        exe,
        model_filename=args.model_name,
        params_filename=args.params_name)
G
Guanghua Yu 已提交
47
    val_dataset = reader.ImageNetDataset(mode='val')
B
Bai Yifan 已提交
48 49 50 51 52

    image = paddle.static.data(
        name='image', shape=[None, 3, 224, 224], dtype='float32')
    label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')

G
Guanghua Yu 已提交
53 54 55 56 57 58 59 60 61
    val_loader = paddle.io.DataLoader(
        val_dataset,
        places=place,
        feed_list=[image, label],
        drop_last=False,
        return_list=True,
        batch_size=args.batch_size,
        use_shared_memory=True,
        shuffle=False)
S
slf12 已提交
62 63

    results = []
G
Guanghua Yu 已提交
64
    for batch_id, data in enumerate(val_loader()):
S
slf12 已提交
65 66 67
        # top1_acc, top5_acc
        if len(feed_target_names) == 1:
            # eval "infer model", which input is image, output is classification probability
G
Guanghua Yu 已提交
68 69
            image = data[0]
            label = data[1]
S
slf12 已提交
70
            pred = exe.run(val_program,
B
Bai Yifan 已提交
71
                           feed={feed_target_names[0]: image},
S
slf12 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
                           fetch_list=fetch_targets)
            pred = np.array(pred[0])
            label = np.array(label)
            sort_array = pred.argsort(axis=1)
            top_1_pred = sort_array[:, -1:][:, ::-1]
            top_1 = np.mean(label == top_1_pred)
            top_5_pred = sort_array[:, -5:][:, ::-1]
            acc_num = 0
            for i in range(len(label)):
                if label[i][0] in top_5_pred[i]:
                    acc_num += 1
            top_5 = float(acc_num) / len(label)
            results.append([top_1, top_5])
        else:
            # eval "eval model", which inputs are image and label, output is top1 and top5 accuracy
G
Guanghua Yu 已提交
87 88
            image = data[0]
            label = data[1]
S
slf12 已提交
89
            result = exe.run(val_program,
B
Bai Yifan 已提交
90 91 92 93
                             feed={
                                 feed_target_names[0]: image,
                                 feed_target_names[1]: label
                             },
S
slf12 已提交
94 95 96
                             fetch_list=fetch_targets)
            result = [np.mean(r) for r in result]
            results.append(result)
G
Guanghua Yu 已提交
97 98
        if batch_id % 100 == 0:
            print('Eval iter: ', batch_id)
S
slf12 已提交
99 100 101 102 103 104
    result = np.mean(np.array(results), axis=0)
    print("top1_acc/top5_acc= {}".format(result))
    sys.stdout.flush()


def main():
105
    paddle.enable_static()
S
slf12 已提交
106 107 108 109 110 111 112
    args = parser.parse_args()
    print_arguments(args)
    eval(args)


if __name__ == '__main__':
    main()