test_imperative_deepcf.py 9.8 KB
Newer Older
X
Xin Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2018 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.

import unittest
import numpy as np
import random
X
Xin Pan 已提交
18
import os
X
Xin Pan 已提交
19 20 21 22 23 24
import sys

import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
from test_imperative_base import new_program_scope
L
lujun 已提交
25
from paddle.fluid.dygraph.base import to_variable
X
Xin Pan 已提交
26

X
polish  
Xin Pan 已提交
27
# Can use Amusic dataset as the DeepCF describes.
X
Xin Pan 已提交
28
DATA_PATH = os.environ.get('DATA_PATH', '')
X
polish  
Xin Pan 已提交
29 30 31

BATCH_SIZE = int(os.environ.get('BATCH_SIZE', 128))
NUM_BATCHES = int(os.environ.get('NUM_BATCHES', 5))
X
Xin Pan 已提交
32
NUM_EPOCHES = int(os.environ.get('NUM_EPOCHES', 1))
X
Xin Pan 已提交
33 34


35
class DMF(fluid.Layer):
X
Xin Pan 已提交
36
    def __init__(self, name_scope):
X
Xin Pan 已提交
37
        super(DMF, self).__init__(name_scope)
38 39
        self._user_latent = fluid.FC(self.full_name(), 256)
        self._item_latent = fluid.FC(self.full_name(), 256)
X
Xin Pan 已提交
40 41 42 43 44 45 46 47

        self._user_layers = []
        self._item_layers = []
        self._hid_sizes = [128, 64]
        for i in range(len(self._hid_sizes)):
            self._user_layers.append(
                self.add_sublayer(
                    'user_layer_%d' % i,
48
                    fluid.FC(self.full_name(), self._hid_sizes[i], act='relu')))
X
Xin Pan 已提交
49 50 51
            self._item_layers.append(
                self.add_sublayer(
                    'item_layer_%d' % i,
52
                    fluid.FC(self.full_name(), self._hid_sizes[i], act='relu')))
X
Xin Pan 已提交
53 54 55 56 57 58 59 60 61 62 63

    def forward(self, users, items):
        users = self._user_latent(users)
        items = self._item_latent(items)

        for ul, il in zip(self._user_layers, self._item_layers):
            users = ul(users)
            items = il(items)
        return fluid.layers.elementwise_mul(users, items)


64
class MLP(fluid.Layer):
X
Xin Pan 已提交
65
    def __init__(self, name_scope):
X
Xin Pan 已提交
66
        super(MLP, self).__init__(name_scope)
67 68
        self._user_latent = fluid.FC(self.full_name(), 256)
        self._item_latent = fluid.FC(self.full_name(), 256)
X
Xin Pan 已提交
69 70 71 72 73 74
        self._match_layers = []
        self._hid_sizes = [128, 64]
        for i in range(len(self._hid_sizes)):
            self._match_layers.append(
                self.add_sublayer(
                    'match_layer_%d' % i,
75
                    fluid.FC(self.full_name(), self._hid_sizes[i], act='relu')))
X
Xin Pan 已提交
76 77 78 79 80 81 82 83 84 85 86 87
        self._mat

    def forward(self, users, items):
        users = self._user_latent(users)
        items = self._item_latent(items)
        match_vec = fluid.layers.concat(
            [users, items], axis=len(users.shape) - 1)
        for l in self._match_layers:
            match_vec = l(match_vec)
        return match_vec


88
class DeepCF(fluid.Layer):
X
Xin Pan 已提交
89
    def __init__(self, name_scope, num_users, num_items, matrix):
X
Xin Pan 已提交
90
        super(DeepCF, self).__init__(name_scope)
X
Xin Pan 已提交
91 92 93
        self._num_users = num_users
        self._num_items = num_items
        self._rating_matrix = self.create_parameter(
X
polish  
Xin Pan 已提交
94
            fluid.ParamAttr(trainable=False),
X
Xin Pan 已提交
95 96 97 98 99
            matrix.shape,
            matrix.dtype,
            is_bias=False,
            default_initializer=fluid.initializer.NumpyArrayInitializer(matrix))
        self._rating_matrix._stop_gradient = True
