model.py 3.9 KB
Newer Older
M
malin10 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

import paddle.fluid as fluid

17
from paddlerec.core.utils import envs
C
Chengmo 已提交
18
from paddlerec.core.model import ModelBase
M
malin10 已提交
19 20 21 22 23 24


class Model(ModelBase):
    def __init__(self, config):
        ModelBase.__init__(self, config)

M
malin10 已提交
25
    def _init_hyper_parameters(self):
M
malin10 已提交
26 27
        self.trigram_d = envs.get_global_env("hyper_parameters.trigram_d")
        self.neg_num = envs.get_global_env("hyper_parameters.neg_num")
M
malin10 已提交
28 29
        self.hidden_layers = envs.get_global_env("hyper_parameters.fc_sizes")
        self.hidden_acts = envs.get_global_env("hyper_parameters.fc_acts")
M
malin10 已提交
30 31
        self.learning_rate = envs.get_global_env(
            "hyper_parameters.learning_rate")
Y
yinhaofeng 已提交
32
        self.slice_end = envs.get_global_env("hyper_parameters.slice_end")
M
malin10 已提交
33 34 35

    def input_data(self, is_infer=False, **kwargs):
        query = fluid.data(
M
malin10 已提交
36
            name="query",
M
malin10 已提交
37
            shape=[-1, self.trigram_d],
M
malin10 已提交
38 39
            dtype='float32',
            lod_level=0)
M
malin10 已提交
40
        doc_pos = fluid.data(
T
tangwei 已提交
41
            name="doc_pos",
M
malin10 已提交
42
            shape=[-1, self.trigram_d],
T
tangwei 已提交
43 44
            dtype='float32',
            lod_level=0)
M
malin10 已提交
45

M
malin10 已提交
46 47 48 49
        if is_infer:
            return [query, doc_pos]

        doc_negs = [
T
tangwei 已提交
50 51
            fluid.data(
                name="doc_neg_" + str(i),
M
malin10 已提交
52
                shape=[-1, self.trigram_d],
T
tangwei 已提交
53
                dtype="float32",
M
malin10 已提交
54
                lod_level=0) for i in range(self.neg_num)
T
tangwei 已提交
55
        ]
M
malin10 已提交
56
        return [query, doc_pos] + doc_negs
T
for mat  
tangwei 已提交
57

M
malin10 已提交
58
    def net(self, inputs, is_infer=False):
M
malin10 已提交
59 60
        def fc(data, hidden_layers, hidden_acts, names):
            fc_inputs = [data]
T
for mat  
tangwei 已提交
61
            for i in range(len(hidden_layers)):
T
tangwei 已提交
62 63 64 65
                xavier = fluid.initializer.Xavier(
                    uniform=True,
                    fan_in=fc_inputs[-1].shape[1],
                    fan_out=hidden_layers[i])
T
for mat  
tangwei 已提交
66 67 68 69 70 71 72 73 74
                out = fluid.layers.fc(input=fc_inputs[-1],
                                      size=hidden_layers[i],
                                      act=hidden_acts[i],
                                      param_attr=xavier,
                                      bias_attr=xavier,
                                      name=names[i])
                fc_inputs.append(out)
            return fc_inputs[-1]

M
malin10 已提交
75
        query_fc = fc(inputs[0], self.hidden_layers, self.hidden_acts,
T
tangwei 已提交
76
                      ['query_l1', 'query_l2', 'query_l3'])
Y
yinhaofeng 已提交
77

M
malin10 已提交
78
        doc_pos_fc = fc(inputs[1], self.hidden_layers, self.hidden_acts,
T
tangwei 已提交
79
                        ['doc_pos_l1', 'doc_pos_l2', 'doc_pos_l3'])
M
malin10 已提交
80
        R_Q_D_p = fluid.layers.cos_sim(query_fc, doc_pos_fc)
M
malin10 已提交
81 82

        if is_infer:
M
malin10 已提交
83
            self._infer_results["query_doc_sim"] = R_Q_D_p
M
malin10 已提交
84 85 86
            return

        R_Q_D_ns = []
M
malin10 已提交
87 88 89 90 91 92
        for i in range(len(inputs) - 2):
            doc_neg_fc_i = fc(
                inputs[i + 2], self.hidden_layers, self.hidden_acts, [
                    'doc_neg_l1_' + str(i), 'doc_neg_l2_' + str(i),
                    'doc_neg_l3_' + str(i)
                ])
M
malin10 已提交
93
            R_Q_D_ns.append(fluid.layers.cos_sim(query_fc, doc_neg_fc_i))
M
malin10 已提交
94
        concat_Rs = fluid.layers.concat(input=[R_Q_D_p] + R_Q_D_ns, axis=-1)
T
for mat  
tangwei 已提交
95 96
        prob = fluid.layers.softmax(concat_Rs, axis=1)

T
tangwei 已提交
97
        hit_prob = fluid.layers.slice(
Y
yinhaofeng 已提交
98
            prob, axes=[0, 1], starts=[0, 0], ends=[self.slice_end, 1])
M
malin10 已提交
99
        loss = -fluid.layers.reduce_sum(fluid.layers.log(hit_prob))
M
malin10 已提交
100 101 102
        avg_cost = fluid.layers.mean(x=loss)
        self._cost = avg_cost
        self._metrics["LOSS"] = avg_cost