train.py 7.7 KB
Newer Older
L
liaogang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2016 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

W
Wang,Jeff 已提交
15
from __future__ import print_function
L
liaogang 已提交
16

17
import os
u010070587's avatar
u010070587 已提交
18
import argparse
W
Wang,Jeff 已提交
19 20 21 22
import paddle
import paddle.fluid as fluid
import numpy
import sys
L
liaogang 已提交
23 24
from vgg import vgg_bn_drop
from resnet import resnet_cifar10
L
liaogang 已提交
25 26


u010070587's avatar
u010070587 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40
def parse_args():
    parser = argparse.ArgumentParser("image_classification")
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help='If set, run the task with continuous evaluation logs.')
    parser.add_argument(
        '--use_gpu', type=bool, default=0, help='whether to use gpu')
    parser.add_argument(
        '--num_epochs', type=int, default=1, help='number of epoch')
    args = parser.parse_args()
    return args


W
Wang,Jeff 已提交
41
def inference_network():
W
Wang,Jeff 已提交
42
    # The image is 32 * 32 with RGB representation.
R
ruri 已提交
43 44
    data_shape = [None, 3, 32, 32]
    images = fluid.data(name='pixel', shape=data_shape, dtype='float32')
W
Wang,Jeff 已提交
45

W
Wang,Jeff 已提交
46
    predict = resnet_cifar10(images, 32)
W
Wang,Jeff 已提交
47
    # predict = vgg_bn_drop(images) # un-comment to use vgg net
W
Wang,Jeff 已提交
48
    return predict
H
Helin Wang 已提交
49

L
liaogang 已提交
50

51
def train_network(predict):
R
ruri 已提交
52
    label = fluid.data(name='label', shape=[None, 1], dtype='int64')
W
Wang,Jeff 已提交
53 54 55 56
    cost = fluid.layers.cross_entropy(input=predict, label=label)
    avg_cost = fluid.layers.mean(cost)
    accuracy = fluid.layers.accuracy(input=predict, label=label)
    return [avg_cost, accuracy]
L
liaogang 已提交
57 58


59 60 61 62
def optimizer_program():
    return fluid.optimizer.Adam(learning_rate=0.001)


63 64
def train(use_cuda, params_dirname):
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
W
Wang,Jeff 已提交
65
    BATCH_SIZE = 128
L
liaogang 已提交
66

u010070587's avatar
u010070587 已提交
67 68 69 70 71 72 73 74 75 76 77 78
    if args.enable_ce:
        train_reader = paddle.batch(
            paddle.dataset.cifar.train10(), batch_size=BATCH_SIZE)
        test_reader = paddle.batch(
            paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE)
    else:
        test_reader = paddle.batch(
            paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE)
        train_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.cifar.train10(), buf_size=128 * 100),
            batch_size=BATCH_SIZE)
L
liaogang 已提交
79

80
    feed_order = ['pixel', 'label']
W
Wang,Jeff 已提交
81

82
    main_program = fluid.default_main_program()
u010070587's avatar
u010070587 已提交
83 84 85 86 87
    start_program = fluid.default_startup_program()

    if args.enable_ce:
        main_program.random_seed = 90
        start_program.random_seed = 90
W
Wang,Jeff 已提交
88

89 90 91 92 93 94 95 96 97 98
    predict = inference_network()
    avg_cost, acc = train_network(predict)

    # Test program
    test_program = main_program.clone(for_test=True)
    optimizer = optimizer_program()
    optimizer.minimize(avg_cost)

    exe = fluid.Executor(place)

u010070587's avatar
u010070587 已提交
99
    EPOCH_NUM = args.num_epochs
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

    # For training test cost
    def train_test(program, reader):
        count = 0
        feed_var_list = [
            program.global_block().var(var_name) for var_name in feed_order
        ]
        feeder_test = fluid.DataFeeder(feed_list=feed_var_list, place=place)
        test_exe = fluid.Executor(place)
        accumulated = len([avg_cost, acc]) * [0]
        for tid, test_data in enumerate(reader()):
            avg_cost_np = test_exe.run(
                program=program,
                feed=feeder_test.feed(test_data),
                fetch_list=[avg_cost, acc])
            accumulated = [
                x[0] + x[1][0] for x in zip(accumulated, avg_cost_np)
            ]
            count += 1
        return [x / count for x in accumulated]

    # main train loop.
    def train_loop():
        feed_var_list_loop = [
            main_program.global_block().var(var_name) for var_name in feed_order
        ]
        feeder = fluid.DataFeeder(feed_list=feed_var_list_loop, place=place)
