mnist.py 7.3 KB
Newer Older
Q
qiaolongfei 已提交
1 2 3
import paddle.v2.framework.core as core
from paddle.v2.framework.op import Operator
import numpy
Q
qiaolongfei 已提交
4
import paddle.v2 as paddle
Q
qiaolongfei 已提交
5

Q
qiaolongfei 已提交
6
BATCH_SIZE = 100
Q
qiaolongfei 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

scope = core.Scope()
place = core.CPUPlace()
dev_ctx = core.DeviceContext.create(place)

# init_net = core.Net.create()
forward_network = core.Net.create()

# should be init after forward_op is constructed
# backward_net = core.Operator.backward(forward_net, set())
backward_net = None
optimize_net = core.Net.create()


def atom_id():
    id = 0
    while True:
        yield id
        id += 1


uniq_id = atom_id().next


def data_layer(name, dims):
    var = scope.new_var(name)
    tensor = var.get_tensor()
    tensor.set_dims(dims)  # 1 is batch size holder.
    return name


def feed_data(name, data):
Q
qiaolongfei 已提交
39
    assert isinstance(data, numpy.ndarray)
Q
qiaolongfei 已提交
40 41
    tensor = scope.find_var(name).get_tensor()
    tensor.set_dims(data.shape)
Q
qiaolongfei 已提交
42 43
    if data.dtype == numpy.dtype('int32'):
        tensor.alloc_int(place)
Q
qiaolongfei 已提交
44 45
    elif data.dtype == numpy.dtype('float32'):
        tensor.alloc_float(place)
Q
qiaolongfei 已提交
46 47
    else:
        raise ValueError("data type not supported")
Q
qiaolongfei 已提交
48 49 50 51 52 53 54
    tensor.set(data, place)


def grad_var_name(var_name):
    return var_name + "@GRAD"


Q
qiaolongfei 已提交
55
def sgd_optimizer(net, param_name, learning_rate=0.005):
Q
qiaolongfei 已提交
56 57
    grad_name = grad_var_name(param_name)
    optimize_op = Operator(
Q
qiaolongfei 已提交
58 59 60 61 62
        "sgd",
        param=param_name,
        grad=grad_name,
        param_out=param_name,
        learning_rate=learning_rate)
Q
qiaolongfei 已提交
63
    net.append_op(optimize_op)
Q
qiaolongfei 已提交
64 65 66 67 68 69 70 71


# should use operator and add these to the init_network
def init_param(param_name, dims):
    var = scope.new_var(param_name)
    tensor = var.get_tensor()
    tensor.set_dims(dims)
    data = numpy.random.uniform(
Q
qiaolongfei 已提交
72
        low=-0.5, high=0.5, size=tensor.shape()).astype("float32")
Q
qiaolongfei 已提交
73 74 75 76
    tensor.set(data, place)


# fc_layer
Q
qiaolongfei 已提交
77
def fc_layer(net, input, size, act="softmax", bias=True, param=None, name=None):
Q
qiaolongfei 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    """
    Add a fc layer to net

    :param input: input variable name.
    :type input: str
    :param size: fully connected layer size.
    :param act: activation name
    :param param: parameter attribute, used for initialize parameters.
    :param bias: bias attribute. False will not have a bias.
    :param name: the name of fc layer. If not set, model will generate a
    readable name
    :return: output variable name.
    """
    if name is None:
        name = 'fc_%d' % uniq_id()
    if not isinstance(name, str):
        raise ValueError("name should be string")

    input_dims = scope.find_var(input).get_tensor().get_dims()

    w_name = param or name + ".w"
    init_param(param_name=w_name, dims=[input_dims[1], size])
    sgd_optimizer(net=optimize_net, param_name=w_name, learning_rate=0.01)

    pre_activation = name + ".mul.out"
    scope.new_var(pre_activation)
    mul_op = Operator("mul", X=input, Y=w_name, Out=pre_activation)
Q
qiaolongfei 已提交
105
    net.append_op(mul_op)
