mnist_model.py 2.8 KB
Newer Older
G
gx_wind 已提交
1 2 3 4
"""
CNN on mnist data using fluid api of paddlepaddle
"""
import paddle.v2 as paddle
L
Luo Tao 已提交
5
import paddle.fluid as fluid
G
gx_wind 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32


def mnist_cnn_model(img):
    """
    Mnist cnn model

    Args:
        img(Varaible): the input image to be recognized

    Returns:
        Variable: the label prediction
    """
    conv_pool_1 = fluid.nets.simple_img_conv_pool(
        input=img,
        num_filters=20,
        filter_size=5,
        pool_size=2,
        pool_stride=2,
        act='relu')

    conv_pool_2 = fluid.nets.simple_img_conv_pool(
        input=conv_pool_1,
        num_filters=50,
        filter_size=5,
        pool_size=2,
        pool_stride=2,
        act='relu')
B
buaawht 已提交
33
    fc = fluid.layers.fc(input=conv_pool_2, size=50, act='relu')
G
gx_wind 已提交
34

B
buaawht 已提交
35
    logits = fluid.layers.fc(input=fc, size=10, act='softmax')
G
gx_wind 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    return logits


def main():
    """
    Train the cnn model on mnist datasets
    """
    img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')
    logits = mnist_cnn_model(img)
    cost = fluid.layers.cross_entropy(input=logits, label=label)
    avg_cost = fluid.layers.mean(x=cost)
    optimizer = fluid.optimizer.Adam(learning_rate=0.01)
    optimizer.minimize(avg_cost)

F
fengjiayi 已提交
51 52 53
    batch_size = fluid.layers.create_tensor(dtype='int64')
    batch_acc = fluid.layers.accuracy(
        input=logits, label=label, total=batch_size)
G
gx_wind 已提交
54 55 56 57 58 59

    BATCH_SIZE = 50
    PASS_NUM = 3
    ACC_THRESHOLD = 0.98
    LOSS_THRESHOLD = 10.0
    train_reader = paddle.batch(
60 61
        paddle.reader.shuffle(
            paddle.dataset.mnist.train(), buf_size=500),
G
gx_wind 已提交
62 63
        batch_size=BATCH_SIZE)

B
buaawht 已提交
64
    # use CPU
G
gx_wind 已提交
65
    place = fluid.CPUPlace()
B
buaawht 已提交
66 67
    # use GPU
    # place = fluid.CUDAPlace(0)
G
gx_wind 已提交
68 69 70 71
    exe = fluid.Executor(place)
    feeder = fluid.DataFeeder(feed_list=[img, label], place=place)
    exe.run(fluid.default_startup_program())

F
fengjiayi 已提交
72
    pass_acc = fluid.average.WeightedAverage()
G
gx_wind 已提交
73
    for pass_id in range(PASS_NUM):
F
fengjiayi 已提交
74
        pass_acc.reset()
G
gx_wind 已提交
75
        for data in train_reader():
F
fengjiayi 已提交
76 77 78 79
            loss, acc, b_size = exe.run(
                fluid.default_main_program(),
                feed=feeder.feed(data),
                fetch_list=[avg_cost, batch_acc, batch_size])
F
fengjiayi 已提交
80
            pass_acc.add(value=acc, weight=b_size)
B
buaawht 已提交
81
            pass_acc_val = pass_acc.eval()[0]
F
fengjiayi 已提交
82
            print("pass_id=" + str(pass_id) + " acc=" + str(acc[0]) +
B
buaawht 已提交
83 84 85
                  " pass_acc=" + str(pass_acc_val))
            if loss < LOSS_THRESHOLD and pass_acc_val > ACC_THRESHOLD:
                # early stop
G
gx_wind 已提交
86 87
                break

F
fengjiayi 已提交
88 89
        print("pass_id=" + str(pass_id) + " pass_acc=" + str(pass_acc.eval()[
            0]))
G
gx_wind 已提交
90 91 92 93 94 95 96
    fluid.io.save_params(
        exe, dirname='./mnist', main_program=fluid.default_main_program())
    print('train mnist done')


if __name__ == '__main__':
    main()