train.py 3.6 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 22 23
    # parse the argument
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'model',
        help='The model for image classification',
        choices=['alexnet', 'vgg13', 'vgg16', 'vgg19', 'resnet', 'googlenet'])
    args = parser.parse_args()
24 25

    # PaddlePaddle init
W
wwhu 已提交
26
    paddle.init(use_gpu=True, trainer_count=1)
27 28 29 30 31

    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 已提交
32 33

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

56 57 58 59 60 61 62 63 64 65
    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),
66
        learning_rate=learning_rate / BATCH_SIZE,
67 68 69 70 71
        learning_rate_decay_a=0.1,
        learning_rate_decay_b=128000 * 35,
        learning_rate_schedule="discexp", )

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

84 85 86 87 88 89 90
    # Create trainer
    trainer = paddle.trainer.SGD(
        cost=cost,
        parameters=parameters,
        update_equation=optimizer,
        extra_layers=extra_layers)

91 92 93 94 95 96 97 98
    # 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:
99
                trainer.save_parameter_to_tar(f)
100 101 102 103 104 105 106 107 108

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