Q
qiaolongfei 已提交
106 107 108 109 110 111

    # create bias variable if needed
    if bias:
        bias_name = name + ".b"
        init_param(param_name=bias_name, dims=[size])
        sgd_optimizer(
Q
qiaolongfei 已提交
112
            net=optimize_net, param_name=bias_name, learning_rate=0.001)
Q
qiaolongfei 已提交
113 114
        bias_out = name + ".rowwise_add.out"
        scope.new_var(bias_out)
Q
qiaolongfei 已提交
115
        rowwise_append_op = Operator(
Q
qiaolongfei 已提交
116
            "rowwise_add", X=pre_activation, b=bias_name, Out=bias_out)
Q
qiaolongfei 已提交
117
        net.append_op(rowwise_append_op)
Q
qiaolongfei 已提交
118 119 120
        pre_activation = bias_out

    activation_op = Operator(act, X=pre_activation, Y=name)
Q
qiaolongfei 已提交
121
    net.append_op(activation_op)
Q
qiaolongfei 已提交
122 123 124 125 126 127 128 129 130
    scope.new_var(name)
    net.infer_shape(scope)
    return name


def cross_entropy_layer(net, input, label):
    cost_name = 'cross_entropy_%d' % uniq_id()
    cross_entropy_op = Operator(
        "onehot_cross_entropy", X=input, label=label, Y=cost_name)
Q
qiaolongfei 已提交
131
    net.append_op(cross_entropy_op)
Q
qiaolongfei 已提交
132 133 134 135 136
    scope.new_var(cost_name)
    net.infer_shape(scope)
    return cost_name


Q
qiaolongfei 已提交
137
def create_backward_net(forward_net):
Q
qiaolongfei 已提交
138 139 140 141 142 143 144 145 146 147
    net = core.Operator.backward(forward_net, set())
    for input in net.inputs()["all"]:
        var = scope.new_var(input)
        var.get_tensor()
    for output in net.outputs()["all"]:
        var = scope.new_var(output)
        var.get_tensor()
    return net


Q
qiaolongfei 已提交
148
def debug_print_op(op):
Q
qiaolongfei 已提交
149 150 151 152
    print("===============" + op.type() + "==============")
    print("***inputs:***")
    for input in op.inputs()["all"]:
        print input, scope.find_var(input).get_tensor().get_dims()
Q
qiaolongfei 已提交
153
    print("\n***outputs:***")
Q
qiaolongfei 已提交
154 155 156 157 158 159
    for output in op.outputs()["all"]:
        print output, scope.find_var(output).get_tensor().get_dims()
    print("")
    print("")


Q
qiaolongfei 已提交
160 161 162 163
def set_cost(cost):
    cost_shape = numpy.array(scope.find_var(cost).get_tensor()).shape
    cost_grad = \
        scope.find_var(grad_var_name(cost)).get_tensor()
Q
qiaolongfei 已提交
164 165 166 167 168
    cost_grad.set_dims(cost_shape)
    cost_grad.alloc_float(place)
    cost_grad.set(numpy.ones(cost_shape).astype("float32"), place)


Q
qiaolongfei 已提交
169 170
def mean_cost(cost):
    cost_data = numpy.array(scope.find_var(cost).get_tensor())
Q
qiaolongfei 已提交
171
    return cost_data.sum() / len(cost_data)
Q
qiaolongfei 已提交
172

Q
qiaolongfei 已提交
173

Q
qiaolongfei 已提交
174 175 176 177 178
def error_rate(predict, label):
    predict_var = numpy.array(scope.find_var(predict).get_tensor()).argmax(
        axis=1)
    label = numpy.array(scope.find_var(label).get_tensor())
    error_num = numpy.sum(predict_var != label)
Q
qiaolongfei 已提交
179
    return error_num / float(len(label))
Q
qiaolongfei 已提交
180 181


