train.py 2.2 KB
Newer Older
1 2 3
import os
import logging
import paddle.v2 as paddle
C
caoying03 已提交
4

5
from network_conf import seq2seq_net
C
caoying03 已提交
6

7 8
logger = logging.getLogger("paddle")
logger.setLevel(logging.INFO)
C
caoying03 已提交
9

10 11

def train(save_dir_path, source_dict_dim, target_dict_dim):
C
caoying03 已提交
12 13 14
    '''
    Training function for NMT

15 16
    :param save_dir_path: path of the directory to save the trained models.
    :param save_dir_path: str
C
caoying03 已提交
17 18 19 20 21
    :param source_dict_dim: size of source dictionary
    :type source_dict_dim: int
    :param target_dict_dim: size of target dictionary
    :type target_dict_dim: int
    '''
22 23 24 25
    if not os.path.exists(save_dir_path):
        os.mkdir(save_dir_path)

    # initialize PaddlePaddle
C
caoying03 已提交
26 27 28 29 30
    paddle.init(use_gpu=False, trainer_count=1)

    cost = seq2seq_net(source_dict_dim, target_dict_dim)
    parameters = paddle.parameters.create(cost)

31
    # define optimization method and the trainer instance
C
caoying03 已提交
32 33 34 35
    optimizer = paddle.optimizer.RMSProp(
        learning_rate=1e-3,
        gradient_clipping_threshold=10.0,
        regularization=paddle.optimizer.L2Regularization(rate=8e-4))
36 37 38
    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=optimizer)
39

C
caoying03 已提交
40 41 42 43 44 45
    # define data reader
    wmt14_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.wmt14.train(source_dict_dim), buf_size=8192),
        batch_size=8)

46
    # define the event_handler callback
C
caoying03 已提交
47 48
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
49 50 51 52 53
            if not event.batch_id % 100 and event.batch_id:
                with gzip.open(
                        os.path.join(save_path,
                                     "nmt_without_att_%05d_batch_%05d.tar.gz" %
                                     event.pass_id, event.batch_id), "w") as f:
54
                    trainer.save_parameter_to_tar(f)
C
caoying03 已提交
55 56

            if event.batch_id and not event.batch_id % 10:
57 58 59 60
                logger.info("Pass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics))

    # start training
C
caoying03 已提交
61 62 63 64 65
    trainer.train(
        reader=wmt14_reader, event_handler=event_handler, num_passes=2)


if __name__ == '__main__':
66
    train(save_dir_path="models", source_dict_dim=30000, target_dict_dim=30000)