movielens.py 8.8 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
Movielens 1-M dataset contains 1 million ratings from 6000 users on 4000
movies, which was collected by GroupLens Research. This module will download
19
Movielens 1-M dataset from
Q
qijun 已提交
20 21
http://files.grouplens.org/datasets/movielens/ml-1m.zip and parse training
set and test set into paddle reader creators.
Q
qijun 已提交
22

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

25 26
from __future__ import print_function

27
import numpy as np
Y
Yu Yang 已提交
28
import zipfile
29
import paddle.dataset.common
30
import paddle.utils.deprecated as deprecated
Y
Yu Yang 已提交
31 32 33
import re
import random
import functools
M
minqiyang 已提交
34
import six
M
minqiyang 已提交
35
import paddle.compat as cpt
Y
Yu Yang 已提交
36

37 38
__all__ = []

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

41 42
#URL = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip'
URL = 'https://dataset.bj.bcebos.com/movielens%2Fml-1m.zip'
Y
Yancey1989 已提交
43 44
MD5 = 'c4d9eecfca2ab87c1945afe126590906'

Y
Yu Yang 已提交
45 46

class MovieInfo(object):
Q
qijun 已提交
47 48 49
    """
    Movie id, title and categories information are stored in MovieInfo.
    """
Q
qijun 已提交
50

Y
Yu Yang 已提交
51 52 53 54 55 56
    def __init__(self, index, categories, title):
        self.index = int(index)
        self.categories = categories
        self.title = title

    def value(self):
Q
qijun 已提交
57
        """
Q
qijun 已提交
58
        Get information from a movie.
Q
qijun 已提交
59
        """
Y
Yu Yang 已提交
60 61 62 63 64
        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 已提交
65 66 67 68 69 70 71
    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 已提交
72 73

class UserInfo(object):
Q
qijun 已提交
74 75 76
    """
    User id, gender, age, and job information are stored in UserInfo.
    """
Q
qijun 已提交
77

Y
Yu Yang 已提交
78 79 80
    def __init__(self, index, gender, age, job_id):
        self.index = int(index)
        self.is_male = gender == 'M'
Y
Refine  
Yu Yang 已提交
81
        self.age = age_table.index(int(age))
Y
Yu Yang 已提交
82 83 84
        self.job_id = int(job_id)

    def value(self):
Q
qijun 已提交
85
        """
Q
qijun 已提交
86
        Get information from a user.
Q
qijun 已提交
87
        """
Y
Yu Yang 已提交
88 89
        return [self.index, 0 if self.is_male else 1, self.age, self.job_id]

Y
Yu Yang 已提交
90 91 92 93 94 95 96 97
    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 已提交
98 99 100 101 102 103 104 105

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


def __initialize_meta_info__():
106
    fn = paddle.dataset.common.download(URL, "movielens", MD5)
Y
Yu Yang 已提交
107 108 109 110 111 112 113 114 115 116 117
    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):
M
minqiyang 已提交
118
                        line = cpt.to_text(line, encoding='latin')
Y
Yu Yang 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
                        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:
M
minqiyang 已提交
143
                        line = cpt.to_text(line, encoding='latin')
Y
Yu Yang 已提交
144 145 146 147 148 149 150 151
                        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__()
152
    np.random.seed(rand_seed)
Y
Yu Yang 已提交
153 154 155
    with zipfile.ZipFile(file=fn) as package:
        with package.open('ml-1m/ratings.dat') as rating:
            for line in rating:
M
minqiyang 已提交
156
                line = cpt.to_text(line, encoding='latin')
157
                if (np.random.random() < test_ratio) == is_test:
Y
Yu Yang 已提交
158 159 160 161 162 163 164 165 166 167
                    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]]


168 169 170
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
171
    level=1,
172
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
173 174 175 176
def __reader_creator__(**kwargs):
    return lambda: __reader__(**kwargs)


Y
Refine  
Yu Yang 已提交
177 178
train = functools.partial(__reader_creator__, is_test=False)
test = functools.partial(__reader_creator__, is_test=True)
Y
Yu Yang 已提交
179 180


