movielens.py 6.9 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.
Y
Yu Yang 已提交
14 15 16
"""
Movielens 1-M dataset.

Q
qijun 已提交
17 18 19 20
Movielens 1-M dataset contains 1 million ratings from 6000 users on 4000 movies, which was 
collected by GroupLens Research. This module will download Movielens 1-M dataset from 
http://files.grouplens.org/datasets/movielens/ml-1m.zip and parse train/test set 
into paddle reader creators.
Q
qijun 已提交
21

Y
Yu Yang 已提交
22
"""
D
dangqingqing 已提交
23

Y
Yu Yang 已提交
24
import zipfile
王益 已提交
25
from common import download
Y
Yu Yang 已提交
26 27 28 29
import re
import random
import functools

Y
Refine  
Yu Yang 已提交
30 31
__all__ = [
    'train', 'test', 'get_movie_title_dict', 'max_movie_id', 'max_user_id',
Y
Yu Yang 已提交
32
    'age_table', 'movie_categories', 'max_job_id', 'user_info', 'movie_info'
Y
Refine  
Yu Yang 已提交
33 34 35
]

age_table = [1, 18, 25, 35, 45, 50, 56]
Y
Yu Yang 已提交
36

Y
Yancey1989 已提交
37 38 39
URL = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip'
MD5 = 'c4d9eecfca2ab87c1945afe126590906'

Y
Yu Yang 已提交
40 41

class MovieInfo(object):
Q
qijun 已提交
42 43 44
    """
    Movie id, title and categories information are stored in MovieInfo.
    """
Y
Yu Yang 已提交
45 46 47 48 49 50
    def __init__(self, index, categories, title):
        self.index = int(index)
        self.categories = categories
        self.title = title

    def value(self):
Q
qijun 已提交
51 52 53
        """
        Get information of a movie.
        """
Y
Yu Yang 已提交
54 55 56 57 58
        return [
            self.index, [CATEGORIES_DICT[c] for c in self.categories],
            [MOVIE_TITLE_DICT[w.lower()] for w in self.title.split()]
        ]

Y
Yu Yang 已提交
59 60 61 62 63 64 65
    def __str__(self):
        return "<MovieInfo id(%d), title(%s), categories(%s)>" % (
            self.index, self.title, self.categories)

    def __repr__(self):
        return self.__str__()

Y
Yu Yang 已提交
66 67

class UserInfo(object):
Q
qijun 已提交
68 69 70
    """
    User id, gender, age, and job information are stored in UserInfo.
    """
Y
Yu Yang 已提交
71 72 73
    def __init__(self, index, gender, age, job_id):
        self.index = int(index)
        self.is_male = gender == 'M'
Y
Refine  
Yu Yang 已提交
74
        self.age = age_table.index(int(age))
Y
Yu Yang 已提交
75 76 77
        self.job_id = int(job_id)

    def value(self):
Q
qijun 已提交
78 79 80
        """
        Get information of a user.
        """
Y
Yu Yang 已提交
81 82
        return [self.index, 0 if self.is_male else 1, self.age, self.job_id]

Y
Yu Yang 已提交
83 84 85 86 87 88 89 90
    def __str__(self):
        return "<UserInfo id(%d), gender(%s), age(%d), job(%d)>" % (
            self.index, "M"
            if self.is_male else "F", age_table[self.age], self.job_id)

    def __repr__(self):
        return str(self)

Y
Yu Yang 已提交
91 92 93 94 95 96 97 98

MOVIE_INFO = None
MOVIE_TITLE_DICT = None
CATEGORIES_DICT = None
USER_INFO = None


def __initialize_meta_info__():
Y
Yancey1989 已提交
99
    fn = download(URL, "movielens", MD5)
Y
Yu Yang 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    global MOVIE_INFO
    if MOVIE_INFO is None:
        pattern = re.compile(r'^(.*)\((\d+)\)$')
        with zipfile.ZipFile(file=fn) as package:
            for info in package.infolist():
                assert isinstance(info, zipfile.ZipInfo)
                MOVIE_INFO = dict()
                title_word_set = set()
                categories_set = set()
                with package.open('ml-1m/movies.dat') as movie_file:
                    for i, line in enumerate(movie_file):
                        movie_id, title, categories = line.strip().split('::')
                        categories = categories.split('|')
                        for c in categories:
                            categories_set.add(c)
                        title = pattern.match(title).group(1)
                        MOVIE_INFO[int(movie_id)] = MovieInfo(
                            index=movie_id, categories=categories, title=title)
                        for w in title.split():
                            title_word_set.add(w.lower())

                global MOVIE_TITLE_DICT
                MOVIE_TITLE_DICT = dict()
                for i, w in enumerate(title_word_set):
                    MOVIE_TITLE_DICT[w] = i

                global CATEGORIES_DICT
                CATEGORIES_DICT = dict()
                for i, c in enumerate(categories_set):
                    CATEGORIES_DICT[c] = i

                global USER_INFO
                USER_INFO = dict()
                with package.open('ml-1m/users.dat') as user_file:
                    for line in user_file:
                        uid, gender, age, job, _ = line.strip().split("::")
                        USER_INFO[int(uid)] = UserInfo(
                            index=uid, gender=gender, age=age, job_id=job)
    return fn


