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

import re
4
import six
Q
Qiao Longfei 已提交
5
import argparse
J
JiabinYang 已提交
6
import io
Q
Qiao Longfei 已提交
7

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

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

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")
30 31 32 33 34 35
    parser.add_argument(
        '--is_local',
        action='store_true',
        required=False,
        default=False,
        help='Local train or not, (default: False)')
Q
Qiao Longfei 已提交
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50
    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 已提交
51 52 53
    return parser.parse_args()


Q
Qiao Longfei 已提交
54
def text_strip(text):
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)
        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

J
JiabinYang 已提交
201 202 203 204
    # if args.with_other_dict:
    #     with io.open(args.other_dict_path, 'r', encoding='utf-8') as f:
    #         for line in f:
    #             word_count[native_to_unicode(line.strip())] = 1
205

J
JiabinYang 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    # if args.is_local:
    #     for i in range(1, 100):
    #         with io.open(
    #                 args.data_path + "/news.en-000{:0>2d}-of-00100".format(i),
    #                 encoding='utf-8') as f:
    #             for line in f:
    #                 line = strip_lines(line)
    #                 words = line.split()
    #                 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
J
JiabinYang 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    # if args.is_local:
    #     with io.open(args.data_path + "/text8", encoding='utf-8') as f:
    #         for line in f:
    #             if args.with_other_dict:
    #                 line = strip_lines(line)
    #                 words = line.split()
    #                 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:
    #                 line = text_strip(line)
    #                 words = line.split()
    #                 for item in words:
    #                     if item in word_count:
    #                         word_count[item] = word_count[item] + 1
    #                     else:
    #                         word_count[item] = 1

    # item_to_remove = []
    # for item in word_count:
    #     if word_count[item] <= args.freq:
    #         item_to_remove.append(item)
    # for item in item_to_remove:
    #     del word_count[item]

    with io.open(args.dict_path, 'r', encoding='utf-8') as f:
        for line in f:
            word, count = line.split()[0], int(line.split()[1])
            word_count[word] = count
Q
Qiao Longfei 已提交
257

J
JiabinYang 已提交
258
    print(word_count)
259 260
    path_table, path_code, word_code_len = build_Huffman(word_count, 40)

J
JiabinYang 已提交
261
    with io.open(args.dict_path, 'w+', encoding='utf-8') as f:
Q
Qiao Longfei 已提交
262
        for k, v in word_count.items():
J
JiabinYang 已提交
263
            f.write(k + " " + str(v) + '\n')
Q
Qiao Longfei 已提交
264

J
JiabinYang 已提交
265
    with io.open(args.dict_path + "_ptable", 'w+', encoding='utf-8') as f2:
266
        for pk, pv in path_table.items():
J
JiabinYang 已提交
267
            f2.write(pk + '\t' + ' '.join((str(x) for x in pv)) + '\n')
268

J
JiabinYang 已提交
269
    with io.open(args.dict_path + "_pcode", 'w+', encoding='utf-8') as f3:
270
        for pck, pcv in path_code.items():
J
JiabinYang 已提交
271
            f3.write(pck + '\t' + ' '.join((str(x) for x in pcv)) + '\n')
272

Q
Qiao Longfei 已提交
273 274

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