u010070587's avatar
u010070587 已提交
127
        exe.run(start_program)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

        step = 0
        for pass_id in range(EPOCH_NUM):
            for step_id, data_train in enumerate(train_reader()):
                avg_loss_value = exe.run(
                    main_program,
                    feed=feeder.feed(data_train),
                    fetch_list=[avg_cost, acc])
                if step_id % 100 == 0:
                    print("\nPass %d, Batch %d, Cost %f, Acc %f" % (
                        step_id, pass_id, avg_loss_value[0], avg_loss_value[1]))
                else:
                    sys.stdout.write('.')
                    sys.stdout.flush()
                step += 1

            avg_cost_test, accuracy_test = train_test(
                test_program, reader=test_reader)
146
            print('\nTest with Pass {0}, Loss {1:2.2}, Acc {2:2.2}'.format(
147
                pass_id, avg_cost_test, accuracy_test))
W
Wang,Jeff 已提交
148

149 150 151
            if params_dirname is not None:
                fluid.io.save_inference_model(params_dirname, ["pixel"],
                                              [predict], exe)
W
Wang,Jeff 已提交
152

u010070587's avatar
u010070587 已提交
153 154 155 156 157 158
            if args.enable_ce and pass_id == EPOCH_NUM - 1:
                print("kpis\ttrain_cost\t%f" % avg_loss_value[0])
                print("kpis\ttrain_acc\t%f" % avg_loss_value[1])
                print("kpis\ttest_cost\t%f" % avg_cost_test)
                print("kpis\ttest_acc\t%f" % accuracy_test)

159
    train_loop()
W
Wang,Jeff 已提交
160

L
liaogang 已提交
161

162
def infer(use_cuda, params_dirname=None):
163
    from PIL import Image
164 165 166
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)
    inference_scope = fluid.core.Scope()
167

168 169
    def load_image(infer_file):
        im = Image.open(infer_file)
170
        im = im.resize((32, 32), Image.ANTIALIAS)
W
Wang,Jeff 已提交
171

172
        im = numpy.array(im).astype(numpy.float32)
W
Wang,Jeff 已提交
173
        # The storage order of the loaded image is W(width),
Q
qingqing01 已提交
174 175
        # H(height), C(channel). PaddlePaddle requires
        # the CHW order, so transpose them.
Q
qingqing01 已提交
176
        im = im.transpose((2, 0, 1))  # CHW
177
        im = im / 255.0
W
Wang,Jeff 已提交
178 179

        # Add one dimension to mimic the list format.
W
Wang,Jeff 已提交
180
        im = numpy.expand_dims(im, axis=0)
181 182
        return im

L
liaogang 已提交
183
    cur_dir = os.path.dirname(os.path.realpath(__file__))
W
Wang,Jeff 已提交
184
    img = load_image(cur_dir + '/image/dog.png')
W
Wang,Jeff 已提交
185

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
        # the feed_target_names (the names of variables that will be feeded
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
        [inference_program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(params_dirname, exe)

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
        results = exe.run(
            inference_program,
            feed={feed_target_names[0]: img},
            fetch_list=fetch_targets)

        # infer label
        label_list = [
            "airplane", "automobile", "bird", "cat", "deer", "dog", "frog",
            "horse", "ship", "truck"
        ]

        print("infer results: %s" % label_list[numpy.argmax(results[0])])
W
Wang,Jeff 已提交
208 209 210 211 212 213


def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return
    save_path = "image_classification_resnet.inference.model"
214

215
    train(use_cuda=use_cuda, params_dirname=save_path)
Q
qingqing01 已提交
216

217
    infer(use_cuda=use_cuda, params_dirname=save_path)
218

L
liaogang 已提交
219 220

if __name__ == '__main__':
W
Wang,Jeff 已提交
221 222
    # For demo purpose, the training runs on CPU
    # Please change accordingly.
u010070587's avatar
u010070587 已提交
223 224 225
    args = parse_args()
    use_cuda = args.use_gpu
    main(use_cuda)