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

import numpy as np
Q
Qiao Longfei 已提交
4
import preprocess
Q
Qiao Longfei 已提交
5

J
JiabinYang 已提交
6 7 8 9 10 11
import logging

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("fluid")
logger.setLevel(logging.INFO)

Q
Qiao Longfei 已提交
12

Q
Qiao Longfei 已提交
13
class Word2VecReader(object):
14 15 16 17 18 19 20
    def __init__(self,
                 dict_path,
                 data_path,
                 filelist,
                 trainer_id,
                 trainer_num,
                 window_size=5):
Q
Qiao Longfei 已提交
21 22
        self.window_size_ = window_size
        self.data_path_ = data_path
23
        self.filelist = filelist
24
        self.num_non_leaf = 0
Q
Qiao Longfei 已提交
25
        self.word_to_id_ = dict()
26 27 28
        self.id_to_word = dict()
        self.word_to_path = dict()
        self.word_to_code = dict()
29 30
        self.trainer_id = trainer_id
        self.trainer_num = trainer_num
Q
Qiao Longfei 已提交
31

32 33
        word_all_count = 0
        word_counts = []
Q
Qiao Longfei 已提交
34
        word_id = 0
35

Q
Qiao Longfei 已提交
36 37
        with open(dict_path, 'r') as f:
            for line in f:
38
                line = line.decode(encoding='UTF-8')
39 40
                word, count = line.split()[0], int(line.split()[1])
                self.word_to_id_[word] = word_id
41
                self.id_to_word[word_id] = word  #build id to word dict
Q
Qiao Longfei 已提交
42
                word_id += 1
43 44 45
                word_counts.append(count)
                word_all_count += count

46 47
        with open(dict_path + "_word_to_id_", 'w+') as f6:
            for k, v in self.word_to_id_.items():
48 49
                f6.write(
                    k.encode("utf-8") + " " + str(v).encode("utf-8") + '\n')
50

Q
Qiao Longfei 已提交
51
        self.dict_size = len(self.word_to_id_)
52 53 54 55 56 57 58 59
        self.word_frequencys = [
            float(count) / word_all_count for count in word_counts
        ]
        print("dict_size = " + str(
            self.dict_size)) + " word_all_count = " + str(word_all_count)

        with open(dict_path + "_ptable", 'r') as f2:
            for line in f2:
60 61
                self.word_to_path[line.split("\t")[0]] = np.fromstring(
                    line.split('\t')[1], dtype=int, sep=' ')
62
                self.num_non_leaf = np.fromstring(
63
                    line.split('\t')[1], dtype=int, sep=' ')[0]
64 65 66 67
        print("word_ptable dict_size = " + str(len(self.word_to_path)))

        with open(dict_path + "_pcode", 'r') as f3:
            for line in f3:
68 69 70
                line = line.decode(encoding='UTF-8')
                self.word_to_code[line.split("\t")[0]] = np.fromstring(
                    line.split('\t')[1], dtype=int, sep=' ')
71
        print("word_pcode dict_size = " + str(len(self.word_to_code)))
Q
Qiao Longfei 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    def get_context_words(self, words, idx, window_size):
        """
        Get the context word list of target word.

        words: the words of the current line
        idx: input word index
        window_size: window size
        """
        target_window = np.random.randint(1, window_size + 1)
        # need to keep in mind that maybe there are no enough words before the target word.
        start_point = idx - target_window if (idx - target_window) > 0 else 0
        end_point = idx + target_window
        # context words of the target word
        targets = set(words[start_point:idx] + words[idx + 1:end_point + 1])
        return list(targets)

89
    def train(self, with_hs):
Q
Qiao Longfei 已提交
90
        def _reader():
91 92
            for file in self.filelist:
                with open(self.data_path_ + "/" + file, 'r') as f:
J
JiabinYang 已提交
93 94
                    logger.info("running data in {}".format(self.data_path_ +
                                                            "/" + file))
95
                    count = 1
96
                    for line in f:
97
                        if self.trainer_id == count % self.trainer_num:
98
                            line = preprocess.strip_lines(line)
99 100 101 102 103 104 105 106 107 108 109 110
                            word_ids = [
                                self.word_to_id_[word] for word in line.split()
                                if word in self.word_to_id_
                            ]
                            for idx, target_id in enumerate(word_ids):
                                context_word_ids = self.get_context_words(
                                    word_ids, idx, self.window_size_)
                                for context_id in context_word_ids:
                                    yield [target_id], [context_id]
                        else:
                            pass
                        count += 1
Q
Qiao Longfei 已提交
111

112
        def _reader_hs():
113 114
            for file in self.filelist:
                with open(self.data_path_ + "/" + file, 'r') as f:
J
JiabinYang 已提交
115 116
                    logger.info("running data in {}".format(self.data_path_ +
                                                            "/" + file))
117
                    count = 1
118
                    for line in f:
119
                        if self.trainer_id == count % self.trainer_num:
120
                            line = preprocess.strip_lines(line)
121 122 123 124 125 126 127 128 129 130
                            word_ids = [
                                self.word_to_id_[word] for word in line.split()
                                if word in self.word_to_id_
                            ]
                            for idx, target_id in enumerate(word_ids):
                                context_word_ids = self.get_context_words(
                                    word_ids, idx, self.window_size_)
                                for context_id in context_word_ids:
                                    yield [target_id], [context_id], [
                                        self.word_to_code[self.id_to_word[
J
JiabinYang 已提交
131
                                            target_id]]
132 133
                                    ], [
                                        self.word_to_path[self.id_to_word[
J
JiabinYang 已提交
134
                                            target_id]]
135 136 137 138
                                    ]
                        else:
                            pass
                        count += 1
139 140 141 142 143

        if not with_hs:
            return _reader
        else:
            return _reader_hs
Q
Qiao Longfei 已提交
144 145 146


if __name__ == "__main__":
Q
Qiao Longfei 已提交
147
    window_size = 10
Q
Qiao Longfei 已提交
148

Q
Qiao Longfei 已提交
149
    reader = Word2VecReader("data/enwik9_dict", "data/enwik9", window_size)
Q
Qiao Longfei 已提交
150
    i = 0
Q
Qiao Longfei 已提交
151
    for x, y in reader.train()():
Q
Qiao Longfei 已提交
152 153 154 155 156 157
        print("x: " + str(x))
        print("y: " + str(y))
        print("\n")
        if i == 10:
            exit(0)
        i += 1