pyreader.py 4.0 KB
Newer Older
Y
yuyang18 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.

import paddle.fluid as fluid
import paddle.dataset.mnist as mnist
import paddle
Y
yuyang18 已提交
18
import paddle.v2
Y
yuyang18 已提交
19 20 21 22 23 24 25 26 27 28
import threading
import numpy


def network(is_train):
    reader, queue = fluid.layers.py_reader(
        capacity=10,
        shapes=((-1, 784), (-1, 1)),
        dtypes=('float32', 'int64'),
        name="train_reader" if is_train else "test_reader")
Y
yuyang18 已提交
29
    img, label = fluid.layers.read_file(reader)
Y
yuyang18 已提交
30 31 32 33 34 35 36 37 38 39

    hidden = img

    for i in xrange(2):
        hidden = fluid.layers.fc(input=hidden, size=100, act='tanh')
        hidden = fluid.layers.dropout(
            hidden, dropout_prob=0.5, is_test=not is_train)

    prediction = fluid.layers.fc(input=hidden, size=10, act='softmax')
    loss = fluid.layers.cross_entropy(input=prediction, label=label)
Y
yuyang18 已提交
40
    return fluid.layers.mean(loss), queue, reader
Y
yuyang18 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73


def pipe_reader_to_queue(reader_creator, queue):
    with fluid.program_guard(fluid.Program(), fluid.Program()):
        feeder = fluid.DataFeeder(
            feed_list=[
                fluid.layers.data(
                    name='img', dtype='float32', shape=[784]),
                fluid.layers.data(
                    name='label', dtype='int64', shape=[1])
            ],
            place=fluid.CPUPlace())

    def __thread_main__():
        for data in feeder.decorate_reader(
                reader_creator, multi_devices=False)():
            tmp = fluid.core.LoDTensorArray()
            tmp.append(data['img'])
            tmp.append(data['label'])
            queue.push(tmp)
        queue.close()

    th = threading.Thread(target=__thread_main__)
    th.start()
    return th


def main():
    train_prog = fluid.Program()
    startup_prog = fluid.Program()

    with fluid.program_guard(train_prog, startup_prog):
        with fluid.unique_name.guard():
Y
yuyang18 已提交
74
            loss, train_queue, train_reader = network(True)
Y
yuyang18 已提交
75 76 77 78
            adam = fluid.optimizer.Adam(learning_rate=0.01)
            adam.minimize(loss)

    test_prog = fluid.Program()
Y
yuyang18 已提交
79 80
    test_startup = fluid.Program()
    with fluid.program_guard(test_prog, test_startup):
Y
yuyang18 已提交
81
        with fluid.unique_name.guard():
Y
yuyang18 已提交
82
            test_loss, test_queue, test_reader = network(False)
Y
yuyang18 已提交
83 84

    fluid.Executor(fluid.CUDAPlace(0)).run(startup_prog)
Y
yuyang18 已提交
85
    fluid.Executor(fluid.CUDAPlace(0)).run(test_startup)
Y
yuyang18 已提交
86

Y
yuyang18 已提交
87 88 89 90 91
    trainer = fluid.ParallelExecutor(
        use_cuda=True, loss_name=loss.name, main_program=train_prog)

    tester = fluid.ParallelExecutor(
        use_cuda=True, share_vars_from=trainer, main_program=test_prog)
Y
yuyang18 已提交
92 93

    for epoch_id in xrange(10):
Y
yuyang18 已提交
94
        train_data_thread = pipe_reader_to_queue(
Y
yuyang18 已提交
95 96
            paddle.batch(paddle.v2.reader.firstn(mnist.train(), 32), 64),
            train_queue)
Y
yuyang18 已提交
97
        try:
Y
yuyang18 已提交
98 99 100
            while True:
                print 'train_loss', numpy.array(
                    trainer.run(fetch_list=[loss.name]))
Y
yuyang18 已提交
101 102
        except fluid.core.EOFException:
            print 'End of epoch', epoch_id
Y
yuyang18 已提交
103
            train_reader.reset()
Y
yuyang18 已提交
104 105 106
        train_data_thread.join()

        test_data_thread = pipe_reader_to_queue(
Y
yuyang18 已提交
107
            paddle.batch(mnist.test(), 32), test_queue)
Y
yuyang18 已提交
108 109
        try:
            while True:
Y
yuyang18 已提交
110 111
                print 'test loss', numpy.array(
                    tester.run(fetch_list=[test_loss.name]))
Y
yuyang18 已提交
112 113
        except fluid.core.EOFException:
            print 'End of testing'
Y
yuyang18 已提交
114
            test_reader.reset()
Y
yuyang18 已提交
115 116 117

        test_data_thread.join()
        break
Y
yuyang18 已提交
118 119
    del trainer
    del tester
Y
yuyang18 已提交
120 121 122 123


if __name__ == '__main__':
    main()