def __reader__(rand_seed=0, test_ratio=0.1, is_test=False):
    fn = __initialize_meta_info__()
    rand = random.Random(x=rand_seed)
    with zipfile.ZipFile(file=fn) as package:
        with package.open('ml-1m/ratings.dat') as rating:
            for line in rating:
                if (rand.random() < test_ratio) == is_test:
                    uid, mov_id, rating, _ = line.strip().split("::")
                    uid = int(uid)
                    mov_id = int(mov_id)
                    rating = float(rating) * 2 - 5.0

                    mov = MOVIE_INFO[mov_id]
                    usr = USER_INFO[uid]
                    yield usr.value() + mov.value() + [[rating]]


def __reader_creator__(**kwargs):
    return lambda: __reader__(**kwargs)


Y
Refine  
Yu Yang 已提交
162 163
train = functools.partial(__reader_creator__, is_test=False)
test = functools.partial(__reader_creator__, is_test=True)
Y
Yu Yang 已提交
164 165


Y
Yu Yang 已提交
166
def get_movie_title_dict():
Q
qijun 已提交
167 168 169
    """
    Get movie title dictionary.
    """
Y
Yu Yang 已提交
170 171 172 173
    __initialize_meta_info__()
    return MOVIE_TITLE_DICT


Y
Refine  
Yu Yang 已提交
174 175 176 177 178 179 180 181
def __max_index_info__(a, b):
    if a.index > b.index:
        return a
    else:
        return b


def max_movie_id():
Q
qijun 已提交
182 183 184
    """
    Get the maximum value of movie id.
    """
Y
Refine  
Yu Yang 已提交
185 186 187 188 189
    __initialize_meta_info__()
    return reduce(__max_index_info__, MOVIE_INFO.viewvalues()).index


def max_user_id():
Q
qijun 已提交
190 191 192
    """
    Get the maximum value of user id.
    """
Y
Refine  
Yu Yang 已提交
193 194 195 196
    __initialize_meta_info__()
    return reduce(__max_index_info__, USER_INFO.viewvalues()).index


Y
Yu Yang 已提交
197 198 199 200 201 202 203 204
def __max_job_id_impl__(a, b):
    if a.job_id > b.job_id:
        return a
    else:
        return b


def max_job_id():
Q
qijun 已提交
205 206 207
    """
    Get the maximum value of job id.
    """
Y
Yu Yang 已提交
208 209 210 211 212
    __initialize_meta_info__()
    return reduce(__max_job_id_impl__, USER_INFO.viewvalues()).job_id


def movie_categories():
Q
qijun 已提交
213 214 215
    """
    Get movie categoriges dictionary.
    """
Y
Yu Yang 已提交
216 217 218 219
    __initialize_meta_info__()
    return CATEGORIES_DICT


Y
Yu Yang 已提交
220
def user_info():
Q
qijun 已提交
221 222 223
    """
    Get user info dictionary.
    """
Y
Yu Yang 已提交
224 225 226 227 228
    __initialize_meta_info__()
    return USER_INFO


def movie_info():
Q
qijun 已提交
229 230 231
    """
    Get movie info dictionary.
    """
Y
Yu Yang 已提交
232 233 234 235
    __initialize_meta_info__()
    return MOVIE_INFO


Y
Yu Yang 已提交
236
def unittest():
Y
Refine  
Yu Yang 已提交
237
    for train_count, _ in enumerate(train()()):
Y
Yu Yang 已提交
238
        pass
Y
Refine  
Yu Yang 已提交
239
    for test_count, _ in enumerate(test()()):
Y
Yu Yang 已提交
240 241 242 243 244
        pass

    print train_count, test_count


245 246
def fetch():
    download(URL, "movielens", MD5)
Y
Yancey1989 已提交
247 248


Y
Yu Yang 已提交
249 250
if __name__ == '__main__':
    unittest()