model.py 8.2 KB
Newer Older
T
tangwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 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
add din  
yaoxuefeng 已提交
15 16
import paddle.fluid as fluid

17 18
from paddlerec.core.utils import envs
from paddlerec.core.model import Model as ModelBase
Y
add din  
yaoxuefeng 已提交
19 20 21 22 23


class Model(ModelBase):
    def __init__(self, config):
        ModelBase.__init__(self, config)
T
tangwei 已提交
24

Y
add din  
yaoxuefeng 已提交
25 26 27 28 29 30
    def config_read(self, config_path):
        with open(config_path, "r") as fin:
            user_count = int(fin.readline().strip())
            item_count = int(fin.readline().strip())
            cat_count = int(fin.readline().strip())
        return user_count, item_count, cat_count
T
tangwei 已提交
31

Y
add din  
yaoxuefeng 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    def din_attention(self, hist, target_expand, mask):
        """activation weight"""

        hidden_size = hist.shape[-1]

        concat = fluid.layers.concat(
            [hist, target_expand, hist - target_expand, hist * target_expand],
            axis=2)
        atten_fc1 = fluid.layers.fc(name="atten_fc1",
                                    input=concat,
                                    size=80,
                                    act=self.act,
                                    num_flatten_dims=2)
        atten_fc2 = fluid.layers.fc(name="atten_fc2",
                                    input=atten_fc1,
                                    size=40,
                                    act=self.act,
                                    num_flatten_dims=2)
        atten_fc3 = fluid.layers.fc(name="atten_fc3",
                                    input=atten_fc2,
                                    size=1,
                                    num_flatten_dims=2)
        atten_fc3 += mask
        atten_fc3 = fluid.layers.transpose(x=atten_fc3, perm=[0, 2, 1])
        atten_fc3 = fluid.layers.scale(x=atten_fc3, scale=hidden_size**-0.5)
        weight = fluid.layers.softmax(atten_fc3)
        out = fluid.layers.matmul(weight, hist)
        out = fluid.layers.reshape(x=out, shape=[0, hidden_size])
        return out
T
tangwei 已提交
61

Y
add din  
yaoxuefeng 已提交
62 63
    def train_net(self):
        seq_len = -1
T
tangwei 已提交
64 65 66 67 68 69
        self.item_emb_size = envs.get_global_env(
            "hyper_parameters.item_emb_size", 64, self._namespace)
        self.cat_emb_size = envs.get_global_env(
            "hyper_parameters.cat_emb_size", 64, self._namespace)
        self.act = envs.get_global_env("hyper_parameters.act", "sigmoid",
                                       self._namespace)
Y
add din  
yaoxuefeng 已提交
70 71
        #item_emb_size = 64
        #cat_emb_size = 64
T
tangwei 已提交
72 73
        self.is_sparse = envs.get_global_env("hyper_parameters.is_sparse",
                                             False, self._namespace)
Y
add din  
yaoxuefeng 已提交
74
        #significant for speeding up the training process
T
tangwei 已提交
75 76 77 78
        self.config_path = envs.get_global_env(
            "hyper_parameters.config_path", "data/config.txt", self._namespace)
        self.use_DataLoader = envs.get_global_env(
            "hyper_parameters.use_DataLoader", False, self._namespace)
