train.py 3.8 KB
Newer Older
1
import gzip
W
wwhu 已提交
2
import paddle.v2.dataset.flowers as flowers
3 4 5
import paddle.v2 as paddle
import reader
import vgg
W
wwhu 已提交
6 7 8 9
import resnet
import alexnet
import googlenet
import argparse
10 11

DATA_DIM = 3 * 224 * 224
W
wwhu 已提交
12
CLASS_DIM = 102
13 14 15 16
BATCH_SIZE = 128


def main():
W
wwhu 已提交
17 18 19 20 21
    # parse the argument
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'model',
        help='The model for image classification',
22 23 24 25
        choices=[
            'alexnet', 'vgg13', 'vgg16', 'vgg19', 'resnet', 'googlenet',
            'xception'
        ])
W
wwhu 已提交
26
    args = parser.parse_args()
27 28

    # PaddlePaddle init
W
wwhu 已提交
29
    paddle.init(use_gpu=True, trainer_count=1)
30 31 32 33 34

    image = paddle.layer.data(
        name="image", type=paddle.data_type.dense_vector(DATA_DIM))
    lbl = paddle.layer.data(
        name="label", type=paddle.data_type.integer_value(CLASS_DIM))
W
wwhu 已提交
35 36

    extra_layers = None
37
    learning_rate = 0.01
W
wwhu 已提交
38
    if args.model == 'alexnet':
W
wwhu 已提交
39
        out = alexnet.alexnet(image, class_dim=CLASS_DIM)
W
wwhu 已提交
40
    elif args.model == 'vgg13':
W
wwhu 已提交
41
        out = vgg.vgg13(image, class_dim=CLASS_DIM)
W
wwhu 已提交
42
    elif args.model == 'vgg16':
W
wwhu 已提交
43
        out = vgg.vgg16(image, class_dim=CLASS_DIM)
W
wwhu 已提交
44
    elif args.model == 'vgg19':
W
wwhu 已提交
45
        out = vgg.vgg19(image, class_dim=CLASS_DIM)
W
wwhu 已提交
46
    elif args.model == 'resnet':
W
wwhu 已提交
47
        out = resnet.resnet_imagenet(image, class_dim=CLASS_DIM)
48
        learning_rate = 0.1
W
wwhu 已提交
49
    elif args.model == 'googlenet':
W
wwhu 已提交
50
        out, out1, out2 = googlenet.googlenet(image, class_dim=CLASS_DIM)
W
wwhu 已提交
51 52 53 54 55 56 57
        loss1 = paddle.layer.cross_entropy_cost(
            input=out1, label=lbl, coeff=0.3)
        paddle.evaluator.classification_error(input=out1, label=lbl)
        loss2 = paddle.layer.cross_entropy_cost(
            input=out2, label=lbl, coeff=0.3)
        paddle.evaluator.classification_error(input=out2, label=lbl)
        extra_layers = [loss1, loss2]
58 59
    elif args.model == 'xception':
        out = xception.xception(image, class_dim=CLASS_DIM)
W
wwhu 已提交
60

61 62 63 64 65 66 67 68 69 70
    cost = paddle.layer.classification_cost(input=out, label=lbl)

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

    # Create optimizer
    optimizer = paddle.optimizer.Momentum(
        momentum=0.9,
        regularization=paddle.optimizer.L2Regularization(rate=0.0005 *
                                                         BATCH_SIZE),
71
        learning_rate=learning_rate / BATCH_SIZE,
72 73 74 75 76
        learning_rate_decay_a=0.1,
        learning_rate_decay_b=128000 * 35,
        learning_rate_schedule="discexp", )

    train_reader = paddle.batch(
W
wwhu 已提交
77
        paddle.reader.shuffle(
W
wwhu 已提交
78 79
            flowers.train(),
            # To use other data, replace the above line with:
80
            # reader.train_reader('train.list'),
W
wwhu 已提交
81
            buf_size=1000),
82 83
        batch_size=BATCH_SIZE)
    test_reader = paddle.batch(
W
wwhu 已提交
84 85
        flowers.valid(),
        # To use other data, replace the above line with:
86
        # reader.test_reader('val.list'),
W
wwhu 已提交
87
        batch_size=BATCH_SIZE)
88

89 90 91 92 93 94 95
    # Create trainer
    trainer = paddle.trainer.SGD(
        cost=cost,
        parameters=parameters,
        update_equation=optimizer,
        extra_layers=extra_layers)

96 97 98 99 100 101 102 103
    # End batch and end pass event handler
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 1 == 0:
                print "\nPass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics)
        if isinstance(event, paddle.event.EndPass):
            with gzip.open('params_pass_%d.tar.gz' % event.pass_id, 'w') as f:
104
                trainer.save_parameter_to_tar(f)
105 106 107 108 109 110 111 112 113

            result = trainer.test(reader=test_reader)
            print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

    trainer.train(
        reader=train_reader, num_passes=200, event_handler=event_handler)


if __name__ == '__main__':
114
    main()