imikolov.py 3.8 KB
Newer Older
D
dangqingqing 已提交
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
"""
Q
qijun 已提交
15
imikolov's simple dataset.
Y
Yu Yang 已提交
16

Q
qijun 已提交
17
This module will download dataset from 
Q
qijun 已提交
18 19
http://www.fit.vutbr.cz/~imikolov/rnnlm/ and parse training set and test set
into paddle reader creators.
20 21
"""
import paddle.v2.dataset.common
22
import collections
23 24
import tarfile

25
__all__ = ['train', 'test', 'build_dict']
26 27 28 29 30 31

URL = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz'
MD5 = '30177ea32e27c525793142b6bf2c8e2d'


def word_count(f, word_freq=None):
32 33
    if word_freq is None:
        word_freq = collections.defaultdict(int)
34 35 36

    for l in f:
        for w in l.strip().split():
37 38 39
            word_freq[w] += 1
        word_freq['<s>'] += 1
        word_freq['<e>'] += 1
40 41 42 43

    return word_freq


44
def build_dict():
Q
qijun 已提交
45
    """
Q
qijun 已提交
46 47
    Build a word dictionary from the corpus,  Keys of the dictionary are words,
    and values are zero-based IDs of these words.
Q
qijun 已提交
48
    """
49 50
    train_filename = './simple-examples/data/ptb.train.txt'
    test_filename = './simple-examples/data/ptb.valid.txt'
51 52 53 54 55 56 57
    with tarfile.open(
            paddle.v2.dataset.common.download(
                paddle.v2.dataset.imikolov.URL, 'imikolov',
                paddle.v2.dataset.imikolov.MD5)) as tf:
        trainf = tf.extractfile(train_filename)
        testf = tf.extractfile(test_filename)
        word_freq = word_count(testf, word_count(trainf))
58 59 60
        if '<unk>' in word_freq:
            # remove <unk> for now, since we will set it as last index
            del word_freq['<unk>']
61 62

        TYPO_FREQ = 50
Y
Yi Wang 已提交
63
        word_freq = filter(lambda x: x[1] > TYPO_FREQ, word_freq.items())
64

65 66
        word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0]))
        words, _ = list(zip(*word_freq_sorted))
67
        word_idx = dict(zip(words, xrange(len(words))))
Y
Yi Wang 已提交
68
        word_idx['<unk>'] = len(words)
69 70 71 72

    return word_idx


73
def reader_creator(filename, word_idx, n):
74 75 76 77 78 79 80
    def reader():
        with tarfile.open(
                paddle.v2.dataset.common.download(
                    paddle.v2.dataset.imikolov.URL, 'imikolov',
                    paddle.v2.dataset.imikolov.MD5)) as tf:
            f = tf.extractfile(filename)

Y
Yi Wang 已提交
81
            UNK = word_idx['<unk>']
82 83 84
            for l in f:
                l = ['<s>'] + l.strip().split() + ['<e>']
                if len(l) >= n:
Y
Yi Wang 已提交
85
                    l = [word_idx.get(w, UNK) for w in l]
86
                    for i in range(n, len(l) + 1):
Y
Yi Wang 已提交
87
                        yield tuple(l[i - n:i])
88 89 90 91

    return reader


92
def train(word_idx, n):
Q
qijun 已提交
93
    """
Q
qijun 已提交
94
    imikolov training set creator.
Q
qijun 已提交
95

Q
qijun 已提交
96
    It returns a reader creator, each sample in the reader is a word ID
Q
qijun 已提交
97 98 99 100 101 102
    tuple.

    :param word_idx: word dictionary
    :type word_idx: dict
    :param n: sliding window size
    :type n: int
Q
qijun 已提交
103
    :return: Training reader creator
Q
qijun 已提交
104 105
    :rtype: callable
    """
106
    return reader_creator('./simple-examples/data/ptb.train.txt', word_idx, n)
107 108


109
def test(word_idx, n):
Q
qijun 已提交
110 111 112
    """
    imikolov test set creator.

Q
qijun 已提交
113
    It returns a reader creator, each sample in the reader is a word ID
Q
qijun 已提交
114 115 116 117 118 119
    tuple.

    :param word_idx: word dictionary
    :type word_idx: dict
    :param n: sliding window size
    :type n: int
Q
qijun 已提交
120
    :return: Test reader creator
Q
qijun 已提交
121 122
    :rtype: callable
    """
123
    return reader_creator('./simple-examples/data/ptb.valid.txt', word_idx, n)
Y
Yancey1989 已提交
124 125


126
def fetch():
Y
Yancey1989 已提交
127
    paddle.v2.dataset.common.download(URL, "imikolov", MD5)