test_recognize_digits_mlp.py 3.5 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
D
dzhwinter 已提交
2
#
F
fengjiayi 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
F
fengjiayi 已提交
9 10 11 12 13
# 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.
F
update  
fengjiayi 已提交
14

15
from __future__ import print_function
Q
Qiao Longfei 已提交
16
import numpy as np
Q
qijun 已提交
17
import paddle.v2 as paddle
18
import paddle.v2.fluid as fluid
Q
qijun 已提交
19

20
BATCH_SIZE = 128
21
image = fluid.layers.data(name='x', shape=[784], dtype='float32')
Q
qijun 已提交
22

Y
Yu Yang 已提交
23
regularizer = fluid.regularizer.L2Decay(0.0005 * BATCH_SIZE)
24

25 26 27
hidden1 = fluid.layers.fc(input=image,
                          size=128,
                          act='relu',
Y
Yu Yang 已提交
28 29
                          param_attr=fluid.ParamAttr(
                              regularizer=regularizer,
F
fengjiayi 已提交
30
                              gradient_clip=fluid.clip.ClipByValue(10)))
31

32 33 34
hidden2 = fluid.layers.fc(input=hidden1,
                          size=64,
                          act='relu',
Y
Yu Yang 已提交
35
                          param_attr=regularizer)
Q
qijun 已提交
36

37 38 39
predict = fluid.layers.fc(input=hidden2,
                          size=10,
                          act='softmax',
Y
Yu Yang 已提交
40
                          param_attr=regularizer)
Q
qijun 已提交
41

42
label = fluid.layers.data(name='y', shape=[1], dtype='int64')
Q
qijun 已提交
43

44 45
cost = fluid.layers.cross_entropy(input=predict, label=label)
avg_cost = fluid.layers.mean(x=cost)
Q
qijun 已提交
46

47
optimizer = fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9)
48
opts = optimizer.minimize(avg_cost)
Q
qijun 已提交
49

50
accuracy = fluid.evaluator.Accuracy(input=predict, label=label)
F
fengjiayi 已提交
51

52
inference_program = fluid.default_main_program().clone()
53 54 55 56
with fluid.program_guard(inference_program):
    test_accuracy = fluid.evaluator.Accuracy(input=predict, label=label)
    test_target = [avg_cost] + test_accuracy.metrics + test_accuracy.states
    inference_program = fluid.io.get_inference_program(test_target)
57

Q
qijun 已提交
58 59 60 61 62
train_reader = paddle.batch(
    paddle.reader.shuffle(
        paddle.dataset.mnist.train(), buf_size=8192),
    batch_size=BATCH_SIZE)

63 64
test_reader = paddle.batch(paddle.dataset.mnist.test(), batch_size=128)

65 66
place = fluid.CPUPlace()
exe = fluid.Executor(place)
Y
Yu Yang 已提交
67
feeder = fluid.DataFeeder(feed_list=[image, label], place=place)
68
exe.run(fluid.default_startup_program())
Q
qijun 已提交
69 70 71

PASS_NUM = 100
for pass_id in range(PASS_NUM):
F
fengjiayi 已提交
72
    accuracy.reset(exe)
Q
qijun 已提交
73
    for data in train_reader():
Y
Yu Yang 已提交
74 75 76
        out, acc = exe.run(fluid.default_main_program(),
                           feed=feeder.feed(data),
                           fetch_list=[avg_cost] + accuracy.metrics)
F
fengjiayi 已提交
77 78
        pass_acc = accuracy.eval(exe)

79 80
        test_accuracy.reset(exe)
        for data in test_reader():
81
            out, acc = exe.run(inference_program,
Y
Yu Yang 已提交
82
                               feed=feeder.feed(data),
83
                               fetch_list=[avg_cost] + test_accuracy.metrics)
84 85 86 87 88 89 90

        test_pass_acc = test_accuracy.eval(exe)
        print("pass_id=" + str(pass_id) + " train_cost=" + str(
            out) + " train_acc=" + str(acc) + " train_pass_acc=" + str(pass_acc)
              + " test_acc=" + str(test_pass_acc))

        if test_pass_acc > 0.7:
91 92 93
            fluid.io.save_inference_model(
                "./recognize_digits_mlp.inference.model/", ["x"], [predict],
                exe)
F
fengjiayi 已提交
94
            exit(0)
95

Q
qijun 已提交
96
exit(1)