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

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


def main():
W
wwhu 已提交
17 18 19 20 21 22 23 24 25 26
    # parse the argument
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'data_dir',
        help='The data directory which contains train.list and val.list')
    parser.add_argument(
        'model',
        help='The model for image classification',
        choices=['alexnet', 'vgg13', 'vgg16', 'vgg19', 'resnet', 'googlenet'])
    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 37

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

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

    train_reader = paddle.batch(
W
wwhu 已提交
73 74 75
        paddle.reader.shuffle(
            reader.test_reader(os.path.join(args.data_dir, 'train.list')),
            buf_size=1000),
76 77
        batch_size=BATCH_SIZE)
    test_reader = paddle.batch(
W
wwhu 已提交
78 79
        reader.train_reader(os.path.join(args.data_dir, 'val.list')),
        batch_size=BATCH_SIZE)
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

    # 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:
                parameters.to_tar(f)

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

    # Create trainer
    trainer = paddle.trainer.SGD(
W
wwhu 已提交
96 97 98 99
        cost=cost,
        parameters=parameters,
        update_equation=optimizer,
        extra_layers=extra_layers)
100 101 102 103 104 105 106

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


if __name__ == '__main__':
    main()