test_image_classification_train.py 5.3 KB
Newer Older
1
import numpy as np
Q
Qiao Longfei 已提交
2
import paddle.v2 as paddle
Q
Qiao Longfei 已提交
3
import paddle.v2.fluid.core as core
Q
Qiao Longfei 已提交
4
import paddle.v2.fluid.framework as framework
Q
Qiao Longfei 已提交
5 6
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.nets as nets
F
fengjiayi 已提交
7
import paddle.v2.fluid.evaluator as evaluator
Q
Qiao Longfei 已提交
8 9
from paddle.v2.fluid.executor import Executor
from paddle.v2.fluid.initializer import XavierInitializer
Q
Qiao Longfei 已提交
10
from paddle.v2.fluid.optimizer import AdamOptimizer
Q
Qiao Longfei 已提交
11 12


13
def resnet_cifar10(input, depth=32):
Q
Qiao Longfei 已提交
14
    def conv_bn_layer(input, ch_out, filter_size, stride, padding, act='relu'):
Q
Qiao Longfei 已提交
15 16 17 18 19 20 21
        tmp = layers.conv2d(
            input=input,
            filter_size=filter_size,
            num_filters=ch_out,
            stride=stride,
            padding=padding,
            act=None,
22
            bias_attr=False)
Q
Qiao Longfei 已提交
23
        return layers.batch_norm(input=tmp, act=act)
Q
Qiao Longfei 已提交
24 25 26 27 28 29 30 31

    def shortcut(input, ch_in, ch_out, stride, program, init_program):
        if ch_in != ch_out:
            return conv_bn_layer(input, ch_out, 1, stride, 0, None, program,
                                 init_program)
        else:
            return input

Q
Qiao Longfei 已提交
32 33 34
    def basicblock(input, ch_in, ch_out, stride):
        tmp = conv_bn_layer(input, ch_out, 3, stride, 1)
        tmp = conv_bn_layer(tmp, ch_out, 3, 1, 1, act=None)
35
        short = shortcut(input, ch_in, ch_out, stride)
Q
Qiao Longfei 已提交
36
        return layers.elementwise_add(x=tmp, y=short, act='relu')
Q
Qiao Longfei 已提交
37

38 39
    def layer_warp(block_func, input, ch_in, ch_out, count, stride):
        tmp = block_func(input, ch_in, ch_out, stride)
Q
Qiao Longfei 已提交
40
        for i in range(1, count):
41
            tmp = block_func(tmp, ch_out, ch_out, 1)
Q
Qiao Longfei 已提交
42 43 44 45 46
        return tmp

    assert (depth - 2) % 6 == 0
    n = (depth - 2) / 6
    conv1 = conv_bn_layer(
Q
Qiao Longfei 已提交
47 48 49 50
        input=input, ch_out=16, filter_size=3, stride=1, padding=1)
    res1 = layer_warp(basicblock, conv1, 16, 16, n, 1)
    res2 = layer_warp(basicblock, res1, 16, 32, n, 2)
    res3 = layer_warp(basicblock, res2, 32, 64, n, 2)
Q
Qiao Longfei 已提交
51
    pool = layers.pool2d(
Q
Qiao Longfei 已提交
52
        input=res3, pool_size=8, pool_type='avg', pool_stride=1)
Q
Qiao Longfei 已提交
53 54 55
    return pool


56
def vgg16_bn_drop(input):
Q
Qiao Longfei 已提交
57
    def conv_block(input, num_filter, groups, dropouts):
Q
Qiao Longfei 已提交
58 59 60 61 62 63 64 65 66
        return nets.img_conv_group(
            input=input,
            pool_size=2,
            pool_stride=2,
            conv_num_filter=[num_filter] * groups,
            conv_filter_size=3,
            conv_act='relu',
            conv_with_batchnorm=True,
            conv_batchnorm_drop_rate=dropouts,
67
            pool_type='max')
Q
Qiao Longfei 已提交
68

69 70 71 72 73
    conv1 = conv_block(input, 64, 2, [0.3, 0])
    conv2 = conv_block(conv1, 128, 2, [0.4, 0])
    conv3 = conv_block(conv2, 256, 3, [0.4, 0.4, 0])
    conv4 = conv_block(conv3, 512, 3, [0.4, 0.4, 0])
    conv5 = conv_block(conv4, 512, 3, [0.4, 0.4, 0])