X
Xin Pan 已提交
100 101 102

        self._mlp = MLP(self.full_name())
        self._dmf = DMF(self.full_name())
103
        self._match_fc = fluid.FC(self.full_name(), 1, act='sigmoid')
X
Xin Pan 已提交
104 105

    def forward(self, users, items):
X
Xin Pan 已提交
106 107 108 109 110 111 112
        # users_emb = self._user_emb(users)
        # items_emb = self._item_emb(items)
        users_emb = fluid.layers.gather(self._rating_matrix, users)
        items_emb = fluid.layers.gather(
            fluid.layers.transpose(self._rating_matrix, [1, 0]), items)
        users_emb.stop_gradient = True
        items_emb.stop_gradient = True
X
Xin Pan 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126

        mlp_predictive = self._mlp(users_emb, items_emb)
        dmf_predictive = self._dmf(users_emb, items_emb)
        predictive = fluid.layers.concat(
            [mlp_predictive, dmf_predictive],
            axis=len(mlp_predictive.shape) - 1)
        prediction = self._match_fc(predictive)
        return prediction


def get_data():
    user_ids = []
    item_ids = []
    labels = []
X
Xin Pan 已提交
127 128
    NUM_USERS = 100
    NUM_ITEMS = 1000
X
polish  
Xin Pan 已提交
129 130
    matrix = np.zeros([NUM_USERS, NUM_ITEMS], dtype=np.float32)

X
Xin Pan 已提交
131 132
    for uid in range(NUM_USERS):
        for iid in range(NUM_ITEMS):
X
Xin Pan 已提交
133
            label = float(random.randint(1, 6) == 1)
X
Xin Pan 已提交
134 135 136
            user_ids.append(uid)
            item_ids.append(iid)
            labels.append(label)
X
Xin Pan 已提交
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            matrix[uid, iid] = label
    indices = np.arange(len(user_ids))
    np.random.shuffle(indices)
    users_np = np.array(user_ids, dtype=np.int32)[indices]
    items_np = np.array(item_ids, dtype=np.int32)[indices]
    labels_np = np.array(labels, dtype=np.float32)[indices]
    return np.expand_dims(users_np, -1), \
           np.expand_dims(items_np, -1), \
           np.expand_dims(labels_np, -1), NUM_USERS, NUM_ITEMS, matrix


def load_data(DATA_PATH):
    sys.stderr.write('loading from %s\n' % DATA_PATH)
    likes = dict()
    num_users = -1
    num_items = -1
    with open(DATA_PATH, 'r') as f:
        for l in f.readlines():
            uid, iid, rating = [int(v) for v in l.split('\t')]
            num_users = max(num_users, uid + 1)
            num_items = max(num_items, iid + 1)
            if float(rating) > 0.0:
                likes[(uid, iid)] = 1.0

    user_ids = []
    item_ids = []
    labels = []
    matrix = np.zeros([num_users, num_items], dtype=np.float32)
    for uid, iid in likes.keys():
        user_ids.append(uid)
        item_ids.append(iid)
        labels.append(1.0)
        matrix[uid, iid] = 1.0

        negative = 0
        while negative < 3:
            nuid = random.randint(0, num_users - 1)
            niid = random.randint(0, num_items - 1)
            if (nuid, niid) not in likes:
                negative += 1
                user_ids.append(nuid)
                item_ids.append(niid)
                labels.append(0.0)

    indices = np.arange(len(user_ids))
X
Xin Pan 已提交
182
    np.random.shuffle(indices)
X
Xin Pan 已提交
183 184
    users_np = np.array(user_ids, dtype=np.int32)[indices]
    items_np = np.array(item_ids, dtype=np.int32)[indices]
X
Xin Pan 已提交
185 186 187
    labels_np = np.array(labels, dtype=np.float32)[indices]
    return np.expand_dims(users_np, -1), \
           np.expand_dims(items_np, -1), \
X
Xin Pan 已提交
188
           np.expand_dims(labels_np, -1), num_users, num_items, matrix
X
Xin Pan 已提交
189 190


