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

J
JiabinYang 已提交
15
from __future__ import print_function
16

L
liaogang 已提交
17
import os
u010070587's avatar
u010070587 已提交
18
import argparse
L
liaogang 已提交
19
from PIL import Image
20
import numpy
W
Wang,Jeff 已提交
21 22
import paddle
import paddle.fluid as fluid
L
Luo Tao 已提交
23

u010070587's avatar
u010070587 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

def parse_args():
    parser = argparse.ArgumentParser("mnist")
    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=False,
        help="Whether to use GPU or not.")
    parser.add_argument(
        '--num_epochs', type=int, default=5, help="number of epochs.")
    args = parser.parse_args()
    return args
Y
yuyang 已提交
40

L
Luo Tao 已提交
41

42 43 44 45 46 47
def loss_net(hidden, label):
    prediction = fluid.layers.fc(input=hidden, size=10, act='softmax')
    loss = fluid.layers.cross_entropy(input=prediction, label=label)
    avg_loss = fluid.layers.mean(loss)
    acc = fluid.layers.accuracy(input=prediction, label=label)
    return prediction, avg_loss, acc
L
Luo Tao 已提交
48 49


50 51 52 53
def multilayer_perceptron(img, label):
    img = fluid.layers.fc(input=img, size=200, act='tanh')
    hidden = fluid.layers.fc(input=img, size=200, act='tanh')
    return loss_net(hidden, label)
L
Luo Tao 已提交
54 55


56 57 58 59 60
def softmax_regression(img, label):
    return loss_net(img, label)


def convolutional_neural_network(img, label):
W
Wang,Jeff 已提交
61
    conv_pool_1 = fluid.nets.simple_img_conv_pool(
L
Luo Tao 已提交
62 63 64 65 66
        input=img,
        filter_size=5,
        num_filters=20,
        pool_size=2,
        pool_stride=2,
W
Wang,Jeff 已提交
67 68 69
        act="relu")
    conv_pool_1 = fluid.layers.batch_norm(conv_pool_1)
    conv_pool_2 = fluid.nets.simple_img_conv_pool(
L
Luo Tao 已提交
70 71 72 73 74
        input=conv_pool_1,
        filter_size=5,
        num_filters=50,
        pool_size=2,
        pool_stride=2,
W
Wang,Jeff 已提交
75
        act="relu")
76
    return loss_net(conv_pool_2, label)
L
Luo Tao 已提交
77

Q
qijun 已提交
78

79 80 81 82 83 84 85
def train(nn_type,
          use_cuda,
          save_dirname=None,
          model_filename=None,
          params_filename=None):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return
Q
qijun 已提交
86

u010070587's avatar
u010070587 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    startup_program = fluid.default_startup_program()
    main_program = fluid.default_main_program()

    if args.enable_ce:
        train_reader = paddle.batch(
            paddle.dataset.mnist.train(), batch_size=BATCH_SIZE)
        test_reader = paddle.batch(
            paddle.dataset.mnist.test(), batch_size=BATCH_SIZE)
        startup_program.random_seed = 90
        main_program.random_seed = 90
    else:
        train_reader = paddle.batch(
            paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=500),
            batch_size=BATCH_SIZE)
        test_reader = paddle.batch(
            paddle.dataset.mnist.test(), batch_size=BATCH_SIZE)

104 105
    img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')
Q
qijun 已提交
106

107 108 109 110 111 112 113 114 115
    if nn_type == 'softmax_regression':
        net_conf = softmax_regression
    elif nn_type == 'multilayer_perceptron':
        net_conf = multilayer_perceptron
    else:
        net_conf = convolutional_neural_network

    prediction, avg_loss, acc = net_conf(img, label)

u010070587's avatar
u010070587 已提交
116
    test_program = main_program.clone(for_test=True)
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    optimizer = fluid.optimizer.Adam(learning_rate=0.001)
    optimizer.minimize(avg_loss)

    def train_test(train_test_program, train_test_feed, train_test_reader):
        acc_set = []
        avg_loss_set = []
        for test_data in train_test_reader():
            acc_np, avg_loss_np = exe.run(
                program=train_test_program,
                feed=train_test_feed.feed(test_data),
                fetch_list=[acc, avg_loss])
            acc_set.append(float(acc_np))
            avg_loss_set.append(float(avg_loss_np))
        # get test acc and loss
        acc_val_mean = numpy.array(acc_set).mean()
        avg_loss_val_mean = numpy.array(avg_loss_set).mean()
        return avg_loss_val_mean, acc_val_mean
