test_image_classification_vgg.py 5.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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
from __future__ import print_function

17 18
import paddle
import paddle.fluid as fluid
19
import paddle.fluid.core as core
20
import numpy
21
import six
22
import os
23
import cifar10_small_test_set
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49


def vgg16_bn_drop(input):
    def conv_block(input, num_filter, groups, dropouts):
        return fluid.nets.img_conv_group(
            input=input,
            pool_size=2,
            pool_stride=2,
            conv_num_filter=[num_filter] * groups,
            conv_filter_size=3,
            conv_act='relu',
            conv_with_batchnorm=True,
            conv_batchnorm_drop_rate=dropouts,
            pool_type='max')

    conv1 = conv_block(input, 64, 2, [0.3, 0])
    conv2 = conv_block(conv1, 128, 2, [0.4, 0])
    conv3 = conv_block(conv2, 256, 3, [0.4, 0.4, 0])
    conv4 = conv_block(conv3, 512, 3, [0.4, 0.4, 0])
    conv5 = conv_block(conv4, 512, 3, [0.4, 0.4, 0])

    drop = fluid.layers.dropout(x=conv5, dropout_prob=0.5)
    fc1 = fluid.layers.fc(input=drop, size=4096, act=None)
    bn = fluid.layers.batch_norm(input=fc1, act='relu')
    drop2 = fluid.layers.dropout(x=bn, dropout_prob=0.5)
    fc2 = fluid.layers.fc(input=drop2, size=4096, act=None)
50 51
    predict = fluid.layers.fc(input=fc2, size=10, act='softmax')
    return predict
52 53 54 55 56


def inference_network():
    data_shape = [3, 32, 32]
    images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32')
57
    predict = vgg16_bn_drop(images)
58 59 60 61 62 63 64 65 66
    return predict


def train_network():
    predict = inference_network()
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')
    cost = fluid.layers.cross_entropy(input=predict, label=label)
    avg_cost = fluid.layers.mean(cost)
    accuracy = fluid.layers.accuracy(input=predict, label=label)
67
    return [avg_cost, accuracy]
68 69


70 71 72 73
def optimizer_func():
    return fluid.optimizer.Adam(learning_rate=0.001)


74
def train(use_cuda, train_program, parallel, params_dirname):
75 76 77
    BATCH_SIZE = 128
    train_reader = paddle.batch(
        paddle.reader.shuffle(
78
            cifar10_small_test_set.train10(batch_size=10), buf_size=128 * 10),
C
chengduoZH 已提交
79 80
        batch_size=BATCH_SIZE,
        drop_last=False)
81 82

    test_reader = paddle.batch(
C
chengduoZH 已提交
83
        paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE, drop_last=False)
84 85

    def event_handler(event):
86 87 88
        if isinstance(event, fluid.EndStepEvent):
            avg_cost, accuracy = trainer.test(
                reader=test_reader, feed_order=['pixel', 'label'])
89

90
            print('Loss {0:2.2}, Acc {1:2.2}'.format(avg_cost, accuracy))
91

92
            if accuracy > 0.01:  # Low threshold for speeding up CI
93 94
                if params_dirname is not None:
                    trainer.save_params(params_dirname)
95
                return
96 97 98

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    trainer = fluid.Trainer(
99 100 101 102
        train_func=train_program,
        place=place,
        optimizer_func=optimizer_func,
        parallel=parallel)
103

104 105 106 107 108 109
    trainer.train(
        reader=train_reader,
        num_epochs=1,
        event_handler=event_handler,
        feed_order=['pixel', 'label'])

110

111
def infer(use_cuda, inference_program, parallel, params_dirname=None):
112
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
113
    inferencer = fluid.Inferencer(
114 115 116 117
        infer_func=inference_program,
        param_path=params_dirname,
        place=place,
        parallel=parallel)
118 119 120 121 122 123 124

    # The input's dimension of conv should be 4-D or 5-D.
    # Use normilized image pixels as input data, which should be in the range
    # [0, 1.0].
    tensor_img = numpy.random.rand(1, 3, 32, 32).astype("float32")
    results = inferencer.infer({'pixel': tensor_img})

125
    print("infer results: ", results)
126 127


128
def main(use_cuda, parallel):
129
    save_path = "image_classification_vgg.inference.model"
130

131
    os.environ['CPU_NUM'] = str(4)
M
minqiyang 已提交
132
    train(
133 134
        use_cuda=use_cuda,
        train_program=train_network,
135 136
        params_dirname=save_path,
        parallel=parallel)
137

138 139 140 141 142
    # FIXME(zcd): in the inference stage, the number of
    # input data is one, it is not appropriate to use parallel.
    if parallel and use_cuda:
        return
    os.environ['CPU_NUM'] = str(1)
143 144 145
    infer(
        use_cuda=use_cuda,
        inference_program=inference_network,
146 147
        params_dirname=save_path,
        parallel=parallel)
148 149 150 151


if __name__ == '__main__':
    for use_cuda in (False, True):
152 153 154
        for parallel in (False, True):
            if use_cuda and not core.is_compiled_with_cuda():
                continue
M
minqiyang 已提交
155 156
            # TODO(minqiyang): remove this line after fixing the deletion
            # order problem of Scope in ParallelExecutor in manylinux
M
minqiyang 已提交
157 158
            if six.PY2:
                main(use_cuda=use_cuda, parallel=parallel)