L
lujun 已提交
191
class TestDygraphDeepCF(unittest.TestCase):
X
Xin Pan 已提交
192
    def test_deefcf(self):
X
Xin Pan 已提交
193
        seed = 90
X
Xin Pan 已提交
194 195 196 197 198 199
        if DATA_PATH:
            (users_np, items_np, labels_np, num_users, num_items,
             matrix) = load_data(DATA_PATH)
        else:
            (users_np, items_np, labels_np, num_users, num_items,
             matrix) = get_data()
X
Xin Pan 已提交
200 201 202 203 204

        startup = fluid.Program()
        startup.random_seed = seed
        main = fluid.Program()
        main.random_seed = seed
X
polish  
Xin Pan 已提交
205

X
Xin Pan 已提交
206 207
        scope = fluid.core.Scope()
        with new_program_scope(main=main, startup=startup, scope=scope):
X
Xin Pan 已提交
208 209
            users = fluid.layers.data('users', [1], dtype='int32')
            items = fluid.layers.data('items', [1], dtype='int32')
X
Xin Pan 已提交
210 211
            labels = fluid.layers.data('labels', [1], dtype='float32')

X
Xin Pan 已提交
212
            deepcf = DeepCF('deepcf', num_users, num_items, matrix)
X
Xin Pan 已提交
213 214 215 216 217 218 219 220 221
            prediction = deepcf(users, items)
            loss = fluid.layers.reduce_sum(
                fluid.layers.log_loss(prediction, labels))
            adam = fluid.optimizer.AdamOptimizer(0.01)
            adam.minimize(loss)

            exe = fluid.Executor(fluid.CPUPlace(
            ) if not core.is_compiled_with_cuda() else fluid.CUDAPlace(0))
            exe.run(startup)
X
Xin Pan 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235
            for e in range(NUM_EPOCHES):
                sys.stderr.write('epoch %d\n' % e)
                for slice in range(0, BATCH_SIZE * NUM_BATCHES, BATCH_SIZE):
                    if slice + BATCH_SIZE >= users_np.shape[0]:
                        break
                    static_loss = exe.run(
                        main,
                        feed={
                            users.name: users_np[slice:slice + BATCH_SIZE],
                            items.name: items_np[slice:slice + BATCH_SIZE],
                            labels.name: labels_np[slice:slice + BATCH_SIZE]
                        },
                        fetch_list=[loss])[0]
                    sys.stderr.write('static loss %s\n' % static_loss)
X
Xin Pan 已提交
236

L
lujun 已提交
237
        with fluid.dygraph.guard():
X
Xin Pan 已提交
238 239 240
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed

X
Xin Pan 已提交
241
            deepcf = DeepCF('deepcf', num_users, num_items, matrix)
X
polish  
Xin Pan 已提交
242
            adam = fluid.optimizer.AdamOptimizer(0.01)
X
Xin Pan 已提交
243 244 245
            for e in range(NUM_EPOCHES):
                sys.stderr.write('epoch %d\n' % e)
                for slice in range(0, BATCH_SIZE * NUM_BATCHES, BATCH_SIZE):
X
polish  
Xin Pan 已提交
246 247
                    if slice + BATCH_SIZE >= users_np.shape[0]:
                        break
X
Xin Pan 已提交
248 249 250 251 252 253 254 255 256 257 258
                    prediction = deepcf(
                        to_variable(users_np[slice:slice + BATCH_SIZE]),
                        to_variable(items_np[slice:slice + BATCH_SIZE]))
                    loss = fluid.layers.reduce_sum(
                        fluid.layers.log_loss(prediction,
                                              to_variable(labels_np[
                                                  slice:slice + BATCH_SIZE])))
                    loss._backward()
                    adam.minimize(loss)
                    deepcf.clear_gradients()
                    dy_loss = loss._numpy()
X
polish  
Xin Pan 已提交
259
                    sys.stderr.write('dynamic loss: %s %s\n' % (slice, dy_loss))
X
Xin Pan 已提交
260 261 262 263 264 265

        self.assertEqual(static_loss, dy_loss)


if __name__ == '__main__':
    unittest.main()