train.py 7.1 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
W
Wang,Jeff 已提交
18 19 20 21
import paddle
import paddle.fluid as fluid
import numpy
import sys
L
liaogang 已提交
22 23
from vgg import vgg_bn_drop
from resnet import resnet_cifar10
L
liaogang 已提交
24 25


W
Wang,Jeff 已提交
26
def inference_network():
W
Wang,Jeff 已提交
27
    # The image is 32 * 32 with RGB representation.
W
Wang,Jeff 已提交
28 29
    data_shape = [3, 32, 32]
    images = fluid.layers.data(name='pixel', shape=data_shape, dtype='float32')
W
Wang,Jeff 已提交
30

W
Wang,Jeff 已提交
31
    predict = resnet_cifar10(images, 32)
W
Wang,Jeff 已提交
32
    # predict = vgg_bn_drop(images) # un-comment to use vgg net
W
Wang,Jeff 已提交
33
    return predict
H
Helin Wang 已提交
34

L
liaogang 已提交
35

36
def train_network(predict):
W
Wang,Jeff 已提交
37 38 39 40 41
    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 已提交
42 43


44 45 46 47
def optimizer_program():
    return fluid.optimizer.Adam(learning_rate=0.001)


48 49
def train(use_cuda, params_dirname):
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
W
Wang,Jeff 已提交
50 51
    BATCH_SIZE = 128
    train_reader = paddle.batch(
52 53
        paddle.reader.shuffle(
            paddle.dataset.cifar.train10(), buf_size=128 * 100),
W
Wang,Jeff 已提交
54
        batch_size=BATCH_SIZE)
L
liaogang 已提交
55

W
Wang,Jeff 已提交
56 57
    test_reader = paddle.batch(
        paddle.dataset.cifar.test10(), batch_size=BATCH_SIZE)
L
liaogang 已提交
58

59
    feed_order = ['pixel', 'label']
W
Wang,Jeff 已提交
60

61 62
    main_program = fluid.default_main_program()
    star_program = fluid.default_startup_program()
W
Wang,Jeff 已提交
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    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)

    EPOCH_NUM = 1

    # 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)
        exe.run(star_program)

        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)
122
            print('\nTest with Pass {0}, Loss {1:2.2}, Acc {2:2.2}'.format(
123
                pass_id, avg_cost_test, accuracy_test))
W
Wang,Jeff 已提交
124

125 126 127
            if params_dirname is not None:
                fluid.io.save_inference_model(params_dirname, ["pixel"],
                                              [predict], exe)
W
Wang,Jeff 已提交
128

129
    train_loop()
W
Wang,Jeff 已提交
130

L
liaogang 已提交
131

132
def infer(use_cuda, params_dirname=None):
133
    from PIL import Image
134 135 136
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)
    inference_scope = fluid.core.Scope()
137

138 139
    def load_image(infer_file):
        im = Image.open(infer_file)
140
        im = im.resize((32, 32), Image.ANTIALIAS)
W
Wang,Jeff 已提交
141

142
        im = numpy.array(im).astype(numpy.float32)
W
Wang,Jeff 已提交
143
        # The storage order of the loaded image is W(width),
Q
qingqing01 已提交
144 145
        # H(height), C(channel). PaddlePaddle requires
        # the CHW order, so transpose them.
Q
qingqing01 已提交
146
        im = im.transpose((2, 0, 1))  # CHW
147
        im = im / 255.0
W
Wang,Jeff 已提交
148 149

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

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

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    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)

        # The input's dimension of conv should be 4-D or 5-D.
        # Use inference_transpiler to speedup
        inference_transpiler_program = inference_program.clone()
        t = fluid.transpiler.InferenceTranspiler()
        t.transpile(inference_transpiler_program, place)

        # 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)

        transpiler_results = exe.run(
            inference_transpiler_program,
            feed={feed_target_names[0]: img},
            fetch_list=fetch_targets)

        assert len(results[0]) == len(transpiler_results[0])
        for i in range(len(results[0])):
            numpy.testing.assert_almost_equal(
                results[0][i], transpiler_results[0][i], decimal=5)

        # 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 已提交
194 195 196 197 198 199


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

201
    train(use_cuda=use_cuda, params_dirname=save_path)
Q
qingqing01 已提交
202

203
    infer(use_cuda=use_cuda, params_dirname=save_path)
204

L
liaogang 已提交
205 206

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