preprocess.py 7.5 KB
Newer Older
Q
Qiao Longfei 已提交
1 2 3
# -*- coding: utf-8 -*

import re
4
import six
Q
Qiao Longfei 已提交
5 6
import argparse

7 8 9
prog = re.compile("[^a-z ]", flags=0)
word_count = dict()

Q
Qiao Longfei 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

def parse_args():
    parser = argparse.ArgumentParser(
        description="Paddle Fluid word2 vector preprocess")
    parser.add_argument(
        '--data_path',
        type=str,
        required=True,
        help="The path of training dataset")
    parser.add_argument(
        '--dict_path',
        type=str,
        default='./dict',
        help="The path of generated dict")
    parser.add_argument(
        '--freq',
        type=int,
        default=5,
        help="If the word count is less then freq, it will be removed from dict")
29 30 31 32 33 34
    parser.add_argument(
        '--is_local',
        action='store_true',
        required=False,
        default=False,
        help='Local train or not, (default: False)')
Q
Qiao Longfei 已提交
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49
    parser.add_argument(
        '--with_other_dict',
        action='store_true',
        required=False,
        default=False,
        help='Using third party provided dict , (default: False)')

    parser.add_argument(
        '--other_dict_path',
        type=str,
        default='',
        help='The path for third party provided dict (default: '
        ')')

Q
Qiao Longfei 已提交
50 51 52
    return parser.parse_args()


Q
Qiao Longfei 已提交
53
def text_strip(text):
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    return prog.sub("", text)


# users can self-define their own strip rules by modifing this method
def strip_lines(line, vocab=word_count):
    return _replace_oov(vocab, native_to_unicode(line))


# Shameless copy from Tensorflow https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/text_encoder.py
def _replace_oov(original_vocab, line):
    """Replace out-of-vocab words with "<UNK>".
  This maintains compatibility with published results.
  Args:
    original_vocab: a set of strings (The standard vocabulary for the dataset)
    line: a unicode string - a space-delimited sequence of words.
  Returns:
    a unicode string - a space-delimited sequence of words.
  """
    return u" ".join([
        word if word in original_vocab else u"<UNK>" for word in line.split()
    ])


# Shameless copy from Tensorflow https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/text_encoder.py
# Unicode utility functions that work with Python 2 and 3
def native_to_unicode(s):
    if _is_unicode(s):
        return s
    try:
        return _to_unicode(s)
    except UnicodeDecodeError:
        res = _to_unicode(s, ignore_errors=True)
        tf.logging.info("Ignoring Unicode error, outputting: %s" % res)
        return res


def _is_unicode(s):
    if six.PY2:
        if isinstance(s, unicode):
            return True
    else:
        if isinstance(s, str):
            return True
    return False


def _to_unicode(s, ignore_errors=False):
    if _is_unicode(s):
        return s
    error_mode = "ignore" if ignore_errors else "strict"
    return s.decode("utf-8", errors=error_mode)
