imikolov.py 3.7 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 18
This module will download dataset from http://www.fit.vutbr.cz/~imikolov/rnnlm/ and
parse train/test set into paddle reader creators.
19 20 21 22
"""
import paddle.v2.dataset.common
import tarfile

23
__all__ = ['train', 'test', 'build_dict']
24 25 26 27 28 29

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


def word_count(f, word_freq=None):
Y
Yi Wang 已提交
30
    add = paddle.v2.dataset.common.dict_add
31 32 33 34 35 36 37 38 39 40 41 42
    if word_freq == None:
        word_freq = {}

    for l in f:
        for w in l.strip().split():
            add(word_freq, w)
        add(word_freq, '<s>')
        add(word_freq, '<e>')

    return word_freq


43
def build_dict():
Q
qijun 已提交
44 45 46
    """
    Build a word dictionary, the key is word, and the value is index.
    """
47 48
    train_filename = './simple-examples/data/ptb.train.txt'
    test_filename = './simple-examples/data/ptb.valid.txt'
49 50 51 52 53 54 55
    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))
56 57 58
        if '<unk>' in word_freq:
            # remove <unk> for now, since we will set it as last index
            del word_freq['<unk>']
59 60

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

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

    return word_idx


71
def reader_creator(filename, word_idx, n):
72 73 74 75 76 77 78
    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 已提交
79
            UNK = word_idx['<unk>']
80 81 82
            for l in f:
                l = ['<s>'] + l.strip().split() + ['<e>']
                if len(l) >= n:
Y
Yi Wang 已提交
83
                    l = [word_idx.get(w, UNK) for w in l]
84
                    for i in range(n, len(l) + 1):
Y
Yi Wang 已提交
85
                        yield tuple(l[i - n:i])
86 87 88 89

    return reader


90
def train(word_idx, n):
Q
qijun 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103
    """
    imikolov train set creator.

    It returns a reader creator, each sample in the reader is an index 
    tuple.

    :param word_idx: word dictionary
    :type word_idx: dict
    :param n: sliding window size
    :type n: int
    :return: Train reader creator
    :rtype: callable
    """
104
    return reader_creator('./simple-examples/data/ptb.train.txt', word_idx, n)
105 106


107
def test(word_idx, n):
Q
qijun 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120
    """
    imikolov test set creator.

    It returns a reader creator, each sample in the reader is an index 
    tuple.

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


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