Q
qijun 已提交
134

135
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
W
Wang,Jeff 已提交
136

137
    exe = fluid.Executor(place)
W
Wang,Jeff 已提交
138

139
    feeder = fluid.DataFeeder(feed_list=[img, label], place=place)
u010070587's avatar
u010070587 已提交
140
    exe.run(startup_program)
141
    epochs = [epoch_id for epoch_id in range(PASS_NUM)]
Q
qijun 已提交
142 143

    lists = []
144 145 146 147 148 149 150 151
    step = 0
    for epoch_id in epochs:
        for step_id, data in enumerate(train_reader()):
            metrics = exe.run(
                main_program,
                feed=feeder.feed(data),
                fetch_list=[avg_loss, acc])
            if step % 100 == 0:
152
                print("Pass %d, Epoch %d, Cost %f" % (step, epoch_id,
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
                                                      metrics[0]))
            step += 1
        # test for epoch
        avg_loss_val, acc_val = train_test(
            train_test_program=test_program,
            train_test_reader=test_reader,
            train_test_feed=feeder)

        print("Test with Epoch %d, avg_cost: %s, acc: %s" %
              (epoch_id, avg_loss_val, acc_val))
        lists.append((epoch_id, avg_loss_val, acc_val))
        if save_dirname is not None:
            fluid.io.save_inference_model(
                save_dirname, ["img"], [prediction],
                exe,
                model_filename=model_filename,
                params_filename=params_filename)
Q
qijun 已提交
170

u010070587's avatar
u010070587 已提交
171 172 173 174 175
    if args.enable_ce:
        print("kpis\ttrain_cost\t%f" % metrics[0])
        print("kpis\ttest_cost\t%s" % avg_loss_val)
        print("kpis\ttest_acc\t%s" % acc_val)

Q
qijun 已提交
176 177
    # find the best pass
    best = sorted(lists, key=lambda list: float(list[1]))[0]
J
JiabinYang 已提交
178 179
    print('Best pass is %s, testing Avgcost is %s' % (best[0], best[1]))
    print('The classification accuracy is %.2f%%' % (float(best[2]) * 100))
Q
qijun 已提交
180

181 182 183 184 185 186 187 188 189 190 191

def infer(use_cuda,
          save_dirname=None,
          model_filename=None,
          params_filename=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

L
liaogang 已提交
192 193 194
    def load_image(file):
        im = Image.open(file).convert('L')
        im = im.resize((28, 28), Image.ANTIALIAS)
195
        im = numpy.array(im).reshape(1, 1, 28, 28).astype(numpy.float32)
A
alexqdh 已提交
196
        im = im / 255.0 * 2.0 - 1.0
L
liaogang 已提交
197 198
        return im

L
liaogang 已提交
199
    cur_dir = os.path.dirname(os.path.realpath(__file__))
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    tensor_img = load_image(cur_dir + '/image/infer_3.png')

    inference_scope = fluid.core.Scope()
    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(
             save_dirname, exe, model_filename, params_filename)

        # 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]: tensor_img},
            fetch_list=fetch_targets)
        lab = numpy.argsort(results)
        print("Inference result of image/infer_3.png is: %d" % lab[0][0][-1])


def main(use_cuda, nn_type):
    model_filename = None
    params_filename = None
    save_dirname = "recognize_digits_" + nn_type + ".inference.model"

    # call train() with is_local argument to run distributed train
    train(
        nn_type=nn_type,
        use_cuda=use_cuda,
        save_dirname=save_dirname,
        model_filename=model_filename,
        params_filename=params_filename)
    infer(
        use_cuda=use_cuda,
        save_dirname=save_dirname,
        model_filename=model_filename,
        params_filename=params_filename)
L
liaogang 已提交
239

Q
qijun 已提交
240

Q
qijun 已提交
241
if __name__ == '__main__':
u010070587's avatar
u010070587 已提交
242 243 244 245
    args = parse_args()
    BATCH_SIZE = 64
    PASS_NUM = args.num_epochs
    use_cuda = args.use_gpu
246 247 248 249
    # predict = 'softmax_regression' # uncomment for Softmax
    # predict = 'multilayer_perceptron' # uncomment for MLP
    predict = 'convolutional_neural_network'  # uncomment for LeNet5
    main(use_cuda=use_cuda, nn_type=predict)