api_train_v2.py 2.1 KB
Newer Older
Y
Yu Yang 已提交
1
import numpy
Q
qiaolongfei 已提交
2 3
import paddle.v2 as paddle

Y
Yu Yang 已提交
4 5
import mnist_util

Q
qiaolongfei 已提交
6 7 8
import pudb
pudb.set_trace()

Y
Yu Yang 已提交
9 10 11 12 13 14 15 16 17

def train_reader():
    train_file = './data/raw_data/train'
    generator = mnist_util.read_from_mnist(train_file)
    for item in generator:
        yield item


def main():
Y
Yu Yang 已提交
18
    paddle.init(use_gpu=False, trainer_count=1)
Q
qiaolongfei 已提交
19 20

    # define network topology
21 22 23 24
    images = paddle.layer.data(
        name='pixel', type=paddle.data_type.dense_vector(784))
    label = paddle.layer.data(
        name='label', type=paddle.data_type.integer_value(10))
Q
qiaolongfei 已提交
25 26 27 28 29 30 31
    hidden1 = paddle.layer.fc(input=images, size=200)
    hidden2 = paddle.layer.fc(input=hidden1, size=200)
    inference = paddle.layer.fc(input=hidden2,
                                size=10,
                                act=paddle.activation.Softmax())
    cost = paddle.layer.classification_cost(input=inference, label=label)

Q
qiaolongfei 已提交
32
    parameters = paddle.parameters.create(cost)
Y
Yu Yang 已提交
33
    for param_name in parameters.keys():
Y
Yu Yang 已提交
34
        array = parameters.get(param_name)
Y
Yu Yang 已提交
35
        array[:] = numpy.random.uniform(low=-1.0, high=1.0, size=array.shape)
Y
Yu Yang 已提交
36
        parameters.set(parameter_name=param_name, value=array)
Y
Yu Yang 已提交
37

Q
qiaolongfei 已提交
38
    adam_optimizer = paddle.optimizer.Adam(learning_rate=0.01)
Y
Yu Yang 已提交
39 40

    def event_handler(event):
Y
Yu Yang 已提交
41
        if isinstance(event, paddle.event.EndIteration):
Q
qiaolongfei 已提交
42
            para = parameters.get('___fc_2__.w0')
Y
Yu Yang 已提交
43 44
            print "Pass %d, Batch %d, Cost %f, Weight Mean Of Fc 2 is %f" % (
                event.pass_id, event.batch_id, event.cost, para.mean())
Y
Yu Yang 已提交
45

Y
Yu Yang 已提交
46 47
        else:
            pass
48

Y
Yu Yang 已提交
49
    trainer = paddle.trainer.SGD(update_equation=adam_optimizer)
Y
Yu Yang 已提交
50 51

    trainer.train(train_data_reader=train_reader,
Q
qiaolongfei 已提交
52
                  topology=cost,
Y
Yu Yang 已提交
53
                  parameters=parameters,
Y
Yu Yang 已提交
54 55 56 57
                  event_handler=event_handler,
                  batch_size=32,  # batch size should be refactor in Data reader
                  data_types={  # data_types will be removed, It should be in
                      # network topology
Q
qiaolongfei 已提交
58 59
                      'pixel': images.type,
                      'label': label.type
Y
Yu Yang 已提交
60 61 62 63 64
                  })


if __name__ == '__main__':
    main()