test_recommender_system.py 6.8 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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
Qiao Longfei 已提交
15
import numpy as np
16
import paddle.v2 as paddle
Q
Qiao Longfei 已提交
17
import paddle.v2.fluid.core as core
18
import paddle.v2.fluid.framework as framework
Q
Qiao Longfei 已提交
19 20
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.nets as nets
Q
Qiao Longfei 已提交
21
from paddle.v2.fluid.executor import Executor
Q
Qiao Longfei 已提交
22
from paddle.v2.fluid.optimizer import SGDOptimizer
23

24 25
IS_SPARSE = True
USE_GPU = False
26 27 28 29 30 31 32 33 34
BATCH_SIZE = 256


def get_usr_combined_features():
    # FIXME(dzh) : old API integer_value(10) may has range check.
    # currently we don't have user configurated check.

    USR_DICT_SIZE = paddle.dataset.movielens.max_user_id() + 1

F
fengjiayi 已提交
35
    uid = layers.data(name='user_id', shape=[1], dtype='int64')
36 37 38

    usr_emb = layers.embedding(
        input=uid,
F
fengjiayi 已提交
39
        dtype='float32',
40
        size=[USR_DICT_SIZE, 32],
Y
Yu Yang 已提交
41
        param_attr='user_table',
42
        is_sparse=IS_SPARSE)
43

Q
Qiao Longfei 已提交
44
    usr_fc = layers.fc(input=usr_emb, size=32)
45 46 47

    USR_GENDER_DICT_SIZE = 2

F
fengjiayi 已提交
48
    usr_gender_id = layers.data(name='gender_id', shape=[1], dtype='int64')
49 50 51 52

    usr_gender_emb = layers.embedding(
        input=usr_gender_id,
        size=[USR_GENDER_DICT_SIZE, 16],
Y
Yu Yang 已提交
53
        param_attr='gender_table',
54
        is_sparse=IS_SPARSE)
55

Q
Qiao Longfei 已提交
56
    usr_gender_fc = layers.fc(input=usr_gender_emb, size=16)
57 58

    USR_AGE_DICT_SIZE = len(paddle.dataset.movielens.age_table)
F
fengjiayi 已提交
59
    usr_age_id = layers.data(name='age_id', shape=[1], dtype="int64")
60 61 62 63

    usr_age_emb = layers.embedding(
        input=usr_age_id,
        size=[USR_AGE_DICT_SIZE, 16],
64
        is_sparse=IS_SPARSE,
Y
Yu Yang 已提交
65
        param_attr='age_table')
66

Q
Qiao Longfei 已提交
67
    usr_age_fc = layers.fc(input=usr_age_emb, size=16)
68 69

    USR_JOB_DICT_SIZE = paddle.dataset.movielens.max_job_id() + 1
F
fengjiayi 已提交
70
    usr_job_id = layers.data(name='job_id', shape=[1], dtype="int64")
71 72 73 74

    usr_job_emb = layers.embedding(
        input=usr_job_id,
        size=[USR_JOB_DICT_SIZE, 16],
Y
Yu Yang 已提交
75
        param_attr='job_table',
76
        is_sparse=IS_SPARSE)
77

Q
Qiao Longfei 已提交
78
    usr_job_fc = layers.fc(input=usr_job_emb, size=16)
79 80

    concat_embed = layers.concat(
Q
Qiao Longfei 已提交
81
        input=[usr_fc, usr_gender_fc, usr_age_fc, usr_job_fc], axis=1)
82

Q
Qiao Longfei 已提交
83
    usr_combined_features = layers.fc(input=concat_embed, size=200, act="tanh")
84 85 86 87 88 89 90 91

    return usr_combined_features


def get_mov_combined_features():

    MOV_DICT_SIZE = paddle.dataset.movielens.max_movie_id() + 1

F
fengjiayi 已提交
92
    mov_id = layers.data(name='movie_id', shape=[1], dtype='int64')
93 94 95

    mov_emb = layers.embedding(
        input=mov_id,
F
fengjiayi 已提交
96
        dtype='float32',
97
        size=[MOV_DICT_SIZE, 32],
Y
Yu Yang 已提交
98
        param_attr='movie_table',
99
        is_sparse=IS_SPARSE)
100

Q
Qiao Longfei 已提交
101
    mov_fc = layers.fc(input=mov_emb, size=32)
102 103 104

    CATEGORY_DICT_SIZE = len(paddle.dataset.movielens.movie_categories())

