|
| 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