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