Skip to content

Commit 380471f

Browse files
authored
Simplify fluid api recognize digit (#10308)
* Save the base of the new test. * Create the notest_recognize_digits_conv and notest_recognize_digits_mlp * precommit check * Change the function name from _network to _program. Update several variable names to make them more consistant. Update the Inferencer construction call. * Fix the incorrect format.
1 parent 375175b commit 380471f

File tree

2 files changed

+223
-0
lines changed

2 files changed

+223
-0
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
from __future__ import print_function
15+
import argparse
16+
import paddle.fluid as fluid
17+
import paddle
18+
import sys
19+
import numpy
20+
import unittest
21+
import math
22+
import sys
23+
import os
24+
import paddle.v2.dataset as dataset
25+
26+
BATCH_SIZE = 64
27+
28+
29+
def inference_program():
30+
img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
31+
32+
conv_pool_1 = fluid.nets.simple_img_conv_pool(
33+
input=img,
34+
filter_size=5,
35+
num_filters=20,
36+
pool_size=2,
37+
pool_stride=2,
38+
act="relu")
39+
conv_pool_1 = fluid.layers.batch_norm(conv_pool_1)
40+
conv_pool_2 = fluid.nets.simple_img_conv_pool(
41+
input=conv_pool_1,
42+
filter_size=5,
43+
num_filters=50,
44+
pool_size=2,
45+
pool_stride=2,
46+
act="relu")
47+
prediction = fluid.layers.fc(input=conv_pool_2, size=10, act='softmax')
48+
return prediction
49+
50+
51+
def train_program():
52+
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
53+
54+
predict = inference_program()
55+
cost = fluid.layers.cross_entropy(input=predict, label=label)
56+
avg_cost = fluid.layers.mean(cost)
57+
acc = fluid.layers.accuracy(input=predict, label=label)
58+
return avg_cost, acc
59+
60+
61+
def train(use_cuda, save_dirname):
62+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
63+
64+
optimizer = fluid.optimizer.Adam(learning_rate=0.001)
65+
trainer = fluid.Trainer(train_program, place=place, optimizer=optimizer)
66+
67+
def event_handler(event):
68+
if isinstance(event, fluid.EndIteration):
69+
avg_cost, acc = event.values
70+
print("avg_cost: %s" % avg_cost)
71+
print("acc : %s" % acc)
72+
73+
if (event.batch_id + 1) % 10 == 0:
74+
test_metrics = trainer.test(reader=dataset.mnist.test())
75+
avg_cost_set = test_metrics[0]
76+
acc_set = test_metrics[1]
77+
78+
# get test acc and loss
79+
acc = numpy.array(acc_set).mean()
80+
avg_cost = numpy.array(avg_cost_set).mean()
81+
if float(acc) > 0.2: # Smaller value to increase CI speed
82+
trainer.save_params(save_dirname)
83+
else:
84+
print('BatchID {0}, Test Loss {1:0.2}, Acc {2:0.2}'.format(
85+
event.batch_id + 1, float(avg_cost), float(acc)))
86+
if math.isnan(float(avg_cost)):
87+
sys.exit("got NaN loss, training failed.")
88+
89+
trainer.train(
90+
reader=dataset.mnist.train(), num_pass=100, event_handler=event_handler)
91+
92+
93+
def infer(use_cuda, save_dirname=None):
94+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
95+
96+
inferencer = fluid.Inferencer(
97+
inference_program, param_path=save_dirname, place=place)
98+
99+
batch_size = 1
100+
tensor_img = numpy.random.uniform(-1.0, 1.0,
101+
[batch_size, 1, 28, 28]).astype("float32")
102+
103+
results = inferencer.infer({'img': tensor_img})
104+
105+
print("infer results: ", results[0])
106+
107+
108+
def main(use_cuda):
109+
save_dirname = "recognize_digits_conv.inference.model"
110+
111+
# call train() with is_local argument to run distributed train
112+
train(use_cuda=use_cuda, save_dirname=save_dirname)
113+
infer(use_cuda=use_cuda, save_dirname=save_dirname)
114+
115+
116+
if __name__ == '__main__':
117+
for use_cuda in (False, True):
118+
main(use_cuda=use_cuda)
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
from __future__ import print_function
15+
import argparse
16+
import paddle.fluid as fluid
17+
import paddle
18+
import sys
19+
import numpy
20+
import unittest
21+
import math
22+
import sys
23+
import os
24+
import paddle.v2.dataset as dataset
25+
26+
BATCH_SIZE = 64
27+
28+
29+
def inference_program():
30+
img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
31+
32+
hidden = fluid.layers.fc(input=img, size=200, act='tanh')
33+
hidden = fluid.layers.fc(input=hidden, size=200, act='tanh')
34+
prediction = fluid.layers.fc(input=hidden, size=10, act='softmax')
35+
return prediction
36+
37+
38+
def train_program():
39+
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
40+
41+
predict = inference_program()
42+
cost = fluid.layers.cross_entropy(input=predict, label=label)
43+
avg_cost = fluid.layers.mean(cost)
44+
acc = fluid.layers.accuracy(input=predict, label=label)
45+
return avg_cost, acc
46+
47+
48+
def train(use_cuda, save_dirname):
49+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
50+
51+
optimizer = fluid.optimizer.Adam(learning_rate=0.001)
52+
trainer = fluid.Trainer(train_program, place=place, optimizer=optimizer)
53+
54+
def event_handler(event):
55+
if isinstance(event, fluid.EndIteration):
56+
avg_cost, acc = event.values
57+
print("avg_cost: %s" % avg_cost)
58+
print("acc : %s" % acc)
59+
60+
if (event.batch_id + 1) % 10 == 0:
61+
test_metrics = trainer.test(reader=dataset.mnist.test())
62+
avg_cost_set = test_metrics[0]
63+
acc_set = test_metrics[1]
64+
65+
# get test acc and loss
66+
acc = numpy.array(acc_set).mean()
67+
avg_cost = numpy.array(avg_cost_set).mean()
68+
if float(acc) > 0.2: # Smaller value to increase CI speed
69+
trainer.save_params(save_dirname)
70+
else:
71+
print('BatchID {0}, Test Loss {1:0.2}, Acc {2:0.2}'.format(
72+
event.batch_id + 1, float(avg_cost), float(acc)))
73+
if math.isnan(float(avg_cost)):
74+
sys.exit("got NaN loss, training failed.")
75+
76+
trainer.train(
77+
reader=dataset.mnist.train(), num_pass=100, event_handler=event_handler)
78+
79+
80+
def infer(use_cuda, save_dirname=None):
81+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
82+
83+
inferencer = fluid.Inferencer(
84+
inference_program, param_path=save_dirname, place=place)
85+
86+
batch_size = 1
87+
tensor_img = numpy.random.uniform(-1.0, 1.0,
88+
[batch_size, 1, 28, 28]).astype("float32")
89+
90+
results = inferencer.infer({'img': tensor_img})
91+
92+
print("infer results: ", results[0])
93+
94+
95+
def main(use_cuda):
96+
save_dirname = "recognize_digits_mlp.inference.model"
97+
98+
# call train() with is_local argument to run distributed train
99+
train(use_cuda=use_cuda, save_dirname=save_dirname)
100+
infer(use_cuda=use_cuda, save_dirname=save_dirname)
101+
102+
103+
if __name__ == '__main__':
104+
for use_cuda in (False, True):
105+
main(use_cuda=use_cuda)

0 commit comments

Comments
 (0)