train.py 2.4 KB
Newer Older
1 2 3
import paddle.v2 as paddle
import paddle.v2.dataset.uci_housing as uci_housing

G
gongweibao 已提交
4

5 6 7 8 9 10
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))
G
gongweibao 已提交
11
    y_predict = paddle.layer.fc(input=x, size=1, act=paddle.activation.Linear())
12
    y = paddle.layer.data(name='y', type=paddle.data_type.dense_vector(1))
L
Luo Tao 已提交
13
    cost = paddle.layer.mse_cost(input=y_predict, label=y)
14 15 16 17 18 19 20

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

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

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

G
gongweibao 已提交
24
    feeding = {'x': 0, 'y': 1}
25 26 27 28 29 30 31 32 33

    # event_handler to print training and testing info
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 100 == 0:
                print "Pass %d, Batch %d, Cost %f" % (
                    event.pass_id, event.batch_id, event.cost)

        if isinstance(event, paddle.event.EndPass):
Q
qiaolongfei 已提交
34 35 36
            if event.pass_id % 10 == 0:
                with open('params_pass_%d.tar' % event.pass_id, 'w') as f:
                    parameters.to_tar(f)
37
            result = trainer.test(
38
                reader=paddle.batch(uci_housing.test(), batch_size=2),
G
gongweibao 已提交
39
                feeding=feeding)
40 41 42 43
            print "Test %d, Cost %f" % (event.pass_id, result.cost)

    # training
    trainer.train(
G
gongweibao 已提交
44
        reader=paddle.batch(
45
            paddle.reader.shuffle(uci_housing.train(), buf_size=500),
46
            batch_size=2),
G
gongweibao 已提交
47
        feeding=feeding,
48 49 50
        event_handler=event_handler,
        num_passes=30)

Q
qiaolongfei 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    # inference
    test_data_creator = paddle.dataset.uci_housing.test()
    test_data = []
    test_label = []

    for item in test_data_creator():
        test_data.append((item[0], ))
        test_label.append(item[1])
        if len(test_data) == 5:
            break

    # load parameters from tar file.
    # users can remove the comments and change the model name
    # with open('params_pass_20.tar', 'r') as f:
    #     parameters = paddle.parameters.Parameters.from_tar(f)

    probs = paddle.infer(
        output_layer=y_predict, parameters=parameters, input=test_data)

    for i in xrange(len(probs)):
        print "label=" + str(test_label[i][0]) + ", predict=" + str(probs[i][0])

G
gongweibao 已提交
73

74 75
if __name__ == '__main__':
    main()