api_train.py 6.8 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9
"""
A very basic example for how to use current Raw SWIG API to train mnist network.

Current implementation uses Raw SWIG, which means the API call is directly \
passed to C++ side of Paddle.

The user api could be simpler and carefully designed.
"""
import random
10

Q
qiaolongfei 已提交
11
import numpy as np
Q
qiaolongfei 已提交
12
import paddle.v2 as paddle_v2
Q
qiaolongfei 已提交
13 14 15
import py_paddle.swig_paddle as api
from paddle.trainer_config_helpers import *
from py_paddle import DataProviderConverter
16

Q
qiaolongfei 已提交
17
from mnist_util import read_from_mnist
18

Y
Yu Yang 已提交
19 20 21 22 23

def init_parameter(network):
    assert isinstance(network, api.GradientMachine)
    for each_param in network.getParameters():
        assert isinstance(each_param, api.Parameter)
Y
Yu Yang 已提交
24 25 26
        array_size = len(each_param)
        array = np.random.uniform(-1.0, 1.0, array_size).astype('float32')
        each_param.getBuf(api.PARAMETER_VALUE).copyFromNumpyArray(array)
Y
Yu Yang 已提交
27 28


Y
Yu Yang 已提交
29 30 31 32 33 34 35 36 37 38 39
def generator_to_batch(generator, batch_size):
    ret_val = list()
    for each_item in generator:
        ret_val.append(each_item)
        if len(ret_val) == batch_size:
            yield ret_val
            ret_val = list()
    if len(ret_val) != 0:
        yield ret_val


Y
Yu Yang 已提交
40 41 42 43 44 45 46 47 48 49 50 51
class BatchPool(object):
    def __init__(self, generator, batch_size):
        self.data = list(generator)
        self.batch_size = batch_size

    def __call__(self):
        random.shuffle(self.data)
        for offset in xrange(0, len(self.data), self.batch_size):
            limit = min(offset + self.batch_size, len(self.data))
            yield self.data[offset:limit]


Y
Yu Yang 已提交
52 53 54 55 56
def input_order_converter(generator):
    for each_item in generator:
        yield each_item['pixel'], each_item['label']


Y
Yu Yang 已提交
57
def main():
Y
Yu Yang 已提交
58
    api.initPaddle("-use_gpu=false", "-trainer_count=4")  # use 4 cpu cores
Y
Yu Yang 已提交
59

Q
qiaolongfei 已提交
60
    optimizer = paddle_v2.optimizer.Adam(
Q
qiaolongfei 已提交
61 62 63 64 65 66 67 68 69 70
        learning_rate=1e-4,
        batch_size=1000,
        model_average=ModelAverage(average_window=0.5),
        regularization=L2Regularization(rate=0.5))

    # Create Local Updater. Local means not run in cluster.
    # For a cluster training, here we can change to createRemoteUpdater
    # in future.
    updater = optimizer.create_local_updater()
    assert isinstance(updater, api.ParameterUpdater)
Y
Yu Yang 已提交
71

Q
qiaolongfei 已提交
72
    # define network
Q
qiaolongfei 已提交
73
    images = paddle_v2.layer.data(
74
        name='pixel', type=paddle_v2.data_type.dense_vector(784))
Q
qiaolongfei 已提交
75
    label = paddle_v2.layer.data(
76
        name='label', type=paddle_v2.data_type.integer_value(10))
Q
qiaolongfei 已提交
77 78 79 80
    hidden1 = paddle_v2.layer.fc(input=images, size=200)
    hidden2 = paddle_v2.layer.fc(input=hidden1, size=200)
    inference = paddle_v2.layer.fc(input=hidden2,
                                   size=10,
81
                                   act=paddle_v2.activation.Softmax())
Q
qiaolongfei 已提交
82
    cost = paddle_v2.layer.classification_cost(input=inference, label=label)
Q
qiaolongfei 已提交
83

Y
Yu Yang 已提交
84
    # Create Simple Gradient Machine.
Q
qiaolongfei 已提交
85
    model_config = paddle_v2.layer.parse_network(cost)
Q
qiaolongfei 已提交
86 87 88
    m = api.GradientMachine.createFromConfigProto(model_config,
                                                  api.CREATE_MODE_NORMAL,
                                                  optimizer.enable_types())
Y
Yu Yang 已提交
89 90 91

    # This type check is not useful. Only enable type hint in IDE.
    # Such as PyCharm
Y
Yu Yang 已提交
92
    assert isinstance(m, api.GradientMachine)
Y
Yu Yang 已提交
93 94

    # Initialize Parameter by numpy.
Y
Yu Yang 已提交
95
    init_parameter(network=m)
Y
Yu Yang 已提交
96 97

    # Initialize ParameterUpdater.
