eval.py 3.8 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

15 16 17 18 19 20 21 22 23
import os
import sys
import argparse
import functools
from functools import partial

import numpy as np
import paddle
import paddle.nn as nn
C
Chang Xu 已提交
24 25
from paddle.io import DataLoader
from imagenet_reader import ImageNetDataset
26 27 28 29 30 31 32 33
from paddleslim.auto_compression.config_helpers import load_config as load_slim_config


def argsparser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--config_path',
        type=str,
C
ceci3 已提交
34 35 36 37 38 39 40
        default='./image_classification/configs/eval.yaml',
        help="path of compression strategy config.")
    parser.add_argument(
        '--model_dir',
        type=str,
        default='./MobileNetV1_infer',
        help='model directory')
C
Chang Xu 已提交
41
    return parser
42 43


C
Chang Xu 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56
def eval_reader(data_dir, batch_size, crop_size, resize_size):
    val_reader = ImageNetDataset(
        mode='val',
        data_dir=data_dir,
        crop_size=crop_size,
        resize_size=resize_size)
    val_loader = DataLoader(
        val_reader,
        batch_size=global_config['batch_size'],
        shuffle=False,
        drop_last=False,
        num_workers=0)
    return val_loader
57 58 59 60 61 62 63 64 65 66 67 68 69


def eval():
    devices = paddle.device.get_device().split(':')[0]
    places = paddle.device._convert_to_place(devices)
    exe = paddle.static.Executor(places)
    val_program, feed_target_names, fetch_targets = paddle.static.load_inference_model(
        global_config["model_dir"],
        exe,
        model_filename=global_config["model_filename"],
        params_filename=global_config["params_filename"])
    print('Loaded model from: {}'.format(global_config["model_dir"]))

C
Chang Xu 已提交
70 71 72 73 74
    val_loader = eval_reader(
        data_dir,
        batch_size=global_config['batch_size'],
        crop_size=img_size,
        resize_size=resize_size)
75
    results = []
C
Chang Xu 已提交
76 77 78 79
    print('Evaluating...')
    for batch_id, (image, label) in enumerate(val_loader):
        image = np.array(image)
        label = np.array(label).astype('int64')
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        pred = exe.run(val_program,
                       feed={feed_target_names[0]: image},
                       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])
    result = np.mean(np.array(results), axis=0)
    return result[0]


C
ceci3 已提交
99
def main(args):
100
    global global_config
C
ceci3 已提交
101
    global_config = load_slim_config(args.config_path)
C
Chang Xu 已提交
102

103 104
    global data_dir
    data_dir = global_config['data_dir']
C
ceci3 已提交
105 106
    if args.model_dir != global_config['model_dir']:
        global_config['model_dir'] = args.model_dir
C
Chang Xu 已提交
107 108

    global img_size, resize_size
C
ceci3 已提交
109 110 111 112
    img_size = int(global_config[
        'img_size']) if 'img_size' in global_config else 224
    resize_size = int(global_config[
        'resize_size']) if 'resize_size' in global_config else 256
C
Chang Xu 已提交
113

114 115 116 117 118 119 120 121
    result = eval()
    print('Eval Top1:', result)


if __name__ == '__main__':
    paddle.enable_static()
    parser = argsparser()
    args = parser.parse_args()
C
ceci3 已提交
122
    main(args)