imdb.py 4.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.
"""
Q
qijun 已提交
15
IMDB dataset.
Y
Yu Yang 已提交
16

Q
qijun 已提交
17 18 19 20
This module downloads IMDB dataset from
http://ai.stanford.edu/%7Eamaas/data/sentiment/. This dataset contains a set
of 25,000 highly polar movie reviews for training, and 25,000 for testing.
Besides, this module also provides API for building dictionary.
21
"""
D
dangqingqing 已提交
22

Y
Yi Wang 已提交
23
import paddle.v2.dataset.common
24
import collections
Y
Yi Wang 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37
import tarfile
import Queue
import re
import string
import threading

__all__ = ['build_dict', 'train', 'test']

URL = 'http://ai.stanford.edu/%7Eamaas/data/sentiment/aclImdb_v1.tar.gz'
MD5 = '7c2ac02c03563afcf9b574c7e56c153a'


def tokenize(pattern):
Q
qijun 已提交
38
    """
Q
qijun 已提交
39
    Read files that match the given pattern.  Tokenize and yield each file.
Q
qijun 已提交
40 41
    """

Y
Yi Wang 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    with tarfile.open(paddle.v2.dataset.common.download(URL, 'imdb',
                                                        MD5)) as tarf:
        # Note that we should use tarfile.next(), which does
        # sequential access of member files, other than
        # tarfile.extractfile, which does random access and might
        # destroy hard disks.
        tf = tarf.next()
        while tf != None:
            if bool(pattern.match(tf.name)):
                # newline and punctuations removal and ad-hoc tokenization.
                yield tarf.extractfile(tf).read().rstrip("\n\r").translate(
                    None, string.punctuation).lower().split()
            tf = tarf.next()


def build_dict(pattern, cutoff):
Q
qijun 已提交
58
    """
Q
qijun 已提交
59 60
    Build a word dictionary from the corpus. Keys of the dictionary are words,
    and values are zero-based IDs of these words.
Q
qijun 已提交
61
    """
62
    word_freq = collections.defaultdict(int)
Y
Yi Wang 已提交
63 64
    for doc in tokenize(pattern):
        for word in doc:
65
            word_freq[word] += 1
Y
Yi Wang 已提交
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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

    # Not sure if we should prune less-frequent words here.
    word_freq = filter(lambda x: x[1] > cutoff, word_freq.items())

    dictionary = sorted(word_freq, key=lambda x: (-x[1], x[0]))
    words, _ = list(zip(*dictionary))
    word_idx = dict(zip(words, xrange(len(words))))
    word_idx['<unk>'] = len(words)
    return word_idx


def reader_creator(pos_pattern, neg_pattern, word_idx, buffer_size):
    UNK = word_idx['<unk>']

    qs = [Queue.Queue(maxsize=buffer_size), Queue.Queue(maxsize=buffer_size)]

    def load(pattern, queue):
        for doc in tokenize(pattern):
            queue.put(doc)
        queue.put(None)

    def reader():
        # Creates two threads that loads positive and negative samples
        # into qs.
        t0 = threading.Thread(
            target=load, args=(
                pos_pattern,
                qs[0], ))
        t0.daemon = True
        t0.start()

        t1 = threading.Thread(
            target=load, args=(
                neg_pattern,
                qs[1], ))
        t1.daemon = True
        t1.start()

        # Read alternatively from qs[0] and qs[1].
        i = 0
        doc = qs[i].get()
        while doc != None:
            yield [word_idx.get(w, UNK) for w in doc], i % 2
            i += 1
            doc = qs[i % 2].get()

        # If any queue is empty, reads from the other queue.
        i += 1
        doc = qs[i % 2].get()
        while doc != None:
            yield [word_idx.get(w, UNK) for w in doc], i % 2
            doc = qs[i % 2].get()

    return reader()


def train(word_idx):
Q
qijun 已提交
123 124 125
    """
    IMDB train set creator.

Q
qijun 已提交
126
    It returns a reader creator, each sample in the reader is an zero-based ID
Q
qijun 已提交
127 128 129 130 131 132 133
    sequence and label in [0, 1].

    :param word_idx: word dictionary
    :type word_idx: dict
    :return: Train reader creator
    :rtype: callable
    """
Y
Yi Wang 已提交
134 135 136 137 138 139
    return reader_creator(
        re.compile("aclImdb/train/pos/.*\.txt$"),
        re.compile("aclImdb/train/neg/.*\.txt$"), word_idx, 1000)


def test(word_idx):
Q
qijun 已提交
140 141 142
    """
    IMDB test set creator.

Q
qijun 已提交
143
    It returns a reader creator, each sample in the reader is an zero-based ID
Q
qijun 已提交
144 145 146 147 148 149 150
    sequence and label in [0, 1].

    :param word_idx: word dictionary
    :type word_idx: dict
    :return: Test reader creator
    :rtype: callable
    """
Y
Yi Wang 已提交
151 152 153
    return reader_creator(
        re.compile("aclImdb/test/pos/.*\.txt$"),
        re.compile("aclImdb/test/neg/.*\.txt$"), word_idx, 1000)
H
hedaoyuan 已提交
154 155 156


def word_dict():
Q
qijun 已提交
157
    """
Q
qijun 已提交
158
    Build a word dictionary from the corpus.
Q
qijun 已提交
159 160 161 162

    :return: Word dictionary
    :rtype: dict
    """
H
hedaoyuan 已提交
163 164
    return build_dict(
        re.compile("aclImdb/((train)|(test))/((pos)|(neg))/.*\.txt$"), 150)
Y
Yancey1989 已提交
165 166


167
def fetch():
Y
Yancey1989 已提交
168
    paddle.v2.dataset.common.download(URL, 'imdb', MD5)