sentiment.py 4.0 KB
Newer Older
W
wen-bo-yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# /usr/bin/env python
# -*- coding:utf-8 -*-

# 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.
"""
Y
Yu Yang 已提交
18
The script fetch and preprocess movie_reviews data set that provided by NLTK
W
wen-bo-yang 已提交
19

Y
Yu Yang 已提交
20
TODO(yuyang18): Complete dataset.
W
wen-bo-yang 已提交
21 22
"""

23 24
from __future__ import print_function

25
import six
W
wen-bo-yang 已提交
26
import collections
27
from itertools import chain
Y
Yu Yang 已提交
28 29

import nltk
W
wen-bo-yang 已提交
30 31
from nltk.corpus import movie_reviews

32
import paddle.dataset.common
Y
Yu Yang 已提交
33

Y
Your Name 已提交
34
__all__ = ['train', 'test', 'get_word_dict', 'convert']
W
wen-bo-yang 已提交
35 36 37 38 39 40 41 42 43 44
NUM_TRAINING_INSTANCES = 1600
NUM_TOTAL_INSTANCES = 2000


def download_data_if_not_yet():
    """
    Download the data set, if the data set is not download.
    """
    try:
        # make sure that nltk can find the data
45 46
        if paddle.dataset.common.DATA_HOME not in nltk.data.path:
            nltk.data.path.append(paddle.dataset.common.DATA_HOME)
W
wen-bo-yang 已提交
47 48
        movie_reviews.categories()
    except LookupError:
49
        print("Downloading movie_reviews data set, please wait.....")
R
root 已提交
50
        nltk.download(
51
            'movie_reviews', download_dir=paddle.dataset.common.DATA_HOME)
52
        print("Download data set success.....")
53
        print("Path is " + nltk.data.find('corpora/movie_reviews').path)
W
wen-bo-yang 已提交
54 55 56 57 58 59 60 61 62


def get_word_dict():
    """
    Sorted the words by the frequency of words which occur in sample
    :return:
        words_freq_sorted
    """
    words_freq_sorted = list()
W
wen-bo-yang 已提交
63
    word_freq_dict = collections.defaultdict(int)
W
wen-bo-yang 已提交
64
    download_data_if_not_yet()
W
wen-bo-yang 已提交
65 66 67 68 69

    for category in movie_reviews.categories():
        for field in movie_reviews.fileids(category):
            for words in movie_reviews.words(field):
                word_freq_dict[words] += 1
M
minqiyang 已提交
70
    words_sort_list = six.iteritems(word_freq_dict)
W
wen-bo-yang 已提交
71 72
    words_sort_list.sort(cmp=lambda a, b: b[1] - a[1])
    for index, word in enumerate(words_sort_list):
W
wen-bo-yang 已提交
73
        words_freq_sorted.append((word[0], index))
W
wen-bo-yang 已提交
74 75 76
    return words_freq_sorted


77 78 79 80 81 82 83 84 85
def sort_files():
    """
    Sorted the sample for cross reading the sample
    :return:
        files_list
    """
    files_list = list()
    neg_file_list = movie_reviews.fileids('neg')
    pos_file_list = movie_reviews.fileids('pos')
86 87
    files_list = list(
        chain.from_iterable(list(zip(neg_file_list, pos_file_list))))
88 89 90
    return files_list


W
wen-bo-yang 已提交
91 92 93 94 95 96
def load_sentiment_data():
    """
    Load the data set
    :return:
        data_set
    """
97
    data_set = list()
W
wen-bo-yang 已提交
98
    download_data_if_not_yet()
99 100 101 102 103 104 105
    words_ids = dict(get_word_dict())
    for sample_file in sort_files():
        words_list = list()
        category = 0 if 'neg' in sample_file else 1
        for word in movie_reviews.words(sample_file):
            words_list.append(words_ids[word.lower()])
        data_set.append((words_list, category))
W
wen-bo-yang 已提交
106 107 108 109 110
    return data_set


def reader_creator(data):
    """
W
wen-bo-yang 已提交
111
    Reader creator, generate an iterator for data set
W
wen-bo-yang 已提交
112 113 114 115
    :param data:
        train data set or test data set
    """
    for each in data:
W
wen-bo-yang 已提交
116
        yield each[0], each[1]
W
wen-bo-yang 已提交
117 118 119 120


def train():
    """
Q
qijun 已提交
121
    Default training set reader creator
W
wen-bo-yang 已提交
122
    """
W
wen-bo-yang 已提交
123
    data_set = load_sentiment_data()
W
wen-bo-yang 已提交
124 125 126 127 128 129 130
    return reader_creator(data_set[0:NUM_TRAINING_INSTANCES])


def test():
    """
    Default test set reader creator
    """
W
wen-bo-yang 已提交
131
    data_set = load_sentiment_data()
W
wen-bo-yang 已提交
132
    return reader_creator(data_set[NUM_TRAINING_INSTANCES:])
Y
Yancey1989 已提交
133 134


135
def fetch():
136
    nltk.download('movie_reviews', download_dir=paddle.dataset.common.DATA_HOME)
R
root 已提交
137 138 139 140 141 142


def convert(path):
    """
    Converts dataset to recordio format
    """
143 144
    paddle.dataset.common.convert(path, train, 1000, "sentiment_train")
    paddle.dataset.common.convert(path, test, 1000, "sentiment_test")