api_train_v2.py 2.0 KB
Newer Older
D
dangqingqing 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import paddle.v2 as paddle
import paddle.v2.dataset.uci_housing as uci_housing


def main():
    # init
    paddle.init(use_gpu=False, trainer_count=1)

    # network config
    x = paddle.layer.data(name='x', type=paddle.data_type.dense_vector(13))
    y_predict = paddle.layer.fc(input=x,
                                param_attr=paddle.attr.Param(name='w'),
                                size=1,
                                act=paddle.activation.Linear(),
                                bias_attr=paddle.attr.Param(name='b'))
    y = paddle.layer.data(name='y', type=paddle.data_type.dense_vector(1))
L
Luo Tao 已提交
17
    cost = paddle.layer.mse_cost(input=y_predict, label=y)
D
dangqingqing 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

    # create parameters
    parameters = paddle.parameters.create(cost)

    # create optimizer
    optimizer = paddle.optimizer.Momentum(momentum=0)

    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=optimizer)

    # event_handler to print training and testing info
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 100 == 0:
Y
Yu Yang 已提交
33 34
                print "Pass %d, Batch %d, Cost %f" % (
                    event.pass_id, event.batch_id, event.cost)
D
dangqingqing 已提交
35 36

        if isinstance(event, paddle.event.EndPass):
Y
Yu Yang 已提交
37 38 39 40 41
            if (event.pass_id + 1) % 10 == 0:
                result = trainer.test(
                    reader=paddle.batch(
                        uci_housing.test(), batch_size=2),
                    feeding={'x': 0,
D
dangqingqing 已提交
42
                             'y': 1})
Y
Yu Yang 已提交
43
                print "Test %d, %.2f" % (event.pass_id, result.cost)
D
dangqingqing 已提交
44 45 46

    # training
    trainer.train(
Y
Yu Yang 已提交
47
        reader=paddle.batch(
D
dangqingqing 已提交
48 49 50
            paddle.reader.shuffle(
                uci_housing.train(), buf_size=500),
            batch_size=2),
Y
Yu Yang 已提交
51 52
        feeding={'x': 0,
                 'y': 1},
D
dangqingqing 已提交
53 54 55 56 57 58
        event_handler=event_handler,
        num_passes=30)


if __name__ == '__main__':
    main()