181 182 183
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
184
    level=1,
185
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
186
def get_movie_title_dict():
Q
qijun 已提交
187 188 189
    """
    Get movie title dictionary.
    """
Y
Yu Yang 已提交
190 191 192 193
    __initialize_meta_info__()
    return MOVIE_TITLE_DICT


Y
Refine  
Yu Yang 已提交
194 195 196 197 198 199 200
def __max_index_info__(a, b):
    if a.index > b.index:
        return a
    else:
        return b


201 202 203
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
204
    level=1,
205
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Refine  
Yu Yang 已提交
206
def max_movie_id():
Q
qijun 已提交
207 208 209
    """
    Get the maximum value of movie id.
    """
Y
Refine  
Yu Yang 已提交
210
    __initialize_meta_info__()
M
minqiyang 已提交
211
    return six.moves.reduce(__max_index_info__, list(MOVIE_INFO.values())).index
Y
Refine  
Yu Yang 已提交
212 213


214 215 216
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
217
    level=1,
218
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Refine  
Yu Yang 已提交
219
def max_user_id():
Q
qijun 已提交
220 221 222
    """
    Get the maximum value of user id.
    """
Y
Refine  
Yu Yang 已提交
223
    __initialize_meta_info__()
M
minqiyang 已提交
224
    return six.moves.reduce(__max_index_info__, list(USER_INFO.values())).index
Y
Refine  
Yu Yang 已提交
225 226


Y
Yu Yang 已提交
227 228 229 230 231 232 233
def __max_job_id_impl__(a, b):
    if a.job_id > b.job_id:
        return a
    else:
        return b


234 235 236
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
237
    level=1,
238
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
239
def max_job_id():
Q
qijun 已提交
240 241 242
    """
    Get the maximum value of job id.
    """
Y
Yu Yang 已提交
243
    __initialize_meta_info__()
M
minqiyang 已提交
244 245
    return six.moves.reduce(__max_job_id_impl__,
                            list(USER_INFO.values())).job_id
Y
Yu Yang 已提交
246 247


248 249 250
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
251
    level=1,
252
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
253
def movie_categories():
Q
qijun 已提交
254
    """
T
tianshuo78520a 已提交
255
    Get movie categories dictionary.
Q
qijun 已提交
256
    """
Y
Yu Yang 已提交
257 258 259 260
    __initialize_meta_info__()
    return CATEGORIES_DICT


261 262 263
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
264
    level=1,
265
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
266
def user_info():
Q
qijun 已提交
267 268 269
    """
    Get user info dictionary.
    """
Y
Yu Yang 已提交
270 271 272 273
    __initialize_meta_info__()
    return USER_INFO


274 275 276
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
277
    level=1,
278
    reason="Please use new dataset API which supports paddle.io.DataLoader")
Y
Yu Yang 已提交
279
def movie_info():
Q
qijun 已提交
280 281 282
    """
    Get movie info dictionary.
    """
Y
Yu Yang 已提交
283 284 285 286
    __initialize_meta_info__()
    return MOVIE_INFO


Y
Yu Yang 已提交
287
def unittest():
Y
Refine  
Yu Yang 已提交
288
    for train_count, _ in enumerate(train()()):
Y
Yu Yang 已提交
289
        pass
Y
Refine  
Yu Yang 已提交
290
    for test_count, _ in enumerate(test()()):
Y
Yu Yang 已提交
291 292
        pass

293
    print(train_count, test_count)
Y
Yu Yang 已提交
294 295


296 297 298
@deprecated(
    since="2.0.0",
    update_to="paddle.text.datasets.Movielens",
299
    level=1,
300
    reason="Please use new dataset API which supports paddle.io.DataLoader")
301
def fetch():
302
    paddle.dataset.common.download(URL, "movielens", MD5)
R
root 已提交
303 304


Y
Yu Yang 已提交
305 306
if __name__ == '__main__':
    unittest()