Q
qiaolongfei 已提交
182
images = data_layer(name='pixel', dims=[BATCH_SIZE, 784])
Q
qiaolongfei 已提交
183
labels = data_layer(name='label', dims=[BATCH_SIZE])
Q
qiaolongfei 已提交
184 185 186
fc1 = fc_layer(net=forward_network, input=images, size=100, act="sigmoid")
fc2 = fc_layer(net=forward_network, input=fc1, size=100, act="sigmoid")
predict = fc_layer(net=forward_network, input=fc2, size=100, act="softmax")
Q
qiaolongfei 已提交
187
cost = cross_entropy_layer(net=forward_network, input=predict, label=labels)
Q
qiaolongfei 已提交
188

Q
qiaolongfei 已提交
189
forward_network.complete_add_op(True)
Q
qiaolongfei 已提交
190
backward_net = create_backward_net(forward_network)
Q
qiaolongfei 已提交
191
optimize_net.complete_add_op(True)
Q
qiaolongfei 已提交
192 193 194

print(forward_network)
print(backward_net)
Q
qiaolongfei 已提交
195
print(optimize_net)
Q
qiaolongfei 已提交
196

Q
qiaolongfei 已提交
197 198 199
debug_print_op(forward_network)
debug_print_op(backward_net)
debug_print_op(optimize_net)
Q
qiaolongfei 已提交
200

Q
qiaolongfei 已提交
201
train_reader = paddle.batch(
Q
qiaolongfei 已提交
202 203 204 205
    paddle.reader.shuffle(
        paddle.dataset.mnist.train(), buf_size=8192),
    batch_size=BATCH_SIZE)

Q
qiaolongfei 已提交
206

Q
qiaolongfei 已提交
207
def test(cost_name):
Q
qiaolongfei 已提交
208 209
    test_reader = paddle.batch(
        paddle.dataset.mnist.test(), batch_size=BATCH_SIZE)
Q
qiaolongfei 已提交
210 211 212
    cost = []
    error = []
    for data in test_reader():
Q
qiaolongfei 已提交
213 214 215 216
        image_data = numpy.array(map(lambda x: x[0], data)).astype("float32")
        label_data = numpy.array(map(lambda x: x[1], data)).astype("int32")
        feed_data(images, image_data)
        feed_data(labels, label_data)
Q
qiaolongfei 已提交
217 218 219

        forward_network.infer_shape(scope)
        forward_network.run(scope, dev_ctx)
Q
qiaolongfei 已提交
220
        cost.append(mean_cost(cost_name))
Q
qiaolongfei 已提交
221 222 223 224 225
        error.append(error_rate(predict, "label"))
    print("cost=" + str(sum(cost) / float(len(cost))) + " error_rate=" + str(
        sum(error) / float(len(error))))


Q
qiaolongfei 已提交
226
PASS_NUM = 1
Q
qiaolongfei 已提交
227
for pass_id in range(PASS_NUM):
Q
qiaolongfei 已提交
228
    batch_id = 0
Q
qiaolongfei 已提交
229

Q
qiaolongfei 已提交
230
    for data in train_reader():
Q
qiaolongfei 已提交
231 232 233 234
        image_data = numpy.array(map(lambda x: x[0], data)).astype("float32")
        label_data = numpy.array(map(lambda x: x[1], data)).astype("int32")
        feed_data(images, image_data)
        feed_data(labels, label_data)
Q
qiaolongfei 已提交
235

Q
qiaolongfei 已提交
236 237
        forward_network.infer_shape(scope)
        forward_network.run(scope, dev_ctx)
Q
qiaolongfei 已提交
238
        set_cost(cost)
Q
qiaolongfei 已提交
239 240
        backward_net.infer_shape(scope)
        backward_net.run(scope, dev_ctx)
Q
qiaolongfei 已提交
241

Q
qiaolongfei 已提交
242
        optimize_net.run(scope, dev_ctx)
Q
qiaolongfei 已提交
243 244
        if batch_id % 100 == 0:
            print("pass[" + str(pass_id) + "] batch_id[" + str(batch_id) + "]")
Q
qiaolongfei 已提交
245
            test(cost)
Q
qiaolongfei 已提交
246 247

        batch_id = batch_id + 1