model.py 5.4 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 18
from paddlerec.core.utils import envs
from paddlerec.core.model import Model as ModelBase
M
malin10 已提交
19 20 21 22 23 24 25


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

    def input(self):
T
tangwei 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        TRIGRAM_D = envs.get_global_env("hyper_parameters.TRIGRAM_D", None,
                                        self._namespace)

        Neg = envs.get_global_env("hyper_parameters.NEG", None,
                                  self._namespace)

        self.query = fluid.data(
            name="query", shape=[-1, TRIGRAM_D], dtype='float32', lod_level=0)
        self.doc_pos = fluid.data(
            name="doc_pos",
            shape=[-1, TRIGRAM_D],
            dtype='float32',
            lod_level=0)
        self.doc_negs = [
            fluid.data(
                name="doc_neg_" + str(i),
                shape=[-1, TRIGRAM_D],
                dtype="float32",
                lod_level=0) for i in range(Neg)
        ]
M
malin10 已提交
46 47 48 49 50 51 52
        self._data_var.append(self.query)
        self._data_var.append(self.doc_pos)
        for input in self.doc_negs:
            self._data_var.append(input)

        if self._platform != "LINUX":
            self._data_loader = fluid.io.DataLoader.from_generator(
T
tangwei 已提交
53 54 55 56
                feed_list=self._data_var,
                capacity=64,
                use_double_buffer=False,
                iterable=False)
M
malin10 已提交
57 58

    def net(self, is_infer=False):
T
tangwei 已提交
59 60 61 62
        hidden_layers = envs.get_global_env("hyper_parameters.fc_sizes", None,
                                            self._namespace)
        hidden_acts = envs.get_global_env("hyper_parameters.fc_acts", None,
                                          self._namespace)
T
for mat  
tangwei 已提交
63

M
malin10 已提交
64 65
        def fc(data, hidden_layers, hidden_acts, names):
            fc_inputs = [data]
T
for mat  
tangwei 已提交
66
            for i in range(len(hidden_layers)):
T
tangwei 已提交
67 68 69 70
                xavier = fluid.initializer.Xavier(
                    uniform=True,
                    fan_in=fc_inputs[-1].shape[1],
                    fan_out=hidden_layers[i])
T
for mat  
tangwei 已提交
71 72 73 74 75 76 77 78 79
                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]

T
tangwei 已提交
80 81 82 83
        query_fc = fc(self.query, hidden_layers, hidden_acts,
                      ['query_l1', 'query_l2', 'query_l3'])
        doc_pos_fc = fc(self.doc_pos, hidden_layers, hidden_acts,
                        ['doc_pos_l1', 'doc_pos_l2', 'doc_pos_l3'])
T
for mat  
tangwei 已提交
84
        self.R_Q_D_p = fluid.layers.cos_sim(query_fc, doc_pos_fc)
M
malin10 已提交
85 86 87 88 89

        if is_infer:
            return

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

T
tangwei 已提交
100 101
        hit_prob = fluid.layers.slice(
            prob, axes=[0, 1], starts=[0, 0], ends=[4, 1])
M
malin10 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        loss = -fluid.layers.reduce_sum(fluid.layers.log(hit_prob))
        self.avg_cost = fluid.layers.mean(x=loss)

    def infer_results(self):
        self._infer_results['query_doc_sim'] = self.R_Q_D_p

    def avg_loss(self):
        self._cost = self.avg_cost

    def metrics(self):
        self._metrics["LOSS"] = self.avg_cost

    def train_net(self):
        self.input()
        self.net(is_infer=False)
        self.avg_loss()
        self.metrics()

    def optimizer(self):
T
tangwei 已提交
121 122
        learning_rate = envs.get_global_env("hyper_parameters.learning_rate",
                                            None, self._namespace)
M
malin10 已提交
123 124 125 126
        optimizer = fluid.optimizer.SGD(learning_rate)
        return optimizer

    def infer_input(self):
T
tangwei 已提交
127 128 129 130 131 132 133 134 135
        TRIGRAM_D = envs.get_global_env("hyper_parameters.TRIGRAM_D", None,
                                        self._namespace)
        self.query = fluid.data(
            name="query", shape=[-1, TRIGRAM_D], dtype='float32', lod_level=0)
        self.doc_pos = fluid.data(
            name="doc_pos",
            shape=[-1, TRIGRAM_D],
            dtype='float32',
            lod_level=0)
M
malin10 已提交
136 137
        self._infer_data_var = [self.query, self.doc_pos]

T
for mat  
tangwei 已提交
138
        self._infer_data_loader = fluid.io.DataLoader.from_generator(
T
tangwei 已提交
139 140 141 142
            feed_list=self._infer_data_var,
            capacity=64,
            use_double_buffer=False,
            iterable=False)
T
for mat  
tangwei 已提交
143

M
malin10 已提交
144
    def infer_net(self):
T
for mat  
tangwei 已提交
145
        self.infer_input()
M
malin10 已提交
146
        self.net(is_infer=True)
T
for mat  
tangwei 已提交
147
        self.infer_results()