train.py 4.8 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

W
Wang,Jeff 已提交
17 18 19 20
import paddle
import paddle.fluid as fluid
import numpy
import sys
L
liaogang 已提交
21

Y
Yu Yang 已提交
22 23 24 25 26 27 28 29 30 31
try:
    from paddle.fluid.contrib.trainer import *
    from paddle.fluid.contrib.inferencer import *
except ImportError:
    print(
        "In the fluid 1.0, the trainer and inferencer are moving to paddle.fluid.contrib",
        file=sys.stderr)
    from paddle.fluid.trainer import *
    from paddle.fluid.inferencer import *

L
liaogang 已提交
32 33
from vgg import vgg_bn_drop
from resnet import resnet_cifar10
L
liaogang 已提交
34 35


W
Wang,Jeff 已提交
36
def inference_network():
W
Wang,Jeff 已提交
37
    # The image is 32 * 32 with RGB representation.
W
Wang,Jeff 已提交
38 39
    data_shape = [3, 32, 32]
    images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32')
W
Wang,Jeff 已提交
40

W
Wang,Jeff 已提交
41
    predict = resnet_cifar10(images, 32)
W
Wang,Jeff 已提交
42
    # predict = vgg_bn_drop(images) # un-comment to use vgg net
W
Wang,Jeff 已提交
43
    return predict
H
Helin Wang 已提交
44

L
liaogang 已提交
45

W
Wang,Jeff 已提交
46 47 48 49 50 51 52
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)
    return [avg_cost, accuracy]
L
liaogang 已提交
53 54


55 56 57 58
def optimizer_program():
    return fluid.optimizer.Adam(learning_rate=0.001)


W
Wang,Jeff 已提交
59 60 61
def train(use_cuda, train_program, params_dirname):
    BATCH_SIZE = 128
    EPOCH_NUM = 2
L
liaogang 已提交
62

W
Wang,Jeff 已提交
63 64 65
    train_reader = paddle.batch(
        paddle.reader.shuffle(paddle.dataset.cifar.train10(), buf_size=50000),
        batch_size=BATCH_SIZE)
L
liaogang 已提交
66

W
Wang,Jeff 已提交
67 68
    test_reader = paddle.batch(
        paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE)
L
liaogang 已提交
69 70

    def event_handler(event):
Y
yuyang 已提交
71
        if isinstance(event, EndStepEvent):
W
Wang,Jeff 已提交
72
            if event.step % 100 == 0:
73
                print("\nPass %d, Batch %d, Cost %f, Acc %f" %
W
Wang,Jeff 已提交
74 75
                      (event.step, event.epoch, event.metrics[0],
                       event.metrics[1]))
L
liaogang 已提交
76 77 78
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
W
Wang,Jeff 已提交
79

Y
yuyang 已提交
80
        if isinstance(event, EndEpochEvent):
W
Wang,Jeff 已提交
81 82 83
            avg_cost, accuracy = trainer.test(
                reader=test_reader, feed_order=['pixel', 'label'])

84 85
            print('\nTest with Pass {0}, Loss {1:2.2}, Acc {2:2.2}'.format(
                event.epoch, avg_cost, accuracy))
W
Wang,Jeff 已提交
86 87 88 89
            if params_dirname is not None:
                trainer.save_params(params_dirname)

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
Y
yuyang 已提交
90
    trainer = Trainer(
91
        train_func=train_program, optimizer_func=optimizer_program, place=place)
F
fengjiayi 已提交
92

L
liaogang 已提交
93
    trainer.train(
W
Wang,Jeff 已提交
94 95
        reader=train_reader,
        num_epochs=EPOCH_NUM,
L
liaogang 已提交
96
        event_handler=event_handler,
W
Wang,Jeff 已提交
97 98 99 100 101
        feed_order=['pixel', 'label'])


def infer(use_cuda, inference_program, params_dirname=None):
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
Y
yuyang 已提交
102
    inferencer = Inferencer(
W
Wang,Jeff 已提交
103
        infer_func=inference_program, param_path=params_dirname, place=place)
L
liaogang 已提交
104

W
Wang,Jeff 已提交
105
    # Prepare testing data. 
106 107
    from PIL import Image
    import numpy as np
L
liaogang 已提交
108
    import os
109 110 111 112

    def load_image(file):
        im = Image.open(file)
        im = im.resize((32, 32), Image.ANTIALIAS)
W
Wang,Jeff 已提交
113

Q
qingqing01 已提交
114
        im = np.array(im).astype(np.float32)
W
Wang,Jeff 已提交
115
        # The storage order of the loaded image is W(width),
Q
qingqing01 已提交
116 117
        # H(height), C(channel). PaddlePaddle requires
        # the CHW order, so transpose them.
Q
qingqing01 已提交
118
        im = im.transpose((2, 0, 1))  # CHW
119
        im = im / 255.0
W
Wang,Jeff 已提交
120 121

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

L
liaogang 已提交
125
    cur_dir = os.path.dirname(os.path.realpath(__file__))
W
Wang,Jeff 已提交
126
    img = load_image(cur_dir + '/image/dog.png')
W
Wang,Jeff 已提交
127 128

    # inference
J
JiabinYang 已提交
129
    results = inferencer.infer({'pixel': img})
W
Wang,Jeff 已提交
130

131 132 133 134 135
    label_list = [
        "airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse",
        "ship", "truck"
    ]
    print("infer results: %s" % label_list[np.argmax(results[0])])
W
Wang,Jeff 已提交
136 137 138 139 140 141


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

W
Wang,Jeff 已提交
143 144 145 146
    train(
        use_cuda=use_cuda,
        train_program=train_network,
        params_dirname=save_path)
Q
qingqing01 已提交
147

W
Wang,Jeff 已提交
148 149 150 151
    infer(
        use_cuda=use_cuda,
        inference_program=inference_network,
        params_dirname=save_path)
152

L
liaogang 已提交
153 154

if __name__ == '__main__':
W
Wang,Jeff 已提交
155 156
    # For demo purpose, the training runs on CPU
    # Please change accordingly.
W
Wang,Jeff 已提交
157
    main(use_cuda=False)