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
import resnet
import alexnet
import googlenet
9
import inception_v4
W
wwhu 已提交
10
import argparse
11 12

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


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

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

    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 已提交
36 37

    extra_layers = None
38
    learning_rate = 0.01
W
wwhu 已提交
39
    if args.model == 'alexnet':
W
wwhu 已提交
40
        out = alexnet.alexnet(image, class_dim=CLASS_DIM)
W
wwhu 已提交
41
    elif args.model == 'vgg13':
W
wwhu 已提交
42
        out = vgg.vgg13(image, class_dim=CLASS_DIM)
W
wwhu 已提交
43
    elif args.model == 'vgg16':
W
wwhu 已提交
44
        out = vgg.vgg16(image, class_dim=CLASS_DIM)
W
wwhu 已提交
45
    elif args.model == 'vgg19':
W
wwhu 已提交
46
        out = vgg.vgg19(image, class_dim=CLASS_DIM)
W
wwhu 已提交
47
    elif args.model == 'resnet':
W
wwhu 已提交
48
        out = resnet.resnet_imagenet(image, class_dim=CLASS_DIM)
49
        learning_rate = 0.1
W
wwhu 已提交
50
    elif args.model == 'googlenet':
W
wwhu 已提交
51
        out, out1, out2 = googlenet.googlenet(image, class_dim=CLASS_DIM)
W
wwhu 已提交
52 53 54 55 56 57 58
        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]
59 60
    elif args.model == 'inception_v4':
        out = inception_v4.inception_v4(image, class_dim=CLASS_DIM)
W
wwhu 已提交
61

62 63 64 65 66 67 68 69 70 71
    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),
72
        learning_rate=learning_rate / BATCH_SIZE,
73 74 75 76 77
        learning_rate_decay_a=0.1,
        learning_rate_decay_b=128000 * 35,
        learning_rate_schedule="discexp", )

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

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

97 98 99 100 101 102 103 104
    # 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:
105
                trainer.save_parameter_to_tar(f)
106 107 108 109 110 111 112 113 114

            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__':
115
    main()