Y
add din  
yaoxuefeng 已提交
79 80 81 82 83 84 85 86
        user_count, item_count, cat_count = self.config_read(self.config_path)

        item_emb_attr = fluid.ParamAttr(name="item_emb")
        cat_emb_attr = fluid.ParamAttr(name="cat_emb")

        hist_item_seq = fluid.data(
            name="hist_item_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(hist_item_seq)
T
tangwei 已提交
87

Y
add din  
yaoxuefeng 已提交
88 89 90
        hist_cat_seq = fluid.data(
            name="hist_cat_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(hist_cat_seq)
T
tangwei 已提交
91 92 93

        target_item = fluid.data(
            name="target_item", shape=[None], dtype="int64")
Y
add din  
yaoxuefeng 已提交
94
        self._data_var.append(target_item)
T
tangwei 已提交
95

Y
add din  
yaoxuefeng 已提交
96 97
        target_cat = fluid.data(name="target_cat", shape=[None], dtype="int64")
        self._data_var.append(target_cat)
T
tangwei 已提交
98

Y
add din  
yaoxuefeng 已提交
99 100
        label = fluid.data(name="label", shape=[None, 1], dtype="float32")
        self._data_var.append(label)
T
tangwei 已提交
101 102 103

        mask = fluid.data(
            name="mask", shape=[None, seq_len, 1], dtype="float32")
Y
add din  
yaoxuefeng 已提交
104
        self._data_var.append(mask)
T
tangwei 已提交
105

Y
add din  
yaoxuefeng 已提交
106 107 108
        target_item_seq = fluid.data(
            name="target_item_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(target_item_seq)
T
tangwei 已提交
109

Y
add din  
yaoxuefeng 已提交
110 111 112 113 114 115
        target_cat_seq = fluid.data(
            name="target_cat_seq", shape=[None, seq_len], dtype="int64")
        self._data_var.append(target_cat_seq)

        if self.use_DataLoader:
            self._data_loader = fluid.io.DataLoader.from_generator(
T
tangwei 已提交
116 117 118 119 120
                feed_list=self._data_var,
                capacity=10000,
                use_double_buffer=False,
                iterable=False)

Y
add din  
yaoxuefeng 已提交
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
        hist_item_emb = fluid.embedding(
            input=hist_item_seq,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        hist_cat_emb = fluid.embedding(
            input=hist_cat_seq,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        target_item_emb = fluid.embedding(
            input=target_item,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        target_cat_emb = fluid.embedding(
            input=target_cat,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        target_item_seq_emb = fluid.embedding(
            input=target_item_seq,
            size=[item_count, self.item_emb_size],
            param_attr=item_emb_attr,
            is_sparse=self.is_sparse)

        target_cat_seq_emb = fluid.embedding(
            input=target_cat_seq,
            size=[cat_count, self.cat_emb_size],
            param_attr=cat_emb_attr,
            is_sparse=self.is_sparse)

        item_b = fluid.embedding(
            input=target_item,
            size=[item_count, 1],
            param_attr=fluid.initializer.Constant(value=0.0))

T
tangwei 已提交
162 163
        hist_seq_concat = fluid.layers.concat(
            [hist_item_emb, hist_cat_emb], axis=2)
Y
add din  
yaoxuefeng 已提交
164 165 166 167 168 169 170
        target_seq_concat = fluid.layers.concat(
            [target_item_seq_emb, target_cat_seq_emb], axis=2)
        target_concat = fluid.layers.concat(
            [target_item_emb, target_cat_emb], axis=1)

        out = self.din_attention(hist_seq_concat, target_seq_concat, mask)
        out_fc = fluid.layers.fc(name="out_fc",
T
tangwei 已提交
171 172 173
                                 input=out,
                                 size=self.item_emb_size + self.cat_emb_size,
                                 num_flatten_dims=1)
Y
add din  
yaoxuefeng 已提交
174 175 176
        embedding_concat = fluid.layers.concat([out_fc, target_concat], axis=1)

        fc1 = fluid.layers.fc(name="fc1",
T
tangwei 已提交
177 178 179
                              input=embedding_concat,
                              size=80,
                              act=self.act)
Y
add din  
yaoxuefeng 已提交
180 181 182 183
        fc2 = fluid.layers.fc(name="fc2", input=fc1, size=40, act=self.act)
        fc3 = fluid.layers.fc(name="fc3", input=fc2, size=1)
        logit = fc3 + item_b

T
tangwei 已提交
184 185 186
        loss = fluid.layers.sigmoid_cross_entropy_with_logits(
            x=logit, label=label)

Y
add din  
yaoxuefeng 已提交
187 188 189 190 191 192 193
        avg_loss = fluid.layers.mean(loss)
        self._cost = avg_loss

        self.predict = fluid.layers.sigmoid(logit)
        predict_2d = fluid.layers.concat([1 - self.predict, self.predict], 1)
        label_int = fluid.layers.cast(label, 'int64')
        auc_var, batch_auc_var, _ = fluid.layers.auc(input=predict_2d,
T
tangwei 已提交
194 195
                                                     label=label_int,
                                                     slide_steps=0)
Y
add din  
yaoxuefeng 已提交
196 197 198 199
        self._metrics["AUC"] = auc_var
        self._metrics["BATCH_AUC"] = batch_auc_var

    def optimizer(self):
T
tangwei 已提交
200 201
        learning_rate = envs.get_global_env("hyper_parameters.learning_rate",
                                            None, self._namespace)
Y
add din  
yaoxuefeng 已提交
202 203 204 205 206
        optimizer = fluid.optimizer.Adam(learning_rate, lazy_mode=True)
        return optimizer

    def infer_net(self, parameter_list):
        self.deepfm_net()