test_recommender_system.py 11.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
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.

15 16
import math
import sys
Q
Qiao Longfei 已提交
17
import numpy as np
18
import paddle.v2 as paddle
19
import paddle.v2.fluid as fluid
20
import paddle.v2.fluid.framework as framework
Q
Qiao Longfei 已提交
21 22
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.nets as nets
Q
Qiao Longfei 已提交
23
from paddle.v2.fluid.executor import Executor
Q
Qiao Longfei 已提交
24
from paddle.v2.fluid.optimizer import SGDOptimizer
25

26 27
IS_SPARSE = True
USE_GPU = False
28 29 30 31 32 33 34 35 36
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 已提交
37
    uid = layers.data(name='user_id', shape=[1], dtype='int64')
38 39 40

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

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

    USR_GENDER_DICT_SIZE = 2

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

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

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

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

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

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

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

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

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

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

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

    return usr_combined_features


def get_mov_combined_features():

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

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

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

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

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

107 108
    category_id = layers.data(
        name='category_id', shape=[1], dtype='int64', lod_level=1)
109 110

    mov_categories_emb = layers.embedding(
Q
Qiao Longfei 已提交
111
        input=category_id, size=[CATEGORY_DICT_SIZE, 32], is_sparse=IS_SPARSE)
112 113

    mov_categories_hidden = layers.sequence_pool(
Q
Qiao Longfei 已提交
114
        input=mov_categories_emb, pool_type="sum")
115 116 117

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

118 119
    mov_title_id = layers.data(
        name='movie_title', shape=[1], dtype='int64', lod_level=1)
120 121

    mov_title_emb = layers.embedding(
Q
Qiao Longfei 已提交
122
        input=mov_title_id, size=[MOV_TITLE_DICT_SIZE, 32], is_sparse=IS_SPARSE)
123 124 125 126 127 128

    mov_title_conv = nets.sequence_conv_pool(
        input=mov_title_emb,
        num_filters=32,
        filter_size=3,
        act="tanh",
129
        pool_type="sum")
130 131

    concat_embed = layers.concat(
Q
Qiao Longfei 已提交
132
        input=[mov_fc, mov_categories_hidden, mov_title_conv], axis=1)
133 134

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

    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 已提交
145
    inference = layers.cos_sim(X=usr_combined_features, Y=mov_combined_features)
T
typhoonzero 已提交
146
    scale_infer = layers.scale(x=inference, scale=5.0)
147

F
fengjiayi 已提交
148
    label = layers.data(name='score', shape=[1], dtype='float32')
T
typhoonzero 已提交
149
    square_cost = layers.square_error_cost(input=scale_infer, label=label)
150
    avg_cost = layers.mean(x=square_cost)
151

152 153
    return scale_infer, avg_cost

154

155 156 157 158 159
def train(use_cuda, save_dirname):
    scale_infer, avg_cost = model()

    # test program
    test_program = fluid.default_main_program().clone()
160

Q
Qiao Longfei 已提交
161
    sgd_optimizer = SGDOptimizer(learning_rate=0.2)
162
    opts = sgd_optimizer.minimize(avg_cost)
163

164
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
165 166

    exe = Executor(place)
167
    exe.run(framework.default_startup_program())
168 169 170 171 172

    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.movielens.train(), buf_size=8192),
        batch_size=BATCH_SIZE)
173 174
    test_reader = paddle.batch(
        paddle.dataset.movielens.test(), batch_size=BATCH_SIZE)
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

    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():
190
            tensor = fluid.LoDTensor()
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            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):
217 218 219
        for batch_id, data in enumerate(train_reader()):
            # train a mini-batch
            outs = exe.run(program=fluid.default_main_program(),
220
                           feed=func_feed(feeding, data),
221
                           fetch_list=[avg_cost])
222
            out = np.array(outs[0])
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
            if (batch_id + 1) % 10 == 0:
                avg_cost_set = []
                for test_data in test_reader():
                    avg_cost_np = exe.run(program=test_program,
                                          feed=func_feed(feeding, test_data),
                                          fetch_list=[avg_cost])
                    avg_cost_set.append(avg_cost_np[0])
                    break  # test only 1 segment for speeding up CI

                # get test avg_cost
                test_avg_cost = np.array(avg_cost_set).mean()
                if test_avg_cost < 6.0:
                    # if avg_cost less than 6.0, we think our code is good.
                    if save_dirname is not None:
                        fluid.io.save_inference_model(save_dirname, [
                            "user_id", "gender_id", "age_id", "job_id",
                            "movie_id", "category_id", "movie_title"
                        ], [scale_infer], exe)
                    return

243 244
            if math.isnan(float(out[0])):
                sys.exit("got NaN loss, training failed.")
245 246


247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

    # Use fluid.io.load_inference_model to obtain the inference program desc,
    # the feed_target_names (the names of variables that will be feeded
    # data using feed operators), and the fetch_targets (variables that
    # we want to obtain data from using fetch operators).
    [inference_program, feed_target_names,
     fetch_targets] = fluid.io.load_inference_model(save_dirname, exe)

    def create_lod_tensor(data, lod=None):
        tensor = fluid.LoDTensor()
        if lod is None:
            # Tensor, the shape is [batch_size, 1]
            index = 0
            lod_0 = [index]
            for l in range(len(data)):
                index += 1
                lod_0.append(index)
            lod = [lod_0]
        tensor.set_lod(lod)

        flattened_data = np.concatenate(data, axis=0).astype("int64")
        flattened_data = flattened_data.reshape([len(flattened_data), 1])
        tensor.set(flattened_data, place)
        return tensor

    # Use the first data from paddle.dataset.movielens.test() as input
    assert feed_target_names[0] == "user_id"
    user_id = create_lod_tensor([[1]])

    assert feed_target_names[1] == "gender_id"
    gender_id = create_lod_tensor([[1]])

    assert feed_target_names[2] == "age_id"
    age_id = create_lod_tensor([[0]])

    assert feed_target_names[3] == "job_id"
    job_id = create_lod_tensor([[10]])

    assert feed_target_names[4] == "movie_id"
    movie_id = create_lod_tensor([[783]])

    assert feed_target_names[5] == "category_id"
    category_id = create_lod_tensor([[10], [8], [9]], [[0, 3]])

    assert feed_target_names[6] == "movie_title"
    movie_title = create_lod_tensor([[1069], [4140], [2923], [710], [988]],
                                    [[0, 5]])

    # Construct feed as a dictionary of {feed_target_name: feed_target_data}
    # and results will contain a list of data corresponding to fetch_targets.
    results = exe.run(inference_program,
                      feed={
                          feed_target_names[0]: user_id,
                          feed_target_names[1]: gender_id,
                          feed_target_names[2]: age_id,
                          feed_target_names[3]: job_id,
                          feed_target_names[4]: movie_id,
                          feed_target_names[5]: category_id,
                          feed_target_names[6]: movie_title
                      },
                      fetch_list=fetch_targets,
                      return_numpy=False)
    print("inferred score: ", np.array(results[0]))


def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the inference model
    save_dirname = "recommender_system.inference.model"

    train(use_cuda, save_dirname)
    infer(use_cuda, save_dirname)


if __name__ == '__main__':
    main(USE_GPU)