F
fengjiayi 已提交
105
    category_id = layers.data(name='category_id', shape=[1], dtype='int64')
106 107

    mov_categories_emb = layers.embedding(
Q
Qiao Longfei 已提交
108
        input=category_id, size=[CATEGORY_DICT_SIZE, 32], is_sparse=IS_SPARSE)
109 110

    mov_categories_hidden = layers.sequence_pool(
Q
Qiao Longfei 已提交
111
        input=mov_categories_emb, pool_type="sum")
112 113 114

    MOV_TITLE_DICT_SIZE = len(paddle.dataset.movielens.get_movie_title_dict())

F
fengjiayi 已提交
115
    mov_title_id = layers.data(name='movie_title', shape=[1], dtype='int64')
116 117

    mov_title_emb = layers.embedding(
Q
Qiao Longfei 已提交
118
        input=mov_title_id, size=[MOV_TITLE_DICT_SIZE, 32], is_sparse=IS_SPARSE)
119 120 121 122 123 124

    mov_title_conv = nets.sequence_conv_pool(
        input=mov_title_emb,
        num_filters=32,
        filter_size=3,
        act="tanh",
125
        pool_type="sum")
126 127

    concat_embed = layers.concat(
Q
Qiao Longfei 已提交
128
        input=[mov_fc, mov_categories_hidden, mov_title_conv], axis=1)
129 130

    # FIXME(dzh) : need tanh operator
Q
Qiao Longfei 已提交
131
    mov_combined_features = layers.fc(input=concat_embed, size=200, act="tanh")
132 133 134 135 136 137 138 139 140

    return mov_combined_features


def model():
    usr_combined_features = get_usr_combined_features()
    mov_combined_features = get_mov_combined_features()

    # need cos sim
Q
Qiao Longfei 已提交
141
    inference = layers.cos_sim(X=usr_combined_features, Y=mov_combined_features)
T
typhoonzero 已提交
142
    scale_infer = layers.scale(x=inference, scale=5.0)
143

F
fengjiayi 已提交
144
    label = layers.data(name='score', shape=[1], dtype='float32')
145

T
typhoonzero 已提交
146
    square_cost = layers.square_error_cost(input=scale_infer, label=label)
147

148
    avg_cost = layers.mean(x=square_cost)
149 150 151 152 153 154

    return avg_cost


def main():
    cost = model()
Q
Qiao Longfei 已提交
155
    sgd_optimizer = SGDOptimizer(learning_rate=0.2)
156
    opts = sgd_optimizer.minimize(cost)
157

158
    if USE_GPU:
D
dzhwinter 已提交
159
        place = core.CUDAPlace(0)
160 161 162 163
    else:
        place = core.CPUPlace()

    exe = Executor(place)
164
    exe.run(framework.default_startup_program())
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.movielens.train(), buf_size=8192),
        batch_size=BATCH_SIZE)

    feeding = {
        'user_id': 0,
        'gender_id': 1,
        'age_id': 2,
        'job_id': 3,
        'movie_id': 4,
        'category_id': 5,
        'movie_title': 6,
        'score': 7
    }

    def func_feed(feeding, data):
        feed_tensors = {}
        for (key, idx) in feeding.iteritems():
            tensor = core.LoDTensor()
            if key != "category_id" and key != "movie_title":
                if key == "score":
                    numpy_data = np.array(map(lambda x: x[idx], data)).astype(
                        "float32")
                else:
                    numpy_data = np.array(map(lambda x: x[idx], data)).astype(
                        "int64")
            else:
                numpy_data = map(lambda x: np.array(x[idx]).astype("int64"),
                                 data)
                lod_info = [len(item) for item in numpy_data]
                offset = 0
                lod = [offset]
                for item in lod_info:
                    offset += item
                    lod.append(offset)
                numpy_data = np.concatenate(numpy_data, axis=0)
                tensor.set_lod([lod])

            numpy_data = numpy_data.reshape([numpy_data.shape[0], 1])
            tensor.set(numpy_data, place)
            feed_tensors[key] = tensor
        return feed_tensors

    PASS_NUM = 100
    for pass_id in range(PASS_NUM):
        for data in train_reader():
213
            outs = exe.run(framework.default_main_program(),
214 215 216
                           feed=func_feed(feeding, data),
                           fetch_list=[cost])
            out = np.array(outs[0])
217 218
            if out[0] < 6.0:
                # if avg cost less than 6.0, we think our code is good.
219 220 221 222
                exit(0)


main()