utils.py 7.3 KB
Newer Older
M
mapingshuo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14 15 16 17 18 19 20 21 22
"""
This module provides utilities for data generator and optimizer definition 
"""

import sys
import time
import numpy as np

import paddle.fluid as fluid
M
mapingshuo 已提交
23
import paddle
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import quora_question_pairs


def to_lodtensor(data, place):
    """
    convert to LODtensor
    """
    seq_lens = [len(seq) for seq in data]
    cur_len = 0
    lod = [cur_len]
    for l in seq_lens:
        cur_len += l
        lod.append(cur_len)
    flattened_data = np.concatenate(data, axis=0).astype("int64")
    flattened_data = flattened_data.reshape([len(flattened_data), 1])
    res = fluid.LoDTensor()
    res.set(flattened_data, place)
    res.set_lod([lod])
    return res


def getOptimizer(global_config):
    """
    get Optimizer by config
    """
    if global_config.optimizer_type == "adam":
Y
Yibing Liu 已提交
50 51 52 53 54 55
        optimizer = fluid.optimizer.Adam(
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=global_config.learning_rate,
                decay_steps=global_config.train_samples_num //
                global_config.batch_size,
                decay_rate=global_config.lr_decay))
56
    elif global_config.optimizer_type == "sgd":
Y
Yibing Liu 已提交
57 58 59 60 61 62
        optimizer = fluid.optimizer.SGD(
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=global_config.learning_rate,
                decay_steps=global_config.train_samples_num //
                global_config.batch_size,
                decay_rate=global_config.lr_decay))
63 64

    elif global_config.optimizer_type == "adagrad":
Y
Yibing Liu 已提交
65 66 67 68 69 70
        optimizer = fluid.optimizer.Adagrad(
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=global_config.learning_rate,
                decay_steps=global_config.train_samples_num //
                global_config.batch_size,
                decay_rate=global_config.lr_decay))
71 72 73 74 75 76 77

    return optimizer


def get_pretrained_word_embedding(word2vec, word2id, config):
    """get pretrained embedding in shape [config.dict_dim, config.emb_dim]"""
    print("preparing pretrained word embedding ...")
Y
Yibing Liu 已提交
78 79
    assert (config.dict_dim >= len(word2id))
    word2id = sorted(word2id.items(), key=lambda x: x[1])
80 81 82 83 84
    words = [x[0] for x in word2id]
    words = words + ['<not-a-real-words>'] * (config.dict_dim - len(words))
    pretrained_emb = []
    for _, word in enumerate(words):
        if word in word2vec:
Y
Yibing Liu 已提交
85
            assert (len(word2vec[word] == config.emb_dim))
86
            if config.embedding_norm:
Y
Yibing Liu 已提交
87 88
                pretrained_emb.append(word2vec[word] /
                                      np.linalg.norm(word2vec[word]))
89 90 91
            else:
                pretrained_emb.append(word2vec[word])
        elif config.OOV_fill == 'uniform':
Y
Yibing Liu 已提交
92 93 94
            pretrained_emb.append(
                np.random.uniform(
                    -0.05, 0.05, size=[config.emb_dim]).astype(np.float32))
95
        elif config.OOV_fill == 'normal':
Y
Yibing Liu 已提交
96 97 98 99
            pretrained_emb.append(
                np.random.normal(
                    loc=0.0, scale=0.1, size=[config.emb_dim]).astype(
                        np.float32))
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        else:
            print("Unkown OOV fill method: ", OOV_fill)
            exit()
    word_embedding = np.stack(pretrained_emb)
    return word_embedding


def getDict(data_type="quora_question_pairs"):
    """
    get word2id dict from quora dataset
    """
    print("Generating word dict...")
    if data_type == "quora_question_pairs":
        word_dict = quora_question_pairs.word_dict()
    else:
        raise RuntimeError("No such dataset")
    print("Vocab size: ", len(word_dict))
    return word_dict


def duplicate(reader):
    """
    duplicate the quora qestion pairs since there are 2 questions in a sample
    Input: reader, which yield (question1, question2, label)
    Output: reader, which yield (question1, question2, label) and yield (question2, question1, label)
    """

    def duplicated_reader():
        for data in reader():
            (q1, q2, label) = data
            yield (q1, q2, label)
            yield (q2, q1, label)

    return duplicated_reader


def pad(reader, PAD_ID):
    """
    Input: reader, yield batches of [(question1, question2, label), ... ]
    Output: padded_reader, yield batches of [(padded_question1, padded_question2, mask1, mask2, label), ... ]
    """

Y
Yibing Liu 已提交
142
    assert (isinstance(PAD_ID, int))
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

    def padded_reader():
        for batch in reader():
            max_len1 = max([len(data[0]) for data in batch])
            max_len2 = max([len(data[1]) for data in batch])

            padded_batch = []
            for data in batch:
                question1, question2, label = data
                seq_len1 = len(question1)
                seq_len2 = len(question2)
                mask1 = [1] * seq_len1 + [0] * (max_len1 - seq_len1)
                mask2 = [1] * seq_len2 + [0] * (max_len2 - seq_len2)
                padded_question1 = question1 + [PAD_ID] * (max_len1 - seq_len1)
                padded_question2 = question2 + [PAD_ID] * (max_len2 - seq_len2)
Y
Yibing Liu 已提交
158 159 160
                padded_question1 = [
                    [x] for x in padded_question1
                ]  # last dim of questions must be 1, according to fluid's request
161
                padded_question2 = [[x] for x in padded_question2]
Y
Yibing Liu 已提交
162 163 164 165 166 167
                assert (len(mask1) == max_len1)
                assert (len(mask2) == max_len2)
                assert (len(padded_question1) == max_len1)
                assert (len(padded_question2) == max_len2)
                padded_batch.append(
                    (padded_question1, padded_question2, mask1, mask2, label))
168
            yield padded_batch
Y
Yibing Liu 已提交
169

170 171 172 173 174 175 176 177 178 179 180 181 182
    return padded_reader


def prepare_data(data_type,
                 word_dict,
                 batch_size,
                 buf_size=50000,
                 duplicate_data=False,
                 use_pad=False):
    """
    prepare data
    """

Y
Yibing Liu 已提交
183
    PAD_ID = word_dict['<pad>']
184 185

    if data_type == "quora_question_pairs":
Y
Yibing Liu 已提交
186 187 188 189 190
        # train/dev/test reader are batched iters which yield a batch of (question1, question2, label) each time
        # qestion1 and question2 are lists of word ID
        # label is 0 or 1
        # for example: ([1, 3, 2], [7, 5, 4, 99], 1)

191 192 193 194
        def prepare_reader(reader):
            if duplicate_data:
                reader = duplicate(reader)
            reader = paddle.batch(
Y
Yibing Liu 已提交
195 196 197 198
                paddle.reader.shuffle(
                    reader, buf_size=buf_size),
                batch_size=batch_size,
                drop_last=False)
199 200 201
            if use_pad:
                reader = pad(reader, PAD_ID=PAD_ID)
            return reader
Y
Yibing Liu 已提交
202

203 204 205 206 207 208 209 210
        train_reader = prepare_reader(quora_question_pairs.train(word_dict))
        dev_reader = prepare_reader(quora_question_pairs.dev(word_dict))
        test_reader = prepare_reader(quora_question_pairs.test(word_dict))

    else:
        raise RuntimeError("no such dataset")

    return train_reader, dev_reader, test_reader