Q
Qiao Longfei 已提交
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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
def build_Huffman(word_count, max_code_length):

    MAX_CODE_LENGTH = max_code_length
    sorted_by_freq = sorted(word_count.items(), key=lambda x: x[1])
    count = list()
    vocab_size = len(word_count)
    parent = [-1] * 2 * vocab_size
    code = [-1] * MAX_CODE_LENGTH
    point = [-1] * MAX_CODE_LENGTH
    binary = [-1] * 2 * vocab_size
    word_code_len = dict()
    word_code = dict()
    word_point = dict()
    i = 0
    for a in range(vocab_size):
        count.append(word_count[sorted_by_freq[a][0]])

    for a in range(vocab_size):
        word_point[sorted_by_freq[a][0]] = [-1] * MAX_CODE_LENGTH
        word_code[sorted_by_freq[a][0]] = [-1] * MAX_CODE_LENGTH

    for k in range(vocab_size):
        count.append(1e15)

    pos1 = vocab_size - 1
    pos2 = vocab_size
    min1i = 0
    min2i = 0
    b = 0

    for r in range(vocab_size):
        if pos1 >= 0:
            if count[pos1] < count[pos2]:
                min1i = pos1
                pos1 = pos1 - 1
            else:
                min1i = pos2
                pos2 = pos2 + 1
        else:
            min1i = pos2
            pos2 = pos2 + 1
        if pos1 >= 0:
            if count[pos1] < count[pos2]:
                min2i = pos1
                pos1 = pos1 - 1
            else:
                min2i = pos2
                pos2 = pos2 + 1
        else:
            min2i = pos2
            pos2 = pos2 + 1

        count[vocab_size + r] = count[min1i] + count[min2i]

        #record the parent of left and right child
        parent[min1i] = vocab_size + r
        parent[min2i] = vocab_size + r
        binary[min1i] = 0  #left branch has code 0
        binary[min2i] = 1  #right branch has code 1

    for a in range(vocab_size):
        b = a
        i = 0
        while True:
            code[i] = binary[b]
            point[i] = b
            i = i + 1
            b = parent[b]
            if b == vocab_size * 2 - 2:
                break

        word_code_len[sorted_by_freq[a][0]] = i
        word_point[sorted_by_freq[a][0]][0] = vocab_size - 2

        for k in range(i):
            word_code[sorted_by_freq[a][0]][i - k - 1] = code[k]

            # only non-leaf nodes will be count in
            if point[k] - vocab_size >= 0:
                word_point[sorted_by_freq[a][0]][i - k] = point[k] - vocab_size

    return word_point, word_code, word_code_len


191
def preprocess(args):
Q
Qiao Longfei 已提交
192
    """
Q
Qiao Longfei 已提交
193 194 195 196 197
    proprocess the data, generate dictionary and save into dict_path.
    :param data_path: the input data path.
    :param dict_path: the generated dict path. the data in dict is "word count"
    :param freq:
    :return:
Q
Qiao Longfei 已提交
198
    """
Q
Qiao Longfei 已提交
199 200
    # word to count

201 202 203 204 205 206
    if args.with_other_dict:
        with open(args.other_dict_path, 'r') as f:
            for line in f:
                word_count[native_to_unicode(line.strip())] = 1

    if args.is_local:
207
        for i in range(1, 100):
208
            with open(args.data_path + "/news.en-000{:0>2d}-of-00100".format(
209 210
                    i)) as f:
                for line in f:
211
                    line = strip_lines(line)
212
                    words = line.split()
J
JiabinYang 已提交
213 214 215 216 217 218 219 220 221 222 223 224
                    if args.with_other_dict:
                        for item in words:
                            if item in word_count:
                                word_count[item] = word_count[item] + 1
                            else:
                                word_count[native_to_unicode('<UNK>')] += 1
                    else:
                        for item in words:
                            if item in word_count:
                                word_count[item] = word_count[item] + 1
                            else:
                                word_count[item] = 1
Q
Qiao Longfei 已提交
225 226
    item_to_remove = []
    for item in word_count:
227
        if word_count[item] <= args.freq:
Q
Qiao Longfei 已提交
228 229 230 231
            item_to_remove.append(item)
    for item in item_to_remove:
        del word_count[item]

232 233
    path_table, path_code, word_code_len = build_Huffman(word_count, 40)

234
    with open(args.dict_path, 'w+') as f:
Q
Qiao Longfei 已提交
235
        for k, v in word_count.items():
236
            f.write(k.encode("utf-8") + " " + str(v).encode("utf-8") + '\n')
Q
Qiao Longfei 已提交
237

238
    with open(args.dict_path + "_ptable", 'w+') as f2:
239
        for pk, pv in path_table.items():
240 241 242
            f2.write(
                pk.encode("utf-8") + "\t" + ' '.join((str(x).encode("utf-8")
                                                      for x in pv)) + '\n')
243

244 245 246 247 248
    with open(args.dict_path + "_pcode", 'w+') as f3:
        for pck, pcv in path_code.items():
            f3.write(
                pck.encode("utf-8") + "\t" + ' '.join((str(x).encode("utf-8")
                                                       for x in pcv)) + '\n')
249

Q
Qiao Longfei 已提交
250 251

if __name__ == "__main__":
252
    preprocess(parse_args())