train.py 6.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

15
from __future__ import print_function
16

17
import sys
u010070587's avatar
u010070587 已提交
18
import argparse
19 20 21 22

import math
import numpy

23 24 25 26
import paddle
import paddle.fluid as fluid


u010070587's avatar
u010070587 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
def parse_args():
    parser = argparse.ArgumentParser("fit_a_line")
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help="If set, run the task with continuous evaluation logs.")
    parser.add_argument(
        '--use_gpu',
        type=bool,
        default=False,
        help="Whether to use GPU or not.")
    parser.add_argument(
        '--num_epochs', type=int, default=100, help="number of epochs.")
    args = parser.parse_args()
    return args


L
lujun 已提交
44
# For training test cost
45
def train_test(executor, program, reader, feeder, fetch_list):
L
lujun 已提交
46 47 48
    accumulated = 1 * [0]
    count = 0
    for data_test in reader():
49 50
        outs = executor.run(
            program=program, feed=feeder.feed(data_test), fetch_list=fetch_list)
L
lujun 已提交
51 52 53 54
        accumulated = [x_c[0] + x_c[1][0] for x_c in zip(accumulated, outs)]
        count += 1
    return [x_d / count for x_d in accumulated]

55

C
ceci 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
def save_result(points1, points2):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    x1 = [idx for idx in range(len(points1))]
    y1 = points1
    y2 = points2
    l1 = plt.plot(x1, y1, 'r--', label='predictions')
    l2 = plt.plot(x1, y2, 'g--', label='GT')
    plt.plot(x1, y1, 'ro-', x1, y2, 'g+-')
    plt.title('predictions VS GT')
    plt.legend()
    plt.savefig('./image/prediction_gt.png')


L
lujun 已提交
71
def main():
72
    batch_size = 20
u010070587's avatar
u010070587 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

    if args.enable_ce:
        train_reader = paddle.batch(
            paddle.dataset.uci_housing.train(), batch_size=batch_size)
        test_reader = paddle.batch(
            paddle.dataset.uci_housing.test(), batch_size=batch_size)
    else:
        train_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.uci_housing.train(), buf_size=500),
            batch_size=batch_size)
        test_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.uci_housing.test(), buf_size=500),
            batch_size=batch_size)
88 89

    # feature vector of length 13
C
ceci3 已提交
90 91
    x = fluid.data(name='x', shape=[None, 13], dtype='float32')
    y = fluid.data(name='y', shape=[None, 1], dtype='float32')
92

93
    main_program = fluid.default_main_program()
L
lujun 已提交
94
    startup_program = fluid.default_startup_program()
95

u010070587's avatar
u010070587 已提交
96 97 98 99 100
    if args.enable_ce:
        main_program.random_seed = 90
        startup_program.random_seed = 90

    y_predict = fluid.layers.fc(input=x, size=1, act=None)
101 102 103
    cost = fluid.layers.square_error_cost(input=y_predict, label=y)
    avg_loss = fluid.layers.mean(cost)

104 105
    test_program = main_program.clone(for_test=True)

106 107 108 109
    sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
    sgd_optimizer.minimize(avg_loss)

    # can use CPU or GPU
u010070587's avatar
u010070587 已提交
110
    use_cuda = args.use_gpu
111
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
112
    exe = fluid.Executor(place)
113 114 115

    # Specify the directory to save the parameters
    params_dirname = "fit_a_line.inference.model"
u010070587's avatar
u010070587 已提交
116
    num_epochs = args.num_epochs
117 118

    # main train loop.
L
lujun 已提交
119
    feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
120
    exe.run(startup_program)
L
lujun 已提交
121 122 123 124 125

    train_prompt = "Train cost"
    test_prompt = "Test cost"
    step = 0

126
    exe_test = fluid.Executor(place)
L
lujun 已提交
127 128 129 130

    for pass_id in range(num_epochs):
        for data_train in train_reader():
            avg_loss_value, = exe.run(
131 132 133
                main_program,
                feed=feeder.feed(data_train),
                fetch_list=[avg_loss])
L
lujun 已提交
134 135 136 137 138 139 140
            if step % 10 == 0:  # record a train cost every 10 batches
                print("%s, Step %d, Cost %f" %
                      (train_prompt, step, avg_loss_value[0]))

            if step % 100 == 0:  # record a test cost every 100 batches
                test_metics = train_test(
                    executor=exe_test,
141
                    program=test_program,
L
lujun 已提交
142
                    reader=test_reader,
143
                    fetch_list=[avg_loss],
L
lujun 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157
                    feeder=feeder)
                print("%s, Step %d, Cost %f" %
                      (test_prompt, step, test_metics[0]))
                # If the accuracy is good enough, we can stop the training.
                if test_metics[0] < 10.0:
                    break

            step += 1

            if math.isnan(float(avg_loss_value[0])):
                sys.exit("got NaN loss, training failed.")
        if params_dirname is not None:
            # We can save the trained parameters for the inferences later
            fluid.io.save_inference_model(params_dirname, ['x'], [y_predict],
158
                                          exe)
159

u010070587's avatar
u010070587 已提交
160 161 162 163
        if args.enable_ce and pass_id == args.num_epochs - 1:
            print("kpis\ttrain_cost\t%f" % avg_loss_value[0])
            print("kpis\ttest_cost\t%f" % test_metics[0])

164 165
    infer_exe = fluid.Executor(place)
    inference_scope = fluid.core.Scope()
166

167 168
    # infer
    with fluid.scope_guard(inference_scope):
L
lujun 已提交
169 170
        [inference_program, feed_target_names, fetch_targets
         ] = fluid.io.load_inference_model(params_dirname, infer_exe)
171
        batch_size = 10
172

173 174
        infer_reader = paddle.batch(
            paddle.dataset.uci_housing.test(), batch_size=batch_size)
175

176 177 178 179 180
        infer_data = next(infer_reader())
        infer_feat = numpy.array(
            [data[0] for data in infer_data]).astype("float32")
        infer_label = numpy.array(
            [data[1] for data in infer_data]).astype("float32")
181

182 183 184 185 186
        assert feed_target_names[0] == 'x'
        results = infer_exe.run(
            inference_program,
            feed={feed_target_names[0]: numpy.array(infer_feat)},
            fetch_list=fetch_targets)
187

188 189 190
        print("infer results: (House Price)")
        for idx, val in enumerate(results[0]):
            print("%d: %.2f" % (idx, val))
191

192 193 194
        print("\nground truth:")
        for idx, val in enumerate(infer_label):
            print("%d: %.2f" % (idx, val))
195

C
ceci 已提交
196 197
        save_result(results[0], infer_label)

198

199
if __name__ == '__main__':
u010070587's avatar
u010070587 已提交
200
    args = parse_args()
201
    main()