Skip to content

Commit 9fad436

Browse files
authored
Simplify fluid api for fit a line (#10301)
1 parent 6ab935f commit 9fad436

File tree

3 files changed

+145
-0
lines changed

3 files changed

+145
-0
lines changed

python/paddle/fluid/tests/book/high-level-api/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ foreach(src ${TEST_OPS})
66
py_test(${src} SRCS ${src}.py)
77
endforeach()
88

9+
add_subdirectory(fit_a_line)
910
add_subdirectory(recognize_digits)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
file(GLOB TEST_OPS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "test_*.py")
2+
string(REPLACE ".py" "" TEST_OPS "${TEST_OPS}")
3+
4+
# default test
5+
foreach(src ${TEST_OPS})
6+
py_test(${src} SRCS ${src}.py)
7+
endforeach()
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
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+
15+
import paddle
16+
import paddle.fluid as fluid
17+
import contextlib
18+
import numpy
19+
import unittest
20+
21+
# train reader
22+
BATCH_SIZE = 20
23+
24+
train_reader = paddle.batch(
25+
paddle.reader.shuffle(
26+
paddle.dataset.uci_housing.train(), buf_size=500),
27+
batch_size=BATCH_SIZE)
28+
29+
test_reader = paddle.batch(
30+
paddle.reader.shuffle(
31+
paddle.dataset.uci_housing.test(), buf_size=500),
32+
batch_size=BATCH_SIZE)
33+
34+
35+
def inference_program():
36+
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
37+
y_predict = fluid.layers.fc(input=x, size=1, act=None)
38+
return y_predict
39+
40+
41+
def linear():
42+
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
43+
y_predict = inference_program()
44+
45+
loss = fluid.layers.square_error_cost(input=y_predict, label=y)
46+
avg_loss = fluid.layers.mean(loss)
47+
48+
return avg_loss
49+
50+
51+
def train(use_cuda, save_dirname):
52+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
53+
54+
trainer = fluid.Trainer(
55+
train_func=linear,
56+
infer_func=inference_program,
57+
place=place,
58+
optimizer=fluid.optimizer.SGD(learning_rate=0.001))
59+
60+
def event_handler(event):
61+
if isinstance(event, fluid.EndEpochEvent):
62+
test_metrics = trainer.test(
63+
reader=test_reader, feed_order=['x', 'y'])
64+
print test_metrics
65+
'''
66+
67+
...
68+
['25.768919467926025']
69+
['15.343549569447836']
70+
...
71+
72+
'''
73+
if float(test_metrics[0]) < 20.0:
74+
if save_dirname is not None:
75+
# NOT clear yet
76+
# fluid.io.save_inference_model(save_dirname, ['x'], [y_predict])
77+
# trainer.save_params(save_dirname)
78+
# https://github.com/PaddlePaddle/Paddle/pull/10445
79+
trainer.save_inference_model(save_dirname)
80+
return
81+
82+
trainer.train(
83+
reader=train_reader,
84+
num_epochs=100,
85+
event_handler=event_handler,
86+
feed_order=['x', 'y'])
87+
88+
89+
# infer
90+
def infer(use_cuda, save_dirname=None):
91+
if save_dirname is None:
92+
return
93+
94+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
95+
inferencer = fluid.Inferencer(param_path=save_dirname, place=place)
96+
97+
batch_size = 10
98+
tensor_x = numpy.random.uniform(0, 10, [batch_size, 13]).astype("float32")
99+
100+
results = inferencer.infer({'x': tensor_x})
101+
print("infer results: ", results[0])
102+
103+
104+
def main(use_cuda):
105+
if use_cuda and not fluid.core.is_compiled_with_cuda():
106+
return
107+
108+
# Directory for saving the trained model
109+
save_dirname = "fit_a_line.inference.model"
110+
111+
train(use_cuda, save_dirname)
112+
infer(use_cuda, save_dirname)
113+
114+
115+
class TestFitALine(unittest.TestCase):
116+
def test_cpu(self):
117+
with self.program_scope_guard():
118+
with fluid.unique_name.guard():
119+
main(use_cuda=False)
120+
121+
def test_cuda(self):
122+
with self.program_scope_guard():
123+
with fluid.unique_name.guard():
124+
main(use_cuda=True)
125+
126+
@contextlib.contextmanager
127+
def program_scope_guard(self):
128+
prog = fluid.Program()
129+
startup_prog = fluid.Program()
130+
scope = fluid.core.Scope()
131+
with fluid.scope_guard(scope):
132+
with fluid.program_guard(prog, startup_prog):
133+
yield
134+
135+
136+
if __name__ == '__main__':
137+
unittest.main()

0 commit comments

Comments
 (0)