Y
Yu Yang 已提交
98
    updater.init(m)
Y
Yu Yang 已提交
99

Y
Yu Yang 已提交
100 101
    # DataProvider Converter is a utility convert Python Object to Paddle C++
    # Input. The input format is as same as Paddle's DataProvider.
Q
qiaolongfei 已提交
102
    converter = DataProviderConverter(input_types=[images.type, label.type])
Y
Yu Yang 已提交
103 104

    train_file = './data/raw_data/train'
Y
Yu Yang 已提交
105
    test_file = './data/raw_data/t10k'
Y
Yu Yang 已提交
106

Y
Yu Yang 已提交
107 108 109
    # start gradient machine.
    # the gradient machine must be started before invoke forward/backward.
    # not just for training, but also for inference.
Y
Yu Yang 已提交
110 111
    m.start()

Y
Yu Yang 已提交
112 113 114 115 116 117 118 119
    # evaluator can print error rate, etc. It is a C++ class.
    batch_evaluator = m.makeEvaluator()
    test_evaluator = m.makeEvaluator()

    # Get Train Data.
    # TrainData will stored in a data pool. Currently implementation is not care
    # about memory, speed. Just a very naive implementation.
    train_data_generator = input_order_converter(read_from_mnist(train_file))
Y
Yu Yang 已提交
120
    train_data = BatchPool(train_data_generator, 512)
Y
Yu Yang 已提交
121 122 123 124 125 126

    # outArgs is Neural Network forward result. Here is not useful, just passed
    # to gradient_machine.forward
    outArgs = api.Arguments.createArguments(0)

    for pass_id in xrange(2):  # we train 2 passes.
Y
Yu Yang 已提交
127 128
        updater.startPass()

Y
Yu Yang 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142
        for batch_id, data_batch in enumerate(train_data()):
            # data_batch is input images.
            # here, for online learning, we could get data_batch from network.

            # Start update one batch.
            pass_type = updater.startBatch(len(data_batch))

            # Start BatchEvaluator.
            # batch_evaluator can be used between start/finish.
            batch_evaluator.start()

            # forwardBackward is a shortcut for forward and backward.
            # It is sometimes faster than invoke forward/backward separately,
            # because in GradientMachine, it may be async.
Y
Yu Yang 已提交
143 144 145 146
            m.forwardBackward(converter(data_batch), outArgs, pass_type)

            for each_param in m.getParameters():
                updater.update(each_param)
Y
Yu Yang 已提交
147

Y
Yu Yang 已提交
148
            # Get cost. We use numpy to calculate total cost for this batch.
Y
Yu Yang 已提交
149 150 151
            cost_vec = outArgs.getSlotValue(0)
            cost_vec = cost_vec.copyToNumpyMat()
            cost = cost_vec.sum() / len(data_batch)
Y
Yu Yang 已提交
152 153 154 155 156 157 158 159 160 161 162 163

            # Make evaluator works.
            m.eval(batch_evaluator)

            # Print logs.
            print 'Pass id', pass_id, 'Batch id', batch_id, 'with cost=', \
                cost, batch_evaluator

            batch_evaluator.finish()
            # Finish batch.
            #  * will clear gradient.
            #  * ensure all values should be updated.
Y
Yu Yang 已提交
164 165
            updater.finishBatch(cost)

Y
Yu Yang 已提交
166
        # testing stage. use test data set to test current network.
Y
Yu Yang 已提交
167
        updater.apply()
Y
Yu Yang 已提交
168 169
        test_evaluator.start()
        test_data_generator = input_order_converter(read_from_mnist(test_file))
Y
Yu Yang 已提交
170
        for data_batch in generator_to_batch(test_data_generator, 512):
Y
Yu Yang 已提交
171 172 173 174 175 176 177
            # in testing stage, only forward is needed.
            m.forward(converter(data_batch), outArgs, api.PASS_TEST)
            m.eval(test_evaluator)

        # print error rate for test data set
        print 'Pass', pass_id, ' test evaluator: ', test_evaluator
        test_evaluator.finish()
Y
Yu Yang 已提交
178 179 180 181 182 183 184
        updater.restore()

        updater.catchUpWith()
        params = m.getParameters()
        for each_param in params:
            assert isinstance(each_param, api.Parameter)
            value = each_param.getBuf(api.PARAMETER_VALUE)
Y
Yu Yang 已提交
185
            value = value.copyToNumpyArray()
Y
Yu Yang 已提交
186 187 188 189

            # Here, we could save parameter to every where you want
            print each_param.getName(), value

Y
Yu Yang 已提交
190 191
        updater.finishPass()

Y
Yu Yang 已提交
192
    m.finish()
Y
Yu Yang 已提交
193 194 195 196


if __name__ == '__main__':
    main()