Q
Qiao Longfei 已提交
74

Q
Qiao Longfei 已提交
75
    drop = layers.dropout(x=conv5, dropout_prob=0.5)
Q
Qiao Longfei 已提交
76 77 78
    fc1 = layers.fc(input=drop,
                    size=512,
                    act=None,
79
                    param_attr={"initializer": XavierInitializer()})
Q
Qiao Longfei 已提交
80 81 82
    reshape1 = layers.reshape(x=fc1, shape=list(fc1.shape + (1, 1)))
    bn = layers.batch_norm(input=reshape1, act='relu')
    drop2 = layers.dropout(x=bn, dropout_prob=0.5)
Q
Qiao Longfei 已提交
83 84 85
    fc2 = layers.fc(input=drop2,
                    size=512,
                    act=None,
86
                    param_attr={"initializer": XavierInitializer()})
Q
Qiao Longfei 已提交
87 88 89 90 91 92
    return fc2


classdim = 10
data_shape = [3, 32, 32]

93 94
images = layers.data(name='pixel', shape=data_shape, data_type='float32')
label = layers.data(name='label', shape=[1], data_type='int64')
Q
Qiao Longfei 已提交
95 96 97

# Add neural network config
# option 1. resnet
98
# net = resnet_cifar10(images, 32)
Q
Qiao Longfei 已提交
99
# option 2. vgg
100
net = vgg16_bn_drop(images)
Q
Qiao Longfei 已提交
101 102 103

# print(program)

104 105 106
predict = layers.fc(input=net, size=classdim, act='softmax')
cost = layers.cross_entropy(input=predict, label=label)
avg_cost = layers.mean(x=cost)
Q
Qiao Longfei 已提交
107

Q
Qiao Longfei 已提交
108 109
# optimizer = SGDOptimizer(learning_rate=0.001)
optimizer = AdamOptimizer(learning_rate=0.001)
110
opts = optimizer.minimize(avg_cost)
Q
Qiao Longfei 已提交
111

F
fengjiayi 已提交
112 113
accuracy, acc_out = evaluator.accuracy(input=predict, label=label)

Q
Qiao Longfei 已提交
114 115 116 117 118 119 120 121 122 123 124
BATCH_SIZE = 128
PASS_NUM = 1

train_reader = paddle.batch(
    paddle.reader.shuffle(
        paddle.dataset.cifar.train10(), buf_size=128 * 10),
    batch_size=BATCH_SIZE)

place = core.CPUPlace()
exe = Executor(place)

125
exe.run(framework.default_startup_program())
Q
Qiao Longfei 已提交
126 127 128

for pass_id in range(PASS_NUM):
    batch_id = 0
F
fengjiayi 已提交
129
    accuracy.reset(exe)
Q
Qiao Longfei 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143
    for data in train_reader():
        img_data = np.array(map(lambda x: x[0].reshape(data_shape),
                                data)).astype("float32")
        y_data = np.array(map(lambda x: x[1], data)).astype("int64")
        batch_size = 1
        for i in y_data.shape:
            batch_size = batch_size * i
        y_data = y_data.reshape([batch_size, 1])

        tensor_img = core.LoDTensor()
        tensor_y = core.LoDTensor()
        tensor_img.set(img_data, place)
        tensor_y.set(y_data, place)

144
        outs = exe.run(framework.default_main_program(),
Q
Qiao Longfei 已提交
145 146
                       feed={"pixel": tensor_img,
                             "label": tensor_y},
F
fengjiayi 已提交
147
                       fetch_list=[avg_cost, acc_out])
Q
Qiao Longfei 已提交
148 149

        loss = np.array(outs[0])
150
        acc = np.array(outs[1])
F
fengjiayi 已提交
151
        pass_acc = accuracy.eval(exe)
Q
Qiao Longfei 已提交
152
        print("pass_id:" + str(pass_id) + " batch_id:" + str(batch_id) +
F
fengjiayi 已提交
153 154
              " loss:" + str(loss) + " acc:" + str(acc) + " pass_acc:" + str(
                  pass_acc))
Q
Qiao Longfei 已提交
155 156 157 158 159 160
        batch_id = batch_id + 1

        if batch_id > 1:
            # this model is slow, so if we can train two mini batch, we think it works properly.
            exit(0)
exit(1)