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 36 37
    optimizer = paddle.optimizer.RMSProp(
        learning_rate=1e-3,
        gradient_clipping_threshold=10.0,
        regularization=paddle.optimizer.L2Regularization(rate=8e-4))
    trainer = paddle.trainer.SGD(
        cost=cost, parameters=parameters, update_equation=optimizer)
38

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

45
    # define the event_handler callback
C
caoying03 已提交
46 47
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
48 49 50 51 52
            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:
C
caoying03 已提交
53 54 55
                    parameters.to_tar(f)

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

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


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