imdb.py 4.3 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
import tarfile
import re
import string

Y
Your Name 已提交
29
__all__ = ['build_dict', 'train', 'test', 'convert']
Y
Yi Wang 已提交
30 31 32 33 34 35

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


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

Y
Yi Wang 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    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 已提交
56
    """
Q
qijun 已提交
57 58
    Build a word dictionary from the corpus. Keys of the dictionary are words,
    and values are zero-based IDs of these words.
Q
qijun 已提交
59
    """
60
    word_freq = collections.defaultdict(int)
Y
Yi Wang 已提交
61 62
    for doc in tokenize(pattern):
        for word in doc:
63
            word_freq[word] += 1
Y
Yi Wang 已提交
64 65 66 67 68 69 70 71 72 73 74

    # 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


D
dangqingqing 已提交
75
def reader_creator(pos_pattern, neg_pattern, word_idx):
Y
Yi Wang 已提交
76
    UNK = word_idx['<unk>']
D
dangqingqing 已提交
77
    INS = []
Y
Yi Wang 已提交
78

D
dangqingqing 已提交
79
    def load(pattern, out, label):
Y
Yi Wang 已提交
80
        for doc in tokenize(pattern):
D
dangqingqing 已提交
81 82 83 84
            out.append(([word_idx.get(w, UNK) for w in doc], label))

    load(pos_pattern, INS, 0)
    load(neg_pattern, INS, 1)
Y
Yi Wang 已提交
85 86

    def reader():
D
dangqingqing 已提交
87 88
        for doc, label in INS:
            yield doc, label
Y
Yi Wang 已提交
89

F
fengjiayi 已提交
90
    return reader
Y
Yi Wang 已提交
91 92 93


def train(word_idx):
Q
qijun 已提交
94
    """
Q
qijun 已提交
95
    IMDB training set creator.
Q
qijun 已提交
96

Q
qijun 已提交
97
    It returns a reader creator, each sample in the reader is an zero-based ID
Q
qijun 已提交
98 99 100 101
    sequence and label in [0, 1].

    :param word_idx: word dictionary
    :type word_idx: dict
Q
qijun 已提交
102
    :return: Training reader creator
Q
qijun 已提交
103 104
    :rtype: callable
    """
Y
Yi Wang 已提交
105 106
    return reader_creator(
        re.compile("aclImdb/train/pos/.*\.txt$"),
D
dangqingqing 已提交
107
        re.compile("aclImdb/train/neg/.*\.txt$"), word_idx)
Y
Yi Wang 已提交
108 109 110


def test(word_idx):
Q
qijun 已提交
111 112 113
    """
    IMDB test set creator.

Q
qijun 已提交
114
    It returns a reader creator, each sample in the reader is an zero-based ID
Q
qijun 已提交
115 116 117 118 119 120 121
    sequence and label in [0, 1].

    :param word_idx: word dictionary
    :type word_idx: dict
    :return: Test reader creator
    :rtype: callable
    """
Y
Yi Wang 已提交
122 123
    return reader_creator(
        re.compile("aclImdb/test/pos/.*\.txt$"),
D
dangqingqing 已提交
124
        re.compile("aclImdb/test/neg/.*\.txt$"), word_idx)
H
hedaoyuan 已提交
125 126 127


def word_dict():
Q
qijun 已提交
128
    """
Q
qijun 已提交
129
    Build a word dictionary from the corpus.
Q
qijun 已提交
130 131 132 133

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


138
def fetch():
Y
Yancey1989 已提交
139
    paddle.v2.dataset.common.download(URL, 'imdb', MD5)
R
root 已提交
140 141


Y
Your Name 已提交
142
def convert(path):
R
root 已提交
143 144 145
    """
    Converts dataset to recordio format
    """
Y
Your Name 已提交
146
    w = word_dict()
147 148
    paddle.v2.dataset.common.convert(path, lambda: train(w), 1000, "imdb_train")
    paddle.v2.dataset.common.convert(path, lambda: test(w), 1000, "imdb_test")